Handling Flask Form Posts
A form post arrives as a POST request. The view reads the method to tell GET from POST.
Make the app
This line imports Flask, request, and render_template_string together. The route below handles both methods.
from flask import Flask, request, render_template_string
app = Flask(__name__)One route, two jobs
A POST echoes the sent word. A GET shows the form instead.
@app.route("/echo", methods=["GET", "POST"])
def echo():
if request.method == "POST":
return "Posted: " + request.form.get("word", "")
return render_template_string('<form action="/echo" method="post"><input name="word"><button>Send</button></form>')Ask with GET and POST
The first ask shows the form. The second ask posts a word and prints the echo.
client = app.test_client()
print(client.get("/echo").data.decode())
print(client.post("/echo", data={"word": "hello"}).data.decode())Example
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route("/echo", methods=["GET", "POST"])
def echo():
if request.method == "POST":
return "Posted: " + request.form.get("word", "")
return render_template_string('<form action="/echo" method="post"><input name="word"><button>Send</button></form>')
client = app.test_client()
print(client.get("/echo").data.decode())
print(client.post("/echo", data={"word": "hello"}).data.decode())Key points
- request.method tells the view which method arrived.
- GET shows the form, and POST reads the sent values.
- One route handles both halves of a form.
- request.form.get reads the sent value safely.
In this example, one route handles both methods. A POST reads word from the form and echoes it. A GET renders the form. The test client asks with GET first, then posts hello, and the prints show the form and the echo.
Note
A GET to the route must not read form data.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a view tell a POST from a GET?