44

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.

Community
  • 1
  • 1
Ryan
  • 1,312
  • 3
  • 20
  • 40

5 Answers5

109

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)
normanius
  • 8,629
  • 7
  • 53
  • 83
jbndlr
  • 4,965
  • 2
  • 21
  • 31
  • 1
    Thanks for the reply! You anticipated parts of the method that I didn't even think to mention, hence you get the accepted answer check mark. It'll be interesting trying out both this and the above approach though. Each has its own appeal. Thanks again! – Ryan Feb 03 '17 at 07:31
  • 3
    Note for those on v1.0: The import has changed to "from flask import request" and "flask." has been removed from the variables within the method making it: "if request.method == 'POST':". (http://flask.pocoo.org/docs/1.0/quickstart/#http-methods) – Flipper Sep 17 '18 at 16:17
  • 1
    It would be nice to mention if the opposite of splitting GET and POST into separate view functions is also possible in Flask? (Which may be nicer, because such dual-purpose view functions violate the single responsibility principle.) – bluenote10 Apr 04 '20 at 11:06
  • this will not work if you decide to go with flask-security – Vaidøtas I. Dec 02 '21 at 22:25
8

Here is the example in which you can easily find the way to use POST, GET methods and use the same way to add other curd operations as well..

#libraries to include

import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
def question():
# request.args is to get urls arguments 


    if request.method == 'GET':
        start = request.args.get('start', default=0, type=int)
        limit_url = request.args.get('limit', default=20, type=int)
        questions = mongo.db.questions.find().limit(limit_url).skip(start);
        data = [doc for doc in questions]
        return jsonify(isError= False,
                    message= "Success",
                    statusCode= 200,
                    data= data), 200

    # request.form to get form parameter

    if request.method == 'POST':
        average_time = request.form.get('average_time')
        choices = request.form.get('choices')
        created_by = request.form.get('created_by')
        difficulty_level = request.form.get('difficulty_level')
        question = request.form.get('question')
        topics = request.form.get('topics')

        ##Do something like insert in DB or Render somewhere etc. it's up to you....... :)
vitaliis
  • 4,082
  • 5
  • 18
  • 40
Shahzaib Ali
  • 382
  • 5
  • 10
3

You could treat "POST" method by calling the validate_on_submit() to check if the form is submitted with valid data, otherwise your function will response to GET request by default. Your function will be like this:

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user."""
    form = SomeForm() 
    # treat POST request 
    if form.validate_on_submit():
       # do something ... 
       # return redirect ... 


    # else response to GET request
    # return render_template... 
vvvvv
  • 25,404
  • 19
  • 49
  • 81
thangtn
  • 856
  • 6
  • 7
3
from flask import Flask, jsonify, request,render_template
import os

app = Flask(__name__)


@app.route('/', methods=['GET'])
def _get_():
    data = request.get_data()
    return data
@app.route('/', methods=['POST'])
def _post_():
    data = request.get_data()
    return data
if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(debug=True, host='0.0.0.0', port=port)

enter image description here

Robert A
  • 337
  • 4
  • 3
0

In my case I have returned the method which returns jsonify if the request is POST and if request is GET it is returning the HTML/template.

obj = user_model()
@app.route("/user/getall", methods=["GET","POST"])
def user_getall_controller():
    if request.method == 'POST':
        return obj.user_getall_model()
    if request.method == 'GET':
        return render_template('getallusers.html')
Avinash
  • 159
  • 2
  • 9