从HTML页面传递数据库账号密码到Flask应用实现数据库连接
Hey there! Let's work through this issue together. The main problem with your current code is that you're trying to access request.form outside of a request context—this will throw an error because request only exists when a client makes a request to your Flask app. You can't set database config variables globally like that; instead, you need to handle the form submission in a route, then configure the MySQL instance there.
Here's the Corrected Approach
1. Basic Flask Setup (Global Scope)
First, initialize your Flask app and MySQL instance without trying to access request data right away:
from flask import Flask, request, render_template from flaskext.mysql import MySQL app = Flask(__name__) mysql = MySQL() # Base config that doesn't depend on user input app.config['MYSQL_DATABASE_DB'] = 'database' app.config['MYSQL_DATABASE_HOST'] = 'localhost'
2. Route to Handle Form Submission
Create a route that displays the input form and processes the user's submission:
@app.route('/configure-db', methods=['GET', 'POST']) def configure_db(): if request.method == 'POST': # Get user input from the form try: db_username = request.form['username.db'] db_password = request.form['password.db'] # Update the app config with user input app.config['MYSQL_DATABASE_USER'] = db_username app.config['MYSQL_DATABASE_PASSWORD'] = db_password # Initialize the MySQL connection with the new config mysql.init_app(app) # Test the connection (optional but helpful) conn = mysql.connect() cursor = conn.cursor() cursor.execute("SELECT 1") result = cursor.fetchone() conn.close() return "Database configuration successful!" except KeyError: return "Error: Missing username or password field in form." except Exception as e: return f"Connection failed: {str(e)}" # If GET request, show the input form return render_template('db_config_form.html')
3. HTML Form Template (templates/db_config_form.html)
Create a simple form for users to input their credentials:
<!DOCTYPE html> <html> <head> <title>Database Configuration</title> </head> <body> <h1>Enter Database Credentials</h1> <form method="POST"> <label for="username.db">Database Username:</label> <input type="text" id="username.db" name="username.db" required><br><br> <label for="password.db">Database Password:</label> <input type="password" id="password.db" name="password.db" required><br><br> <button type="submit">Configure Database</button> </form> </body> </html>
Important Notes
- Never send credentials over HTTP: Always use HTTPS in production to protect user passwords during transmission.
- Consider persistence: This approach sets the config temporarily (until the app restarts). If you need to save the config long-term, store it in a secure configuration file or encrypted database.
- Error handling: The example includes basic error handling, but you can expand it to validate input or show more user-friendly messages.
- Alternative for production: For production apps, it's better to use environment variables for database credentials instead of user input forms—this is more secure and follows best practices.
内容的提问来源于stack exchange,提问作者Vikram Karthic

