Python 在 Flask 中获取数据 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43218413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:39:40  来源:igfitidea点击:

Get Data JSON in Flask

pythonjsoncurlflaskcmd

提问by BrunoCX92

Even following many example here & there, i can't get my API work in POST Method. Here the code about it :

即使在这里和那里遵循许多示例,我也无法在 POST 方法中使用我的 API。这里是关于它的代码:

from flask import Flask, jsonify, request

@app.route('/api/v1/lists', methods=['POST'])
def add_entry():
    print("p0")
    content = request.get_json()
    appname = content.get('title')
    print(content)
    print(appname)

When i query with curl (i'm running it on Windows):

当我使用 curl 查询时(我在 Windows 上运行它):

curl.exe -i -H "Content-Type: application/json" -X POST -d '{"title":"titi"}' http://localhost:5000/api/v1/lists

curl.exe -i -H "Content-Type: application/json" -X POST -d '{"title":"titi"}' http://localhost:5000/api/v1/lists

curl.exe -i -H "Content-Type: application/json" -X POST -d "{"""title""":"""Read a book"""}" http://localhost:5000/api/v1/lists

curl.exe -i -H "Content-Type: application/json" -X POST -d "{"""title""":"""读一本书"""}" http://localhost:5000/ api/v1/列表

I have always a 400 error in return:

我总是有 400 错误作为回报:

HTTP/1.0 400 BAD REQUEST Content-Type: text/html Content-Length: 192 Server: Werkzeug/0.12.1 Python/3.6.0 Date: Tue, 04 Apr 2017 21:55:29 GMT 400 Bad Request Bad Request The browser (or proxy) sent a request that this server could not understand.

HTTP/1.0 400 BAD REQUEST 内容类型:text/html 内容长度:192 服务器:Werkzeug/0.12.1 Python/3.6.0 日期:2017 年 4 月 4 日星期二 21:55:29 GMT 400 Bad Request Bad Request 浏览器(或代理)发送了此服务器无法理解的请求。

I dont see where the error is.

我没有看到错误在哪里。

Thanks for your help.

谢谢你的帮助。

回答by Farhan Ahmed

Even with the "working" code, in case of your if-block failure (when value1and value2is None) will cause the same error, since you are not handling the elsepart of the if-block. The corrected should be:

即使使用“工作”代码,如果您的 if 块失败(whenvalue1value2is None)也会导致相同的错误,因为您没有处理elseif 块的一部分。更正的应该是:

@app.route('/api/v1/list', methods=['POST'])
def add_entry():
    print("p0")
    request_json     = request.get_json()
    value1           = request_json.get('First_Name')
    value2           = request_json.get('Last_Name')
    response_content = None

    if value1 is not None and value2 is not None:
        print("p3")
        cursor.execute("INSERT INTO person (first_name,last_name) VALUES (%s,%s)", (value1, value2))
        response_content = conn.commit()

    return jsonify(response_content)

Of course you may want something better than Noneas the response.

当然,您可能想要比None响应更好的东西。

回答by Allie Fitter

Your add_entryfunction isn't returning a response. You must return somethingeven if it's just return 'OK'.

您的add_entry函数没有返回响应。你必须返回一些东西,即使它只是return 'OK'.

EDIT:You're still not returning anything. In Flaskthe Python printstatement is not the equivalent of PHP's echo. All printdoes is print to the console. You still have to return a value. If what you need is to return contentand appnameJSON encoded, then add

编辑:你仍然没有返回任何东西。在FlaskPythonprint语句中并不等同于 PHP 的echo. 所有print做的是打印到控制台。您仍然必须返回一个值。如果你需要的是返回contentappnameJSON 编码,然后添加

return json.loads({'contents': contents, 'appname': appname})

return json.loads({'contents': contents, 'appname': appname})

to the end of your function.

到你的函数结束。

And to be clear in Flask views must return a value. That Python functions implicitly return None is inconsequential. The error that's occurring is that your function has no return statment.

并且要在 Flask 视图中明确必须返回一个值。Python 函数隐式返回 None 是无关紧要的。发生的错误是您的函数没有返回语句。

回答by BrunoCX92

Here a code working in my case :

这是在我的情况下工作的代码:

@app.route('/api/v1/list', methods=['POST'])
def add_entry():
    print("p0")
    request_json = request.get_json()
    value1 = request_json.get('First_Name')
    value2 = request_json.get('Last_Name')
    if value1 is not None and value2 is not None:
        print("p3")
        cursor.execute("INSERT INTO person (first_name,last_name) VALUES (%s,%s)", (value1, value2))
        data = conn.commit()
        return jsonify(data)