我在一个Flask应用程序中编写了代码,使用JSON格式的请求,可以像这样获取JSON对象:
Request = request.get_json()
目前这个功能运作良好,但我想使用Python的unittest模块创建单元测试,而我很难找到一种方法来发送包含JSON的请求。
response=self.app.post('/test_function',
data=json.dumps(dict(foo = 'bar')))
这给了我:
>>> request.get_data()
'{"foo": "bar"}'
>>> request.get_json()
None
Flask似乎有一个JSON参数,您可以在POST请求中设置json = dict(foo ='bar'),但我不知道如何使用unittest模块实现。
request.data
包含什么内容?通常当 JSON 解析由于错误的输入而失败时,它会默默地失败并返回None
,因此原始输入数据可能不是 JSON。 - Benoît Latinier