Skip to content
Advertisement

List of query params with Flask request.args

I am trying to pass comma separated query parameters to a Flask endpoint.

An example URI would be:

localhost:3031/someresource#?status=1001,1002,1003

Looking at the return of request.args or request.args.getlist('status') I see that I only get a string.

ipdb> pp request.args
ImmutableMultiDict([('status', '1001,1002,1003')])
ipdb> request.args.getlist('status')
['1001,1002,1003']

I know I can split the string by comma but that feels hacky. Is there a more idiomatic way to handle this in Flask? Or are my query params wrong format?

Solution
Since Flask does not directly support comma separated query params, I put this in in my base controller to support comma-separated or duplicate query params on all endpoints.

request_data = {}
params = request.args.getlist('status') or request.form.getlist('status')
if len(params) == 1 and ',' in params[0]:
    request_data['status'] = comma_separated_params_to_list(params[0])})
else:
    request_data['status'] = params
def comma_separated_params_to_list(param):
    result = []
    for val in param.split(','):
        if val:
            result.append(val)
    return result

Advertisement

Answer

This is what you might want here:

request.args.to_dict(flat=False)

flat is True by default, so by setting it to False, you allow it to return a dict with values inside a list when there’s more than one.

According to to_dict documentation:

 to_dict(flat=True)

    Return the contents as regular dict. If flat is True
    the returned dict will only have the first item present, if flat is False
    all values will be returned as lists.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement