[英]Flask-Restful: How to send non-json POST argument?
I have a problem making the simple (non-json) arguments work with POST. 我在使简单(非json)参数与POST一起使用时遇到问题。 Just taking the simple example from their tutorials, I can't make a unit test where the task is passing as an argument.
仅以他们的教程中的简单示例为例 ,我无法对任务作为参数传递的位置进行单元测试。 However task is never passed in. Its none.
但是,任务永远不会传递。
class TodoList(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('task', type = str)
super(TodoList, self).__init__()
def post(self):
args = self.reqparse.parse_args()
#args['task'] is None, but why?
return TODOS[args['task']], 201
Unit test: 单元测试:
def test_task(self):
rv = self.app.post('todos', data='task=test')
self.check_content_type(rv.headers)
resp = json.loads(rv.data)
eq_(rv.status_code, 201)
What am I missing please? 我想念什么?
When you use 'task=test'
test_client
do not set application/x-www-form-urlencoded
content type, because you put string to input stream. 当您使用
'task=test'
test_client
请勿设置application/x-www-form-urlencoded
内容类型,因为您将字符串放入输入流中。 So flask can't detect form and read data from form and reqparse
will return None
for any values for this case. 因此,flask无法检测到表单并从表单读取数据,因此
reqparse
对于这种情况下的任何值都将返回None
。
To fix it you must set up content type or use dict {'task': 'test'}
or tuple. 要修复它,您必须设置内容类型或使用dict
{'task': 'test'}
或元组。
Also for request testing better to use client = self.app.test_client()
instead app = self.app.test_client()
, if you use FlaskTesting.TestCase
class, then just call self.client.post
. 为了更好地进行请求测试,也可以使用
client = self.app.test_client()
代替app = self.app.test_client()
,如果使用FlaskTesting.TestCase
类,则只需调用self.client.post
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.