二手产品经理

二手产品经理

THIS IS RENO

form request - 79~80 days - learn Python online for 100 days

Record#

  1. 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.
  2. Today's study is about linking Flask and form together, using Flask's request function to get the data submitted by the form.
  3. First, import Flask and request from Flask.
  4. 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 use request.form in the code to get all the form data.
  5. The data from request.form is in dictionary format. After assigning it to a variable, it can be used normally in the code. For example: form['username'].
  6. 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:

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.