二手产品经理

二手产品经理

THIS IS RENO

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

Record#

  1. 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.
  2. Today I learned how to link Flask and forms together, and use Flask's request function to retrieve data submitted from the form.
  3. First, import Flask and request from Flask.
  4. 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 use request.form in your code to retrieve all the form data.
  5. 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'].
  6. 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)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.