Compare commits
No commits in common. "f3ef70b09618404d06606fc2bbfe102c86df7bcb" and "bb53d199bd079334a320293a5dba288a042f3651" have entirely different histories.
f3ef70b096
...
bb53d199bd
48
app/views.py
48
app/views.py
|
|
@ -1,16 +1,9 @@
|
|||
from flask import Flask, request, redirect, url_for, render_template, session, jsonify
|
||||
from db.connection import MySQLPool
|
||||
from config import SECRET_KEY
|
||||
from db.database_manager import DatabaseManager
|
||||
from models.User import User
|
||||
|
||||
app = Flask(__name__)
|
||||
app.secret_key = SECRET_KEY # 从配置文件设置
|
||||
|
||||
# 一个全局MySQLPool对象,用于管理数据库连接
|
||||
mysql_pool = MySQLPool()
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
# 如果用户已登录,则重定向到主页;否则,重定向到登录页面
|
||||
|
|
@ -18,53 +11,42 @@ def index():
|
|||
return redirect(url_for('home'))
|
||||
else:
|
||||
return render_template('login.html')
|
||||
|
||||
|
||||
@app.route('/register', methods=['GET', 'POST'])
|
||||
def register():
|
||||
if request.method == 'POST':
|
||||
# 解析JSON数据而不是表单数据
|
||||
data = request.get_json()
|
||||
# print(data)
|
||||
user = User(
|
||||
nickname=data.get('nickname'),
|
||||
phone_number=data.get('cellphone'), # 确保JSON中的键和这里匹配
|
||||
password=data.get('password'),
|
||||
identity=data.get('identity'),
|
||||
is_active=True # 或者根据你的逻辑设置
|
||||
)
|
||||
db_manager = DatabaseManager()
|
||||
if not db_manager.user_exists(user.phone_number):
|
||||
db_manager.insert_user(user)
|
||||
return jsonify({"success": True, "message": "注册成功"})
|
||||
else:
|
||||
return jsonify({"success": False, "message": "用户已存在"})
|
||||
nick_name = data['nickname']
|
||||
print(nick_name)
|
||||
# 处理注册逻辑...
|
||||
return jsonify({"success": True, "message": "注册成功"}) # 返回JSON响应
|
||||
else:
|
||||
return render_template('register.html')
|
||||
|
||||
|
||||
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
if request.method == 'GET':
|
||||
return render_template('login.html')
|
||||
else:
|
||||
phone_number = request.form['username']
|
||||
username = request.form['username']
|
||||
password = request.form['password']
|
||||
db_manager = DatabaseManager()
|
||||
print(username, password)
|
||||
# 验证用户名和密码...
|
||||
if db_manager.valid_login(phone_number, password):
|
||||
if valid_login(username, password):
|
||||
# 登录成功
|
||||
session['username'] = phone_number
|
||||
session['username'] = username
|
||||
return jsonify(success=True, message="登录成功")
|
||||
else:
|
||||
# 登录失败
|
||||
return jsonify(success=False, message="无效的用户名或密码")
|
||||
|
||||
|
||||
|
||||
@app.route('/forget', methods=['GET', 'POST'])
|
||||
def forget_page():
|
||||
return render_template('forget.html')
|
||||
|
||||
|
||||
@app.route('/home')
|
||||
def home():
|
||||
if 'username' in session:
|
||||
|
|
@ -72,7 +54,6 @@ def home():
|
|||
else:
|
||||
return redirect("login")
|
||||
|
||||
|
||||
@app.route('/logout')
|
||||
def logout():
|
||||
# 清除session中的所有信息
|
||||
|
|
@ -81,5 +62,10 @@ def logout():
|
|||
return redirect('/login')
|
||||
|
||||
|
||||
def valid_login(username, password):
|
||||
# 这里应该是验证用户名和密码的逻辑,比如查询数据库等等
|
||||
# 假设用户名是admin且密码是secret
|
||||
return username == '1' and password == '1'
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
app.run(debug = True)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
# config.py
|
||||
import pymysql
|
||||
|
||||
# app secretkey
|
||||
SECRET_KEY = 'sUNiJ7QPulxrbmZD'
|
||||
|
|
@ -7,10 +6,9 @@ SECRET_KEY = 'sUNiJ7QPulxrbmZD'
|
|||
# 数据库连接配置
|
||||
DB_CONFIG = {
|
||||
'host': '42.193.20.110',
|
||||
'port': 8006, # 注意端口是数字,不是字符串
|
||||
'user': 'test',
|
||||
'password': 'X7gq9lbxqpDGbyCi',
|
||||
'database': 'test_db',
|
||||
'charset': 'utf8mb4',
|
||||
'cursorclass': pymysql.cursors.DictCursor
|
||||
'cursorclass': 'pymysql.cursors.DictCursor'
|
||||
}
|
||||
|
|
@ -20,3 +20,16 @@ class MySQLPool:
|
|||
def get_connection(self):
|
||||
# 从连接池中获取一个连接
|
||||
return self.pool.connection()
|
||||
|
||||
# 使用上下文管理器自动处理连接的开启和关闭
|
||||
def execute(self, sql, args=None):
|
||||
with self.get_connection() as connection:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(sql, args)
|
||||
if sql.strip().lower().startswith("select"):
|
||||
# 如果是查询操作,返回所有结果
|
||||
return cursor.fetchall()
|
||||
else:
|
||||
# 如果是增、删、改操作,提交事务并返回影响的行数
|
||||
connection.commit()
|
||||
return cursor.rowcount
|
||||
|
|
@ -1,55 +1,28 @@
|
|||
import pymysql
|
||||
from db.connection import MySQLPool
|
||||
import bcrypt
|
||||
from config import DB_CONFIG
|
||||
|
||||
class DatabaseManager:
|
||||
def __init__(self):
|
||||
# 使用MySQLPool初始化数据库连接池
|
||||
self.pool = MySQLPool()
|
||||
self.connection = pymysql.connect(**DB_CONFIG)
|
||||
|
||||
def fetch(self, query, params=None):
|
||||
conn = self.pool.get_connection()
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(query, params or ())
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
finally:
|
||||
cursor.close()
|
||||
conn.close()
|
||||
# 实现查询逻辑
|
||||
pass
|
||||
|
||||
def execute(self, query, params=None):
|
||||
conn = self.pool.get_connection()
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(query, params or ())
|
||||
conn.commit()
|
||||
return cursor.rowcount
|
||||
finally:
|
||||
cursor.close()
|
||||
conn.close()
|
||||
def insert(self, query, params=None):
|
||||
# 实现插入逻辑
|
||||
pass
|
||||
|
||||
def user_exists(self, phone_number):
|
||||
sql = "SELECT 1 FROM user WHERE phone_number=%s LIMIT 1"
|
||||
result = self.fetch(sql, (phone_number,))
|
||||
return len(result) > 0
|
||||
def update(self, query, params=None):
|
||||
# 实现更新逻辑
|
||||
pass
|
||||
|
||||
def insert_user(self, user):
|
||||
sql = """
|
||||
INSERT INTO user (nickname, phone_number, password, identity, is_active)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
"""
|
||||
data = (user.nickname, user.phone_number, user.password, user.identity, user.is_active)
|
||||
# print(data)
|
||||
return self.execute(sql, data)
|
||||
def delete(self, query, params=None):
|
||||
# 实现删除逻辑
|
||||
pass
|
||||
|
||||
def valid_login(self, phone_number, password_attempt):
|
||||
# SQL查询获取用户的哈希密码
|
||||
sql = "SELECT password FROM user WHERE phone_number=%s LIMIT 1"
|
||||
result = self.fetch(sql, (phone_number,))
|
||||
if result:
|
||||
stored_hash = result[0]['password'] # 假设结果是密码字段
|
||||
# 使用bcrypt进行密码验证
|
||||
if bcrypt.checkpw(password_attempt.encode('utf-8'), stored_hash.encode('utf-8')):
|
||||
return True # 密码匹配,登录成功
|
||||
return False # 密码不匹配或用户不存在,登录失败
|
||||
def close(self):
|
||||
# 关闭数据库连接
|
||||
self.connection.close()
|
||||
|
||||
# 可能还包含其他数据库操作方法...
|
||||
|
|
|
|||
|
|
@ -1,14 +1,10 @@
|
|||
import bcrypt
|
||||
|
||||
class User:
|
||||
def __init__(self, nickname, phone_number, password, identity, is_active):
|
||||
self.nickname = nickname # 用户昵称
|
||||
self.phone_number = phone_number # 手机号
|
||||
self.password = self.hash_password(password) # 哈希密码
|
||||
self.password = password # 密码
|
||||
self.identity = identity # 身份(老师或学生)
|
||||
self.is_active = is_active # 状态(是否可用)
|
||||
|
||||
def hash_password(self, password):
|
||||
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
||||
def __str__(self):
|
||||
return f"User({self.nickname}, {self.phone_number}, {'Teacher' if self.identity == 'teacher' else 'Student'}, {'Active' if self.is_active else 'Inactive'})"
|
||||
Reference in New Issue