Python Flask and Psycopg -- Query string request.get in WHERE

245 views Asked by At

What is the correct way to pass query string variables in flask to psycopg as a parameter in a WHERE clause?

Specifically, if the variable is not set, I do not want the variable added to the WHERE clause:

 id = int(request.args.get('id'))
 cur.execute("SELECT * FROM data WHERE id = %s;", id)

If id is None, I want the SQL with no WHERE clause:

SELECT * FROM data

Is the only way to do this is with an if statement?

1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

Just issue a different query if no (valid) id query parameter was provided:

id = request.args.get('id', type=int)
if id is not None:
    cur.execute("SELECT * FROM data WHERE id = %s", (id,))
else:
    # No (valid) id given, give everything
    cur.execute("SELECT * FROM data")

Note that I used the type keyword argument for the MultiDict.get() method; the method returns a default value (None unless specified otherwise via the default argument) if the key is missing or can't be converted to an integer.