简体   繁体   English

Flask使用自定义标题测试放置请求

[英]Flask Testing a put request with custom headers

Im trying to test a PUT request in my Flask app, using flasks test client. 我试图使用flasks测试客户端在我的Flask应用程序中测试PUT请求。 Everything looks good to me but i keep getting 400 BAD request. 一切对我来说看起来不错,但我不断收到400错误的要求。

I tried the same request using POSTMAN and I get the response back. 我使用POSTMAN尝试了相同的请求,并且得到了响应。

Here is the code 这是代码

 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)

Output 输出量

Response streamed [400 BAD REQUEST]

You do need to actually encode the data to JSON: 您确实需要将数据编码为JSON:

import json

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

Setting data to a dictionary treats that as a regular form request, so each key-value pair would be encoded into application/x-www-form-urlencoded or multipart/form-data content, if you had used either content type. data设置为字典会将其视为常规表单请求,因此,如果您使用了两种内容类型,则每个键值对都将被编码为application/x-www-form-urlencodedmultipart/form-data内容。 As it is, your data is entirely ignored instead. 实际上,您的数据将被完全忽略。

I think it is simpler to just pass the data using the json parameter instead of the data parameter: 我认为使用json参数而不是data参数传递数据更简单:

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

Quoting from 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. 在测试客户端方法中传递json参数会将请求数据设置为JSON序列化的对象,并将内容类型设置为application / json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM