[英]Self-built flask_restful api returns NULL when posted using request module
我最近一直在自學 API,就在我以為我已經開始弄清楚的時候,我遇到了這個問題:
我使用 flast_restful 構建了自己的 api:
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {"hello": "world"}
def post(self):
json_str = request.get_json()
return {"you sent": json_str}
api.add_resource(HelloWorld, "/")
if __name__ == "__main__":
app.run(debug=True)
我在控制台中運行它,然后計划使用 python 請求模塊在代碼中訪問它:
import requests
data = {"hello:": "world"}
r = requests.post("http://127.0.0.1:5000", data=data)
print(r.text)
為什么這會返回{"you sent": null}
,而不是 post 請求中指定的數據? get 請求工作,post 請求的響應碼是 200。
我認為有一些簡單的解決方法,我根本無法找到。 非常感謝任何幫助!
r = requests.post("http://127.0.0.1:5000", data=data)
這里的問題是data
沒有作為 json 發送; 默認情況下它是表單編碼的。 要正確發送它,您必須在 header 中將內容類型設置為application/json
。 你可以這樣做:
import json
headers = {'Content-type': 'application/json'}
r = requests.post("http://127.0.0.1:5000", data=json.dumps(data), headers=headers)
或者更簡單地使用 Requests 2.4.2 及更高版本:
r = requests.post("http://127.0.0.1:5000", json=data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.