Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - Convert request.args to dict

I've been trying to figure out how to pass the request.args to sqlalchemy filter.

I thought this should work:

model.query.filter(**request.args).all()

But it's throwing the error:

TypeError: <lambda>() got an unexpected keyword argument 'userid'

When userid or any other get arg is present.

According to this post - https://stackoverflow.com/questions/19506105/flask-sqlalchemy-query-with-keyword-as-variable - you can pass a dict to the filter function.

Any ideas what I'm doing wrong?

Many thanks :)

UPDATE: Many thanks to the poster below, however now it's throwing the following error:

ProgrammingError: (ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY tblclients.clientname' at line 3") 'SELECT favourites.id AS favourites_id, favourites.userid AS favourites_userid, favourites.clientid AS favourites_clientid, favourites.last_visit AS favourites_last_visit \nFROM favourites INNER JOIN tblclients ON tblclients.clientid = favourites.clientid \nWHERE favourites.userid = %s ORDER BY tblclients.clientname' ([u'41'],)

Any ideas?

like image 372
Ben Kilah Avatar asked Oct 30 '13 10:10

Ben Kilah


People also ask

What is args in flask?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method: get(key, default=None, type=None) Return the default value if the requested data doesn't exist.

What is args get?

The args attribute is a dictionary containing arguments from the URL. The get() method is a built-in dictionary method that will “get” an item from a dictionary or return a default value ( None if key not found). In this case, it avoids a KeyError if “name” argument not found.

What is request form flask?

In the client-server architecture, the request object contains all the data that is sent from the client to the server. As we have already discussed in the tutorial, we can retrieve the data at the server side using the HTTP methods.


2 Answers

First, you have to use filter_by, not filter.

Second, Flask request.args uses a MultiDict, a dict with the values inside a list, allowing more than one value for the same key, because the same field can appear more than once in a querystring. You got the error because the SQL query got the [u'41'] when it expected only '41'. You can use request.args.to_dict() to fix that:

model.query.filter_by(**request.args.to_dict()).all()
like image 147
Pedro Werneck Avatar answered Sep 28 '22 06:09

Pedro Werneck


You can:

http://localhost:5000/filter-test?var=test

query_dict = request.args.to_dict()

print(query_dict)
{'var': 'test'}

print(query_dict['var'])
var
like image 22
eike Avatar answered Sep 28 '22 05:09

eike