Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling GET and POST in same Flask view

Tags:

python

flask

When I type request.form["name"], for example, to retrieve the name from a form submitted by POST, must I also write a separate branch that looks something like request.form.get["name"]? If I want to support both methods, need I write separate statements for all POST and all GET requests?

@app.route("/register", methods=["GET", "POST"]) def register():     """Register user.""" 

My question is tangentially related to Obtaining values of request variables using python and Flask.

like image 573
Ryan Avatar asked Feb 03 '17 07:02

Ryan


People also ask

How do you handle GET and POST IN Flask?

By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator. In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL.

How do you handle multiple requests at the same time in Flask?

By default, the server can handle multiple client requests without the programmer having to do anything special in the application. However, if you wish your application to handle a massive amount of simultaneous connections, you could make use of a suitable messaging library such as ZeroMQ.

What is the difference between G variable and session in the Flask?

session gives you a place to store data per specific browser. As a user of your Flask app, using a specific browser, returns for more requests, the session data is carried over across those requests. g on the other hand is data shared between different parts of your code base within one request cycle.


1 Answers

You can distinguish between the actual method using request.method.

I assume that you want to:

  • Render a template when the route is triggered with GET method
  • Read form inputs and register a user if route is triggered with POST

So your case is similar to the one described in the docs: Flask Quickstart - HTTP Methods

import flask app = flask.Flask('your_flask_env')  @app.route('/register', methods=['GET', 'POST']) def register():     if flask.request.method == 'POST':         username = flask.request.values.get('user') # Your form's         password = flask.request.values.get('pass') # input names         your_register_routine(username, password)     else:         # You probably don't have args at this route with GET         # method, but if you do, you can access them like so:         yourarg = flask.request.args.get('argname')         your_register_template_rendering(yourarg) 
like image 151
jbndlr Avatar answered Sep 28 '22 06:09

jbndlr