Handling GET and POST in same Flask view

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


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... 

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....... :)

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)

Tags:

Python

Flask