Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access form data using flask?

My login endpoint looks like

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        print request.form # debug line, see data printed below
        user = User.get(request.form['uuid'])
        if user and hash_password(request.form['password']) == user._password:
            login_user(user, remember=True)  # change remember as preference
            return redirect('/home/')
    else:
        return 'GET on login not supported'

When I test this using curl, the GET call looks like

⮀ ~PYTHONPATH ⮀ ⭠ 43± ⮀ curl http://127.0.0.1:5000/login/
GET on login not supported

but on POST, I am not able to access the form data and get HTTP 400

⮀ ~PYTHONPATH ⮀ ⭠ 43± ⮀ curl -d "{'uuid': 'admin', 'password': 'admin'}" http://127.0.0.1:5000/login/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

On the server though, my debug information prints the following

ImmutableMultiDict([("{'uuid': 'admin', 'password': 'admin'}", u'')])

where I do print request.form. I am not able to understand where I am doing wrong

like image 787
daydreamer Avatar asked Apr 06 '13 20:04

daydreamer


People also ask

How do I access data from a form Flask?

You can get form data from Flask's request object with the form attribute: from flask import Flask, request app = Flask(__name__) @app. route('/', methods=['GET', 'POST']) def index(): data = request.

How do I send form data in Flask?

Python for web development using Flask html) which has a form. The data filled in it is posted to the '/result' URL which triggers the result() function. The results() function collects form data present in request. form in a dictionary object and sends it for rendering to result.


1 Answers

You are not using curl correctly. Try like this:

curl -d 'uuid=admin&password=admin'

The 400 Bad Request error is the usual behavior when you try to get nonexistent keys from request.form.

Alternatively, use request.json instead of request.form and call curl like this:

curl -d '{"uuid":"admin","password":"admin"}' -H "Content-Type: application/json" 
like image 80
janos Avatar answered Sep 19 '22 22:09

janos