flask+python+mysql实现登录注册代码
时间: 2023-09-27 11:10:13 浏览: 104
可以的,您需要一个Flask应用程序、MySQL数据库和Python编程知识来实现它。以下是一个基本的代码示例:
from flask import Flask, render_template, request, redirect, url_for
from flask_mysqldb import MySQL
app = Flask(__name__)
# MySQL配置
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'mydatabase'
# 初始化MySQL
mysql = MySQL(app)
# 登录页面处理
@app.route('/')
def login():
return render_template('login.html')
# 注册页面处理
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
# 获取表单数据
name = request.form['name']
email = request.form['email']
password = request.form['password']
# 将用户数据插入数据库
cur = mysql.connection.cursor()
cur.execute("INSERT INTO users (name, email, password) VALUES (%s, %s, %s)", (name, email, password))
mysql.connection.commit()
cur.close()
# 重定向到登录页面
return redirect(url_for('login'))
# 返回注册页面
return render_template('register.html')
# 验证用户登录
@app.route('/login', methods=['POST'])
def verify_login():
# 获取表单数据
email = request.form['email']
password = request.form['password']
# 查询数据库
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM users WHERE email=%s AND password=%s", (email, password))
user = cur.fetchone()
cur.close()
if user is None:
# 验证失败
return "Invalid email or password"
# 验证成功
return "Welcome, " + user['name']
if __name__ == '__main__':
app.run()
阅读全文