简体   繁体   English

Python-flask 从 POST 请求中提取值到 REST API

[英]Python-flask extracting values from a POST request to REST API

I am trying to extract values from a JSON payload by POST request:我正在尝试通过 POST 请求从 JSON 有效负载中提取值:

Question 1: What is a better way to get the data?问题1:获取数据的更好方法是什么?

First Way?第一条路?

@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        test = request.data
        return test

or Second Way?或第二种方式?

@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        test = json.loads(request.json)
        return test

Question 2: How do I get a specific value?问题2:如何获取特定值?

Given the json payload is:鉴于 json 有效载荷是:

{ "test": "hello world" }

I tried doing code below, but does not work.我尝试在下面编写代码,但不起作用。

#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

If you are posting JSON to a flask endpoint you should use: 如果要将JSON发布到Flask端点,则应使用:

request.get_json() request.get_json()

A very important API note: 一个非常重要的API注释:

By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter 默认情况下,如果mimetype不是application / json,则此函数将返回None,但是可以由force参数覆盖

Meaning... either make sure the mimetype of the POST is application/json OR be sure to set the force option to true 含义......要么确保POST的MIME类型是application / JSON 一定要设置force选项true

A good design would put this behind: 一个好的设计将使它落后:

request.is_json like this: 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() parses the incoming JSON request data and returns it. Request.get_json()解析传入的 JSON 请求数据并返回。 By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter.默认情况下,如果mimetype不是application/json ,则此 function 将返回None但这可以被force参数覆盖。

Request.get_json(force=False, silent=False, cache=True) 

Example:例子:

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.

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