Record#
- Yesterday's study was about building form forms in HTML, which was very simple. The final exercise was to write a user login page and form.
- Today's study is about linking Flask and form together, using Flask's request function to get the data submitted by the form.
- First, import Flask and request from Flask.
- When receiving data using Flask's route, the receiving method needs to be defined. Methods can be "get" or "post".
@app.route('/path', methods=["POST"]). Then, you can userequest.formin the code to get all the form data. - The data from
request.formis in dictionary format. After assigning it to a variable, it can be used normally in the code. For example:form['username']. - Today's exercise is to add validation functionality based on yesterday's exercise. If the data is consistent, 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)
Translation: