0
0
Flaskframework~30 mins

Login form and verification in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Login form and verification
📖 Scenario: You are building a simple web app where users can log in with a username and password.This app will check if the username and password match a stored list of users.
🎯 Goal: Create a Flask app with a login form that verifies user credentials and shows a welcome message on success.
📋 What You'll Learn
Create a dictionary called users with exact username-password pairs
Create a Flask app with a route for /login that shows a login form
Add a variable error_message to hold login error text
Check submitted username and password against users dictionary
Show a welcome message if login is successful, or show the login form with error if not
💡 Why This Matters
🌍 Real World
Login forms are essential for websites and apps to control access and personalize user experience.
💼 Career
Understanding how to build and verify login forms is a key skill for web developers working with backend frameworks like Flask.
Progress0 / 4 steps
1
Create the users dictionary
Create a dictionary called users with these exact entries: 'alice': 'wonderland', 'bob': 'builder', 'carol': 'sunshine'.
Flask
Need a hint?

Use curly braces to create a dictionary with usernames as keys and passwords as values.

2
Set up Flask app and error message variable
Import Flask, request, and render_template_string from flask. Create a Flask app called app. Create a variable called error_message and set it to an empty string ''.
Flask
Need a hint?

Use from flask import Flask, request, render_template_string and then app = Flask(__name__).

3
Create the login route and check credentials
Create a route @app.route('/login', methods=['GET', 'POST']). Define a function login(). Inside it, check if the request method is POST. If yes, get username and password from request.form. Check if username is in users and the password matches. If correct, return a welcome message with f"Welcome, {username}!". Otherwise, set error_message to 'Invalid username or password.'. If method is GET or login fails, show a simple HTML login form with username and password fields and display error_message if any.
Flask
Need a hint?

Use @app.route with methods=['GET', 'POST']. Use request.form.get() to get form data. Use render_template_string to show the form and error message.

4
Run the Flask app
Add the code to run the Flask app only if the script is run directly: if __name__ == '__main__': and inside it call app.run(debug=true).
Flask
Need a hint?

Use the standard Flask pattern to run the app only when the script is executed directly.