Get json from request flask [duplicate]

2020-06-04 03:09发布

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.

EDIT:

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

3条回答
别忘想泡老子
2楼-- · 2020-06-04 03:37

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

enter image description here

查看更多
叼着烟拽天下
3楼-- · 2020-06-04 03:44

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/json and see if that gets you where you want.

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

查看更多
Deceive 欺骗
4楼-- · 2020-06-04 03:46

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})

Retrieve the data in Flask with:

data = request.get_json()
查看更多
登录 后发表回答