Flask 使用自定义 headers 测试放置请求
Flask Testing a put request with custom headers
我正在尝试使用 Flask 测试客户端在我的 Flask 应用程序中测试 PUT 请求。
一切对我来说都很好,但我不断收到 400 BAD 请求。
我使用 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)
输出
Response streamed [400 BAD REQUEST]
您确实需要将数据实际编码为 JSON:
import json
with app.test_client() as client:
api_response = client.put(api, data=json.dumps(data), headers=headers)
将 data
设置为字典会将其视为常规表单请求,因此每个 key-value 对将被编码为 application/x-www-form-urlencoded
或 multipart/form-data
内容,如果使用任一内容类型。事实上,您的数据将被完全忽略。
我认为使用 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.
我正在尝试使用 Flask 测试客户端在我的 Flask 应用程序中测试 PUT 请求。 一切对我来说都很好,但我不断收到 400 BAD 请求。
我使用 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)
输出
Response streamed [400 BAD REQUEST]
您确实需要将数据实际编码为 JSON:
import json
with app.test_client() as client:
api_response = client.put(api, data=json.dumps(data), headers=headers)
将 data
设置为字典会将其视为常规表单请求,因此每个 key-value 对将被编码为 application/x-www-form-urlencoded
或 multipart/form-data
内容,如果使用任一内容类型。事实上,您的数据将被完全忽略。
我认为使用 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.