Flask Testing a put request with custom headers

孤街浪徒 提交于 2019-12-11 03:14:50

问题


Im trying to test a PUT request in my Flask app, using flasks test client. Everything looks good to me but i keep getting 400 BAD request.

I tried the same request using POSTMAN and I get the response back.

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]

回答1:


You do need to actually encode the data to 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. As it is, your data is entirely ignored instead.




回答2:


I think it is simpler to just pass the data using the json parameter instead of the data parameter:

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.



来源:https://stackoverflow.com/questions/41653058/flask-testing-a-put-request-with-custom-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!