简体   繁体   中英

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?

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 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 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'}

使用request对象 ,您应该能够使用request.args.get('key', 'default')获得所需的参数。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM