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

Flask实现登录按钮跳转login.html表单并对接MySQL Workbench

Flask Login Flow + MySQL Data Storage Guide

Hey there! Let's walk through getting your login button to redirect to the login form, then saving user input to MySQL Workbench. Here's how to do it step by step:

1. Confirm Your Project Structure

You already have the templates folder set up, so make sure your files are organized like this (it keeps things clean and Flask-friendly):

your_flask_app/
├── app.py
└── templates/
    ├── index.html
    └── login.html

2. Set Up Flask Routes for Navigation & Data Handling

First, let's write the core Flask code to handle the button redirect and save form data to MySQL. Here's the full app.py code:

from flask import Flask, render_template, request
import mysql.connector

app = Flask(__name__)

# Route for your homepage (loads index.html)
@app.route('/')
def index():
    return render_template('index.html')

# Route for login page: handles showing the form (GET) and submitting data (POST)
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        # User clicked the login button, so render the login form
        return render_template('login.html')
    elif request.method == 'POST':
        # Grab the data the user entered in the form
        username = request.form['username']
        password = request.form['password']
        
        # Save the data to MySQL (we'll define this function next)
        save_user_to_db(username, password)
        # You can replace this message with a redirect to the homepage or a success page
        return "Login details saved successfully! Check your MySQL database."

def save_user_to_db(username, password):
    # Update these values to match your MySQL Workbench credentials
    db_connection = mysql.connector.connect(
        host="localhost",  # Usually localhost if MySQL is on your local machine
        user="your_mysql_username",  # e.g., root
        password="your_mysql_password",
        database="flask_login_db"  # We'll create this database in MySQL next
    )
    cursor = db_connection.cursor()

    # Insert query - make sure your table matches these fields
    insert_query = "INSERT INTO users (username, password) VALUES (%s, %s)"
    user_data = (username, password)
    cursor.execute(insert_query, user_data)

    # Commit changes to the database and close connections
    db_connection.commit()
    cursor.close()
    db_connection.close()

if __name__ == '__main__':
    app.run(debug=True)

3. Update Your HTML Files

index.html (Add the Login Button)

Add a button that links to the /login route. You can use either an anchor tag or a form—here are both options:

<!DOCTYPE html>
<html>
<head>
    <title>Homepage</title>
</head>
<body>
    <h1>Welcome to the Main Page</h1>
    <!-- Option 1: Simple anchor tag styled as a button -->
    <a href="/login" style="padding: 8px 16px; background: #2563eb; color: white; text-decoration: none; border-radius: 4px;">Login</a>

    <!-- Option 2: Form with a submit button (if you prefer this approach) -->
    <!-- <form action="/login" method="GET">
        <button type="submit" style="padding: 8px 16px;">Login</button>
    </form> -->
</body>
</html>

login.html (Your Login Form)

Make sure the form uses method="POST" so data is sent to Flask correctly, and all input fields have a name attribute (this is how Flask reads the data):

<!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>
</head>
<body>
    <h1>Please Log In</h1>
    <form action="/login" method="POST">
        <div style="margin: 10px 0;">
            <label>Username:</label>
            <input type="text" name="username" required>
        </div>
        <div style="margin: 10px 0;">
            <label>Password:</label>
            <input type="password" name="password" required>
        </div>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

4. Prepare MySQL Workbench

Before running the app, create a database and table in MySQL Workbench to store the login data:

  1. Open MySQL Workbench and connect to your server.
  2. Run these SQL commands:
-- Create a new database
CREATE DATABASE IF NOT EXISTS flask_login_db;
USE flask_login_db;

-- Create a users table to store login details
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
);
  1. Update the save_user_to_db function in app.py with your actual MySQL username, password, and database name (we used flask_login_db here—match it if you used the same SQL).

5. Install Required Packages

Run these commands in your terminal to install Flask and the MySQL connector:

pip install flask mysql-connector-python

6. Test the Flow

  1. Run app.py—your terminal will show a local server URL (usually http://localhost:5000).
  2. Open that URL in your browser, click the Login button—you'll be taken to the login form.
  3. Fill in the username and password, submit, then check MySQL Workbench's flask_login_db database—your data should be in the users table!

Quick Note: In a production app, never store plain-text passwords. Use a hashing library like bcrypt to hash passwords before saving them. But for your basic use case, this setup works perfectly.

内容的提问来源于stack exchange,提问作者shivam thaman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:10:52