从请求瓶获取json

问题描述:

客户代码:

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)

服务器代码:

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.

我也尝试使用:

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

request.form['user']

当我打印内容时,我有:<请求' http://127.0.0.1:5050/login '[POST]>.所以我无法找到客户端发送的json.

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.

我确实添加了json.dumps并使用了request.get_json()并有效

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

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

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.

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

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

Retrieve the data in Flask with:

data = request.get_json()