How to Create User Registration in Flask: Simple Guide
To create registration in
Flask, define a route with a form that collects user data, validate the input, and save it to a database. Use Flask-WTF for form handling and Werkzeug to hash passwords securely before storing.Syntax
Creating registration in Flask involves these parts:
- Route: Defines the URL where the registration form is shown and processed.
- Form: Collects user input like username, email, and password.
- Validation: Checks if inputs are correct and safe.
- Database: Saves the new user data securely.
python
from flask import Flask, render_template, request, redirect, url_for from werkzeug.security import generate_password_hash app = Flask(__name__) @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] hashed_password = generate_password_hash(password) # Save username and hashed_password to database here return redirect(url_for('login')) return render_template('register.html')
Example
This example shows a simple Flask app with a registration form that saves user data in memory and hashes the password.
python
from flask import Flask, render_template_string, request, redirect, url_for from werkzeug.security import generate_password_hash app = Flask(__name__) users = {} form_html = ''' <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Register</title></head> <body> <h2>Register</h2> <form method="POST"> <label>Username: <input type="text" name="username" required></label><br> <label>Password: <input type="password" name="password" required></label><br> <button type="submit">Register</button> </form> </body> </html> ''' @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username in users: return 'User already exists', 400 hashed_password = generate_password_hash(password) users[username] = hashed_password return redirect(url_for('success', username=username)) return render_template_string(form_html) @app.route('/success/<username>') def success(username): return f"User {username} registered successfully!" if __name__ == '__main__': app.run(debug=True)
Output
User alice registered successfully!
Common Pitfalls
Common mistakes when creating registration in Flask include:
- Not hashing passwords before saving, which risks user security.
- Not validating form inputs, allowing empty or invalid data.
- Not checking if the username already exists, causing duplicates.
- Forgetting to set
methods=['GET', 'POST']on the route, so POST requests fail.
python
from flask import Flask, request app = Flask(__name__) users = {} # Wrong: No password hashing and no duplicate check @app.route('/register', methods=['POST']) def register_wrong(): username = request.form['username'] password = request.form['password'] users[username] = password # Storing plain password return 'Registered' # Right: Hash password and check duplicates from werkzeug.security import generate_password_hash @app.route('/register', methods=['POST']) def register_right(): username = request.form['username'] password = request.form['password'] if username in users: return 'User exists', 400 users[username] = generate_password_hash(password) return 'Registered securely'
Quick Reference
Tips for Flask registration:
- Use
POSTmethod to submit forms. - Always hash passwords with
generate_password_hash. - Validate inputs to avoid empty or invalid data.
- Check for existing usernames before saving.
- Use Flask-WTF for easier form handling and validation.
Key Takeaways
Always hash passwords before saving user data to protect security.
Use POST method and validate form inputs to ensure data integrity.
Check if a username already exists to prevent duplicates.
Flask-WTF simplifies form handling and validation in Flask apps.
Keep registration routes simple and clear for easy maintenance.