Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get json from request flask [duplicate]

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

like image 363
lads Avatar asked Mar 30 '17 19:03

lads


People also ask

How do I access json data in flask?

You need to set the request content type to application/json for the . json property and . get_json() method (with no arguments) to work as either will produce None otherwise.

What does flask request Get_json do?

Parses the incoming JSON request data and returns it. By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter.


1 Answers

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()
like image 184
Alex Avatar answered Sep 20 '22 15:09

Alex