烧瓶 - 如何从JSON GET请求获取参数 [英] flask - how to get parameters from a JSON GET request

查看:167
本文介绍了烧瓶 - 如何从JSON GET请求获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

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


$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b打印任务

显示为

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



要获得任务值,
$

  request.args.getlist('task')

我得到 [] 而不是 hello 。关于如何从这里挖出hello的任何想法?

解决方案

忽略 request.args 这里;您在这里没有表单编码查询参数。



使用 request.query_string 取而代之,将高速缓冲存储器断路器(& ; _ =< random number> ),解码URL引用并将结果提供给 json.loads()

  from urllib import从容器中导入
导入json

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

演示:

 >>> 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'任务':u'hello'}


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

这篇关于烧瓶 - 如何从JSON GET请求获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆