Flask实现HTML表单数据跨页传递及数据库存储(新手求助)
Hey there! Let's walk through how to build this feature step by step—since you're new to Flask, I'll keep things simple and break down each part clearly.
First, let's structure your app.py with the core setup. We'll use SQLite for this example (it's file-based, no extra server needed, perfect for beginners).
from flask import Flask, render_template, request import sqlite3 app = Flask(__name__) # Optional but good practice: set a secret key for future session management app.secret_key = 'your_custom_secret_key_here' # Helper function to connect to the database def get_db_connection(): conn = sqlite3.connect('clients.db') conn.row_factory = sqlite3.Row return conn # Create the clients table automatically if it doesn't exist with app.app_context(): conn = get_db_connection() conn.execute(''' CREATE TABLE IF NOT EXISTS clients ( id INTEGER PRIMARY KEY AUTOINCREMENT, full_name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, phone TEXT ) ''') conn.commit() conn.close()
client_signup.html) Create a templates folder in your project root, then add this HTML file. The form sends data via POST to our upcoming /signup route.
<!DOCTYPE html> <html> <head> <title>Client Signup</title> </head> <body> <h1>Sign Up as a Client</h1> <form method="POST" action="/signup"> <label for="full_name">Full Name:</label> <input type="text" id="full_name" name="full_name" required><br><br> <label for="email">Email:</label> <input type="email" id="email" name="email" required><br><br> <label for="phone">Phone Number:</label> <input type="tel" id="phone" name="phone"><br><br> <button type="submit">Submit</button> </form> </body> </html>
app.py This route handles three key tasks: grabbing form data, inserting it into the database, and passing the data to the next page for display.
@app.route('/') def show_signup_form(): return render_template('client_signup.html') @app.route('/signup', methods=['POST']) def process_signup(): # Extract data from the submitted form full_name = request.form['full_name'] email = request.form['email'] phone = request.form.get('phone', '') # Use get() to handle optional fields gracefully # Insert data into the database conn = get_db_connection() try: # Use parameterized queries to avoid SQL injection attacks conn.execute(''' INSERT INTO clients (full_name, email, phone) VALUES (?, ?, ?) ''', (full_name, email, phone)) conn.commit() except sqlite3.IntegrityError: # Handle duplicate email errors (since we set email as UNIQUE in the table) return "Oops! This email is already registered. Try a different one." finally: conn.close() # Pass the submitted data to the result page return render_template('client_profile.html', full_name=full_name, email=email, phone=phone)
client_profile.html) This page uses Flask's Jinja2 templating to display the data we passed from the /signup route.
<!DOCTYPE html> <html> <head> <title>Client Profile</title> </head> <body> <h1>Welcome, {{ full_name }}!</h1> <h2>Your Signup Details:</h2> <ul> <li>Email: {{ email }}</li> <li>Phone Number: {% if phone %}{{ phone }}{% else %}Not provided{% endif %}</li> </ul> <p>Your information has been successfully saved to our database.</p> </body> </html>
- Install Flask if you haven't already:
pip install flask - Run your app with
flask run - Visit
http://localhost:5000in your browser, fill out the form, and submit—you'll see your data on the profile page, and it will be stored inclients.db!
内容的提问来源于stack exchange,提问作者Jay Desai

