![](/img/trans.png)
[英]Sending a POST request to my RESTful API(Python-Flask), but receiving a GET request
[英]Python-flask extracting values from a POST request to REST API
我正在嘗試通過 POST 請求從 JSON 有效負載中提取值:
問題1:獲取數據的更好方法是什么?
第一條路?
@app.route('/login', methods=['POST'])
def login():
if request.method == 'POST':
test = request.data
return test
或第二種方式?
@app.route('/login', methods=['POST'])
def login():
if request.method == 'POST':
test = json.loads(request.json)
return test
問題2:如何獲取特定值?
鑒於 json 有效載荷是:
{ "test": "hello world" }
我嘗試在下面編寫代碼,但不起作用。
#way1
return request.data["test"]
#error message: TypeError: string indices must be integers, not str
#way2
test["test"]
#error message: TypeError: expected string or buffer
如果要將JSON發布到Flask端點,則應使用:
一個非常重要的API注釋:
默認情況下,如果mimetype不是application / json,則此函數將返回None,但是可以由force參數覆蓋
含義......要么確保POST的MIME類型是application / JSON 或一定要設置force
選項true
一個好的設計將使它落后:
request.is_json像這樣:
@app.route('/post/', methods=['POST'])
def post():
if request.is_json:
data = request.get_json()
return jsonify(data)
else:
return jsonify(status="Request was not JSON")
Request.get_json()
解析傳入的 JSON 請求數據並返回。 默認情況下,如果mimetype
不是application/json
,則此 function 將返回None
但這可以被force
參數覆蓋。
Request.get_json(force=False, silent=False, cache=True)
例子:
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route("/login", methods = ['POST'])
def login():
req = request.get_json()
return "Hello " + req['username']
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.