Issue
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?
Solution
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'}
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.