Flask测试带有定制头的put请求

2024-09-27 00:16:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的flasks应用程序中测试一个PUT请求,使用flasks测试客户端。 在我看来一切都很好,但我一直收到400个错误的请求。在

我用POSTMAN尝试了同样的请求,得到了响应。在

这是密码

 from flask import Flask 
 app = Flask(__name__) 
 data = {"filename": "/Users/resources/rovi_source_mock.csv"}
 headers = {'content-type': 'application/json'}
 api = "http://localhost:5000/ingest"
 with app.test_client() as client:
    api_response = client.put(api, data=data, headers=headers)
 print(api_response)

输出

^{pr2}$

Tags: fromclientapiapp应用程序密码客户端flask
2条回答

您确实需要将数据编码为JSON:

import json

with app.test_client() as client:
    api_response = client.put(api, data=json.dumps(data), headers=headers)

data设置为字典会将其视为常规的表单请求,因此如果您使用了其中一种内容类型,则每个键值对都将被编码为application/x-www-form-urlencoded或{}内容。事实上,你的数据被完全忽略了。在

我认为使用json参数而不是data参数传递数据会更简单:

reponse = test_client.put(
    api, 
    json=data,
)

引自here

Passing the json argument in the test client methods sets the request data to the JSON-serialized object and sets the content type to application/json.

相关问题 更多 >

    热门问题