Python-flask 从 POST REST 请求中提取值 API
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
问题二:
我如何获得特定值?
鉴于 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 发布到烧瓶端点,您应该使用:
一个非常重要的API注意事项:
By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter
意思...要么确保 POST 的 mimetype 是 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")
我正在尝试通过 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
问题二: 我如何获得特定值?
鉴于 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 发布到烧瓶端点,您应该使用:
一个非常重要的API注意事项:
By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter
意思...要么确保 POST 的 mimetype 是 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")