You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.


1. Set Up Your Flask App & Database Connection

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()

2. Build the Signup Form (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>

3. Add the Form Submission Route to 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)

4. Create the Result Page (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>

Testing the App
  1. Install Flask if you haven't already: pip install flask
  2. Run your app with flask run
  3. Visit http://localhost:5000 in your browser, fill out the form, and submit—you'll see your data on the profile page, and it will be stored in clients.db!

内容的提问来源于stack exchange,提问作者Jay Desai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:02:05