Flask Form Data
Form data travels in the body of a POST request. The request.form dict holds the sent values.
Make the app
This line imports Flask and request together. The route below reads form data.
from flask import Flask, request
app = Flask(__name__)Echo the sent word
This route takes POST only. It reads word from the form and echoes it back.
@app.route("/echo", methods=["POST"])
def echo():
return "Posted: " + request.form.get("word", "")Post two words
The test client posts a form with one word each time. Each print shows the echoed word.
client = app.test_client()
print(client.post("/echo", data={"word": "hello"}).data.decode())
print(client.post("/echo", data={"word": "hi"}).data.decode())Example
from flask import Flask, request
app = Flask(__name__)
@app.route("/echo", methods=["POST"])
def echo():
return "Posted: " + request.form.get("word", "")
client = app.test_client()
print(client.post("/echo", data={"word": "hello"}).data.decode())
print(client.post("/echo", data={"word": "hi"}).data.decode())Key points
- request.form holds values sent by a form.
- form.get("word", "") returns "" when word is missing.
- POST sends data, so forms use POST.
- The test client sends form data with data={...}.
In this example, the route takes POST only and reads word from request.form. The test client posts two forms, one with hello and one with hi. The prints show the echoed word each time.
Note
Form values are always text.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does form data travel in a POST request?