spitz
spitz

Reputation: 668

flask - how to get parameters from a JSON GET request

I have a client side api that issues the following GET request:

"GET /tasks/5fe7eabd-842e-40d2-849e-409655e0891d?{%22task%22:%22hello%22,%22url%22:%22/tasks/5fe7eabd-842e-40d2-849e-409655e0891d%22}&_=1411772296171 HTTP/1.1" 200 -

Doing

task = request.args
print task

shows it to be

ImmutableMultiDict([('{"task":"hello","url":"/tasks/5fe7eabd-842e-40d2-849e-409655e0891d"}', u''), ('_', u'1411772296171')])

To get the "task" value, if I do:

  request.args.getlist('task')

I get [] instead of hello. Any ideas on how to dig out hello from this?

Upvotes: 4

Views: 12970

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125368

Ignore request.args here; you don't have a form-encoded query parameter here.

Use request.query_string instead, splitting of the cache breaker (&_=<random number>), decoding the URL quoting and feeding the result to json.loads():

from urllib.parse import unquote
from flask import json

data = json.loads(unquote(request.query_string.partition('&')[0]))
task = data.get('task')

Demo:

>>> request.query_string
'{%22task%22:%22hello%22,%22url%22:%22/tasks/5fe7eabd-842e-40d2-849e-409655e0891d%22}&_=1411772296171'
>>> from urllib.parse import unquote
>>> from flask import json
>>> unquote(request.query_string.partition('&')[0])
'{"task":"hello","url":"/tasks/5fe7eabd-842e-40d2-849e-409655e0891d"}'
>>> json.loads(unquote(request.query_string.partition('&')[0]))
{u'url': u'/tasks/5fe7eabd-842e-40d2-849e-409655e0891d', u'task': u'hello'}

Upvotes: 7

Celeo
Celeo

Reputation: 5682

Using the request object, you should be able to use request.args.get('key', 'default') to get the parameter you want.

request.args.get('task', None)

Upvotes: -2

Related Questions