【问题标题】:Flask-Restful: How to send non-json POST argument?Flask-Restful:如何发送非 json POST 参数?
【发布时间】:2013-11-23 07:47:11
【问题描述】:

我在使简单(非 json)参数与 POST 一起工作时遇到问题。只是从他们的教程中获取简单的example,我无法在任务作为参数传递的情况下进行单元测试。但是任务永远不会传入。它没有。

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

单元测试:

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)

请问我错过了什么?

【问题讨论】:

    标签: python flask flask-restful


    【解决方案1】:

    当您使用'task=test' test_client 时不要设置application/x-www-form-urlencoded 内容类型,因为您将字符串放入输入流。因此,flask 无法检测表单并从表单中读取数据,reqparse 将针对这种情况的任何值返回 None。

    要修复它,您必须设置内容类型或使用 dict {'task': 'test'} 或元组。

    对于请求测试,最好使用client = self.app.test_client() 而不是app = self.app.test_client(),如果您使用FlaskTesting.TestCase 类,则只需调用self.client.post。

    【讨论】:

    • 你的意思是'要修复它,你必须设置内容类型',我应该将它设置为{'Content-Type':'application/json'}吗?因此最好还是一起使用 json,对吧?
    • 我告诉过rv = self.client.post('/', data='task=test', content_type='application/x-www-form-urlencoded') 或rv = self.client.post('/', data={'task':'test'})。但它不是 json,它的 html 表单格式。如果你想使用 json 你必须发送 json rv = self.client.post('/', data='{"task":"test"}', content_type='application/json') 并解析 json self.reqparse.add_argument('task', type=str, location='get_json')。
    猜你喜欢
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2023-03-14
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多