The two most common HTTP methods are GET and POST. Flask can run different code from the same URL dependent on the HTTP method used. For example, in a web service with accounts, it is most convenient to route the sign in page and the sign in process through the same URL. A GET request, the same that is made when you open a URL in your browser should show the login form, while a POST request (carrying login data) should be processed separately. A route is also created to handle the DELETE and PUT HTTP method.
@app.route("/login", methods=["GET"])
def login_form():
return "This is the login form"
@app.route("/login", methods=["POST"])
def login_auth():
return "Processing your data"
@app.route("/login", methods=["DELETE", "PUT"])
def deny():
return "This method is not allowed"
To simplify the code a bit, we can import the request
package from flask.
from flask import request
@app.route("/login", methods=["GET", "POST", "DELETE", "PUT"])
def login():
if request.method == "DELETE" or request.method == "PUT":
return "This method is not allowed"
elif request.method == "GET":
return "This is the login forum"
elif request.method == "POST":
return "Processing your data"
To retrieve data from the POST request, we must use the request
package:
from flask import request
@app.route("/login", methods=["GET", "POST", "DELETE", "PUT"])
def login():
if request.method == "DELETE" or request.method == "PUT":
return "This method is not allowed"
elif request.method == "GET":
return "This is the login forum"
elif request.method == "POST":
return "Username was " + request.form["username"] + " and password was " + request.form["password"]