flask+mysql实现用户登录注册代码
时间: 2023-09-05 14:13:47 浏览: 223
以下是一个简单的 Flask+MySQL 实现用户登录注册的代码:
```
from flask import Flask, request, session, redirect
from flask_mysqldb import MySQL
app = Flask(__name__)
app.secret_key = 'your secret key'
mysql = MySQL(app)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'your mysql username'
app.config['MYSQL_PASSWORD'] = 'your mysql password'
app.config['MYSQL_DB'] = 'your mysql database'
@app.route('/')
def index():
if 'username' in session:
return f'Hello, {session["username"]}!'
else:
return 'Please login first.'
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
cur = mysql.connection.cursor()
cur.execute('INSERT INTO users(username, password) VALUES (%s, %s)', (username, password))
mysql.connection.commit()
cur.close()
session['username'] = username
return redirect('/')
else:
return '''
<form method="post">
<input type="text" name="username" placeholder="Username"/><br>
<input type="password" name="password" placeholder="Password"/><br>
<button type="submit">Signup</button>
</form>
'''
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
cur = mysql.connection.cursor()
cur.execute('SELECT password FROM users WHERE username = %s', [username])
password_from_db = cur.fetchone()
cur.close()
if password_from_db and password_from_db[0] == password:
session['username'] = username
return redirect('/')
else:
return 'Invalid username or password.'
else:
return '''
<form method="post">
<input type="text" name="username" placeholder="Username"/><br>
<input type="password" name="password" placeholder="Password"/><br>
<button type="submit">Login</button>
</form>
'''
if __name__ == '__main__':
app.run()
```
以上代码使用 Flask 框架和 Flask-MySQLdb 扩展实现用户注册和登录功能。用户信息保存在 MySQL 数据库中,密码使用明文存储(实际应用中应使用加密后的密码)。
阅读全文