Incoming!
Today, we're going to learn how to deal with data from forms in Flask.
π To start, I've added yesterday's HTML code for my form in main.py for you already. (You're welcome!) Go take a look!
π However, at the moment, the app.route() has no method associated with it, so I need to create a route for this page to receive the data.
First, I need a new import: request.
Then I create the app.route - I also need to add an extra argument to specify the methods being received. At the moment, that's just 'post', but it does need to be ALL CAPS - POST.
Finally I define the process() subroutine that returns request.form
π Here's the new code on its own:
from Flask import Flask, request
app.route('/process', methods=["POST"])
def process():
return request.form
π And here it is as part of the whole code:
from flask import Flask, request
app = Flask(__name__)
app.route("/process", methods=["POST"])
def process():
return request.form
@app.route('/')
def index():
page = """<form method = "post" action="/process">
<p>Name: <input type="text" name="username" required> </p>
<p>Email: <input type="Email" name="email"> </p>
<p>Website: <input type="url" name="website"> </p>
<p>Age: <input type="number" name="age"> </p>
<input type="hidden" name="userID" value="232"> </p>
<p>
Fave Baldy:
<select name="baldies">
<option>David</option>
<option>Jean Luc Picard</option>
<option>Yul Brynner</option>
</select>
</p>
<button type="submit">Save Data</button>
</form>
"""
return page
app.run(host='0.0.0.0', port=81)
This will get us the data from the form in a dictionary format, like this:
Comments
Post a Comment