Every time a client communicates with a server it does so through a request. By default our Flask routes only support GET requests. These are requests for data such as what to display in a browser window. When submitting a form through a website, the form data is sent as a POST request. This type of request wants to add data to the app. Routes can handle POST requests if it is specified in the
methods argument of the
@app.route("/", methods=["GET", "POST"])
The code above shows a route that now supports both GET and POST requests. By default
methods is set to [“GET”]. When adding “POST” to a route’s
methods, be sure to include “GET” if you plan for the route to handle those requests as well.
Flask provides access to the data in the request through the
request object. Importing the
request object allows us to access everything about the requests to our app including form data and the request method such as
from flask import request
When data is sent via a form submission it can be accessed using the
form attribute of the
request object. The
form attribute is a dictionary with the form’s field names as the keys and the associated data as the values. For example, if a text input had the name
"my_text", then the data access would look like this.
text_in_field = request.form["my_text"]
Before we begin with the form data, there are a few additions in the
index() function to note regarding the gathering of form data:
- The variable
new_idis assigned an integer that’s one more than the length of the
recipesdictionary we imported form helper.py. This variable will be used as the key for the new recipe data.
if len(request.form) > 0statement makes sure there is data in the
formobject before trying to access them. Without this, a
KeyErrorwould be raised when the route is accessed and the form is not submitted.
Review the changes and run the code when you are ready.
In app.py, note the
request object has been added to the import section.
Working in the
index route and using the
request object, assign the contents of the form’s
"recipe" text field to
After you run the code feel free to try out your work by refreshing the browser. Keep in mind that not all data is processed yet so clicking on the new recipe links will raise a
Repeat the same step for the
description form data by assigning the
description field data to
The helper functions
add_instructions() are set up to add the contents of the variables
new_instructions to the data. Currently both variables are set to
Put the form data named
"instructions" into the appropriate variables so the data is added to the app.