Record#
- Yesterday I learned how to build a form in HTML, which was very simple. The final exercise was to create a user login page and form.
- Today I learned how to link Flask and forms together, and use Flask's request function to retrieve data submitted from the form.
- First, import Flask and request from Flask.
- When using Flask's route to receive data, you need to define the method for receiving the data. Use methods=["POST"] for receiving.
@app.route('/path', methods=["POST"])
. Then you can userequest.form
in your code to retrieve all the form data. - The data in
request.form
is in dictionary format. After assigning it to a variable, you can use it normally in your code. For example:form['username']
. - Today's exercise is to add validation to the previous exercise. If the data matches, display "Login Successful", otherwise display "Login Failed".
CODE#
from flask import Flask, request
app = Flask(__name__)
@app.route("/login", methods=["POST"])
def process():
uname = '1'
umail = '[email protected]'
upass = '1'
page = ""
form = request.form
if form['username'] == uname and form['email'] == umail and form[
'password'] == upass:
page += f"Welcome!"
else:
page += f"Error!"
return page
@app.route('/')
def index():
page = """<form method="post" action="/login">
<p>Name: <input type="text" name="username" required> </p>
<p>Email: <input type="Email" name="email" required> </p>
<p>Password: <input type="password" name="password" required> </p>
<button type="submit">Login</button>
</form>
"""
return page
app.run(host='0.0.0.0', port=81)