Flask实现登录按钮跳转login.html表单并对接MySQL Workbench
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:
- Open MySQL Workbench and connect to your server.
- 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 );
- Update the
save_user_to_dbfunction inapp.pywith your actual MySQL username, password, and database name (we usedflask_login_dbhere—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
- Run
app.py—your terminal will show a local server URL (usuallyhttp://localhost:5000). - Open that URL in your browser, click the Login button—you'll be taken to the login form.
- Fill in the username and password, submit, then check MySQL Workbench's
flask_login_dbdatabase—your data should be in theuserstable!
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

