我正在使用Flask在Python中实现REST。我必须获得参数才能执行查询并返回资源。为了与REST原则保持一致,我将对此操作使用一个GET请求。
考虑到可能有很多参数,我希望通过一个conf.json文件发送它们,例如:
{"parameter": "xxx"}我通过curl执行请求
$ curl -H "Content-Type: application/json“--data @conf.json -G http://localhost:8080/resources/
通过以下操作将请求重定向到路由:
@resources.route('/resources/', methods=['GET'])
def discover():
if request.get_json():
json_data=request.get_json()
return jsonify(json_data)我回来的是:
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code 400.
<p>Message: Bad request syntax ('GET /resources/?{"parameter": "xxx"} HTTP/1.1').
<p>Error code explanation: 400 = Bad request syntax or unsupported method. </body>有人知道如何获取json数据并在请求中正确地处理它?
发布于 2016-08-16 14:58:16
request.get_json()在请求体中查找JSON数据(例如POST请求将包括什么)。您可以将JSON数据放在GET请求的URL查询字符串中。
您的curl命令发送您的JSON转义,并生成一个无效的URL,因此服务器正确地拒绝了这一点:
http://localhost:8080/resources/?{"parameter": "xxx"}例如,您不能在URL中有空格。为了正确地转义,您必须使用--data-urlencode:
$ curl --data-urlencode @conf.json -G http://localhost:8080/resources/注意,这里不需要Content-Type头;您没有任何请求正文来记录。
调整后的curl命令现在发送一个正确编码的URL:
http://localhost:8080/resources/?%7B%22parameter%22%3A%20%22xxx%22%7D%0A%0A使用request.query_string访问该数据。您还必须再次解码URL编码,然后再将其传递给json.loads()。
from urllib import unquote
json_raw_data = unquote(request.query_string)
json_data = json.loads(json_raw_data)考虑到许多‘ll服务器对他们接受URL的时间设置了限制。如果您计划以这种方式在URL中发送超过4k个字符,那么您确实需要重新考虑并使用POST请求。这是4k与JSON数据URL编码,这增加了相当大的开销。
发布于 2016-08-17 06:37:22
马蒂恩的回答是对的
$ curl --data-urlencode @conf.json -G http://localhost:8080/resources/但是您不需要使用urllib来获得带有烧瓶的args。相反,我将在我的端点上使用以下内容。
@resources.route('/resources')
def test():
args = request.args
return args.get('parameter')此外,我还将考虑使用flask_testing扩展,这样您就可以在运行中的应用程序的上下文中设置可重复的测试用例。
from flask_testing import TestCase
from app import app
class TestQueryString(TestCase):
def create_app(self): # Must be implemented
return app
def test_json_parse_args(self):
data = {
'parameter': 'value'
}
r = self.client.get('/resources', query_string=data)
self.assert200(r)
self.assertEqual(r.data, 'value')https://stackoverflow.com/questions/38978160
复制相似问题