Python 从请求烧瓶中获取 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43126956/
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:33:40  来源:igfitidea点击:

Get json from request flask

pythonjsonhttpflask

提问by lads

Client code:

客户端代码:

import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)

Server code:

服务器代码:

from flask import Flask, request, make_response

app = Flask(__name__)


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

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)

The problem is that my username and password are always None.

问题是我的用户名和密码总是无。

I also tried using:

我也尝试使用:

content = request.get_json(force = True) 
password = content['pass']

and

request.form['user']

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

当我打印内容时,我有: < Request ' http://127.0.0.1:5050/login' [POST]> 。所以我找不到从客户端发送的 json。

EDIT:

编辑:

I did add json.dumps and used request.get_json() and it worked

我确实添加了 json.dumps 并使用了 request.get_json() 并且它起作用了

回答by Alex

You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json=to send JSON data.

您发送的是表单编码数据,而不是 JSON。仅设置内容类型不会将您的请求转换为 JSON。使用json=发送JSON数据。

response = requests.post(url, json={"user": user,"pass": password})

Retrieve the data in Flask with:

使用以下命令检索 Flask 中的数据:

data = request.get_json()

回答by Afaq

I tried executing the same code that you have posted and I was able to fetch values for usernameand passwordinstead of None.

我尝试执行您发布的相同代码,并且能够获取username和 的值而password不是None.

enter image description here

在此处输入图片说明

回答by Gerad Bottorff

My initial guess is that since you aren't setting the Content-Type header in your request Flask doesn't understand that it should be able to parse the data. Try adding Content-Type header with the value application/jsonand see if that gets you where you want.

我最初的猜测是,由于您没有在请求中设置 Content-Type 标头,因此 Flask 不明白它应该能够解析数据。尝试添加带有值的 Content-Type 标头,application/json看看是否可以让您到达您想要的位置。

Another thing to note is when I hit my login page the browser sets the Content-Type header to application/x-www-form-urlencodedand encodes the data as user=asdf&passwd=asdf

另一件要注意的事情是,当我点击登录页面时,浏览器将 Content-Type 标头设置为 application/x-www-form-urlencoded并将数据编码为user=asdf&passwd=asdf