Compare commits

...

5 Commits
master ... lbj

Author SHA1 Message Date
sd 67c1d0b687 注册 4 months ago
sd 32ce72e393 111 4 months ago
sd 6d566667a6 111 4 months ago
sd e8e9e4d4b3 111 4 months ago
sd fc9d1062f8 111 4 months ago
  1. 12
      app.py
  2. 11
      config.py
  3. 382
      controller/LoginController.py
  4. 182
      controller/RegisterController.py
  5. BIN
      resource/avatar/1.jpg
  6. BIN
      resource/avatar/1_1766477129_1706.jpg
  7. BIN
      resource/avatar/2.jpg
  8. BIN
      resource/avatar/4.png
  9. BIN
      resource/avatar/admin_1766388917_8519.jpg
  10. BIN
      resource/avatar/admin_1766389471_9334.jpg
  11. BIN
      resource/avatar/f8c6732809a04f74bc4f3856b949de5e.jpg
  12. 176
      service/UserService.py
  13. 69
      util/mysql_utils.py
  14. 65
      vue/src/App.vue
  15. 40
      vue/src/api/login.js
  16. 46
      vue/src/api/profile.js
  17. 33
      vue/src/api/register.js
  18. BIN
      vue/src/assets/logo.png
  19. BIN
      vue/src/assets/登录.png
  20. BIN
      vue/src/assets/背景.png
  21. 423
      vue/src/components/Menu.vue
  22. 39
      vue/src/router/index.js
  23. 60
      vue/src/system/Index.vue
  24. 548
      vue/src/system/Login.vue
  25. 671
      vue/src/system/Profile.vue
  26. 763
      vue/src/system/Register.vue
  27. 48
      vue/src/utils/request.js
  28. 58
      vue/vue.config.js
  29. 15
      web_main.py

12
app.py

@ -0,0 +1,12 @@
import os
import sys
from robyn import Robyn
# 自动将 web_server 目录加入 Python 路径
web_server_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if web_server_path not in sys.path:
sys.path.insert(0, web_server_path)
app = Robyn(__file__)

11
config.py

@ -0,0 +1,11 @@
# MySQL数据库配置
# 请根据您的实际MySQL配置修改以下参数
MYSQL_CONFIG = {
"host": "localhost", # MySQL主机地址
"port": 3306, # MySQL端口
"user": "root", # MySQL用户名
"password": "123456", # MySQL密码
"database": "kg", # 数据库名
"charset": "utf8mb4" # 字符
}

382
controller/LoginController.py

@ -0,0 +1,382 @@
from robyn import jsonify, Response, Request
from app import app
from datetime import datetime, timedelta
import uuid
import json
import os
import base64
from service.UserService import user_service
# 临时存储token,用于会话管理
TEMP_TOKENS = {}
def generate_token() -> str:
"""生成随机token"""
return str(uuid.uuid4())
def validate_token(token: str) -> dict:
"""验证token并返回用户信息"""
if not token or token not in TEMP_TOKENS:
return None
# 检查token是否过期
if datetime.now() > TEMP_TOKENS[token]["expires_at"]:
del TEMP_TOKENS[token]
return None
return TEMP_TOKENS[token]["user"]
@app.post("/api/login")
def login_route(request):
"""登录接口"""
try:
# 解析请求数据
request_data = {}
if request.body:
try:
request_data = json.loads(request.body)
except json.JSONDecodeError:
pass
# 如果JSON解析失败,尝试从form_data获取
if not request_data and hasattr(request, 'form_data'):
request_data = getattr(request, 'form_data', {})
username = request_data.get("username", "").strip()
password = request_data.get("password", "").strip()
remember = request_data.get("remember", False)
# 验证输入
if not username or not password:
return Response(
status_code=400,
description=jsonify({"success": False, "message": "用户名和密码不能为空"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 验证用户
user = user_service.verify_user(username, password)
if not user:
return Response(
status_code=401,
description=jsonify({"success": False, "message": "用户名或密码错误"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 生成token并设置过期时间
token = generate_token()
expires_at = datetime.now() + timedelta(days=7 if remember else 1)
TEMP_TOKENS[token] = {"user": user, "expires_at": expires_at}
return Response(
status_code=200,
description=jsonify({"success": True, "message": "登录成功", "token": token, "user": user}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
except Exception as e:
return Response(
status_code=500,
description=jsonify({"success": False, "message": f"登录失败: {str(e)}"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
@app.post("/api/logout")
def logout_route(request):
"""登出接口"""
try:
request_data = json.loads(request.body) if request.body else {}
token = request_data.get("token", "")
# 删除token
TEMP_TOKENS.pop(token, None)
return Response(
status_code=200,
description=jsonify({"success": True, "message": "登出成功"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
except Exception as e:
return Response(
status_code=500,
description=jsonify({"success": False, "message": f"登出失败: {str(e)}"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
@app.get("/api/userInfo")
def user_info_route(request):
"""获取用户信息接口"""
try:
query_params = getattr(request, 'query_params', {})
token = query_params.get("token", "")
# 验证token
user = validate_token(token)
if not user:
return Response(
status_code=401,
description=jsonify({"success": False, "message": "未登录或登录已过期"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 从数据库获取最新的用户信息
username = user["username"]
db_user = user_service.get_user_info(username)
if db_user:
# 更新TEMP_TOKENS中的用户信息
TEMP_TOKENS[token]["user"] = db_user
user_info = db_user
else:
user_info = user
return Response(
status_code=200,
description=jsonify({"success": True, "user": user_info}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
except Exception as e:
return Response(
status_code=500,
description=jsonify({"success": False, "message": f"获取用户信息失败: {str(e)}"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
@app.post("/api/updateAvatar")
async def update_avatar_route(request: Request):
"""更新用户头像接口"""
try:
# 从files中获取文件和token
avatar_file = request.files.get('avatar') if hasattr(request, 'files') else None
token = None
# 从form_data中获取token
if hasattr(request, 'form_data'):
token = request.form_data.get('token')
# 如果files中没有直接找到'avatar',尝试获取第一个文件
if not avatar_file and hasattr(request, 'files') and request.files:
first_key = list(request.files.keys())[0]
avatar_file = request.files[first_key]
# 如果form_data中没有token,尝试从headers获取
if not token:
headers_dict = {}
if hasattr(request, 'headers'):
try:
headers_dict = dict(request.headers)
except:
pass
token = headers_dict.get('Authorization') or headers_dict.get('authorization')
# 如果还是没有token,尝试从body中解析
if not token and hasattr(request, 'body'):
try:
body_data = json.loads(request.body)
token = body_data.get('token')
except:
pass
# 验证token
user = validate_token(token)
if not user:
return Response(
status_code=401,
description=jsonify({"success": False, "message": "未登录或登录已过期"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 检查文件是否存在
if not avatar_file:
return Response(
status_code=400,
description=jsonify({"success": False, "message": "未上传头像文件"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 获取文件内容和文件名
file_content = None
filename = ""
# Robyn框架中,files字典的值通常是字节数据
if isinstance(avatar_file, bytes):
file_content = avatar_file
filename = list(request.files.keys())[0] if request.files else "avatar.jpg"
elif isinstance(avatar_file, str):
filename = avatar_file
else:
if avatar_file is not None:
# 尝试获取文件内容的其他方式
if hasattr(avatar_file, 'content'):
file_content = avatar_file.content
elif hasattr(avatar_file, 'read'):
file_content = avatar_file.read()
filename = getattr(avatar_file, 'filename', 'avatar.jpg')
# 如果我们有文件内容,继续处理
if not file_content:
return Response(
status_code=400,
description=jsonify({"success": False, "message": "无法读取文件内容"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 处理文件名
if not filename:
filename = "avatar.jpg"
file_extension = filename.split('.')[-1] if '.' in filename else 'jpg'
# 验证文件类型
is_valid_image = False
# 通过扩展名验证
if file_extension.lower() in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']:
is_valid_image = True
# 如果扩展名验证失败,尝试读取文件头验证
if not is_valid_image:
try:
if (file_content.startswith(b'\xFF\xD8\xFF') or # JPEG
file_content.startswith(b'\x89PNG\r\n\x1a\n') or # PNG
file_content.startswith(b'GIF87a') or # GIF
file_content.startswith(b'GIF89a') or # GIF
file_content.startswith(b'BM') or # BMP
file_content.startswith(b'RIFF') and b'WEBP' in file_content[:12]): # WebP
is_valid_image = True
except Exception:
pass
if not is_valid_image:
return Response(
status_code=400,
description=jsonify({"success": False, "message": f"文件类型必须是图片 (支持的格式: JPG, PNG, GIF, BMP, WebP, SVG)"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 生成唯一的文件名
import time
import random
timestamp = int(time.time())
random_num = random.randint(1000, 9999)
username = user["username"]
new_filename = f"{username}_{timestamp}_{random_num}.{file_extension}"
# 定义文件保存路径(使用相对路径)
current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
avatar_dir = os.path.join(current_dir, "resource", "avatar")
file_path = os.path.join(avatar_dir, new_filename)
# 确保目录存在
os.makedirs(avatar_dir, exist_ok=True)
# 保存文件到磁盘
with open(file_path, "wb") as f:
f.write(file_content)
# 更新用户头像到数据库,存储相对路径
avatar_relative_path = f"/resource/avatar/{new_filename}"
success = user_service.update_user_avatar(username, avatar_relative_path)
if not success:
return Response(
status_code=500,
description=jsonify({"success": False, "message": "更新头像失败"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 更新token中的用户信息
TEMP_TOKENS[token]["user"]["avatar"] = avatar_relative_path
return Response(
status_code=200,
description=jsonify({
"success": True,
"message": "头像更新成功",
"avatar": avatar_relative_path
}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
except Exception as e:
return Response(
status_code=500,
description=jsonify({"success": False, "message": f"更新头像失败: {str(e)}"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
@app.post("/api/updatePassword")
def update_password_route(request):
"""更新用户密码接口"""
try:
# 解析请求数据
request_data = json.loads(request.body) if request.body else {}
token = request_data.get("token", "")
current_password = request_data.get("currentPassword", "")
new_password = request_data.get("newPassword", "")
# 验证输入
if not current_password or not new_password:
return Response(
status_code=400,
description=jsonify({"success": False, "message": "当前密码和新密码不能为空"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 验证token
user = validate_token(token)
if not user:
return Response(
status_code=401,
description=jsonify({"success": False, "message": "未登录或登录已过期"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 获取用户信息
username = user["username"]
# 验证当前密码
db_user = user_service.get_user_by_username(username)
if not db_user:
return Response(
status_code=404,
description=jsonify({"success": False, "message": "用户不存在"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 验证密码
is_password_valid = user_service.verify_password(current_password, db_user["password"])
if not is_password_valid:
return Response(
status_code=401,
description=jsonify({"success": False, "message": "当前密码不正确"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 更新密码
success = user_service.update_user_password(username, new_password)
if not success:
return Response(
status_code=500,
description=jsonify({"success": False, "message": "密码更新失败"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
return Response(
status_code=200,
description=jsonify({"success": True, "message": "密码更新成功"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
except Exception as e:
return Response(
status_code=500,
description=jsonify({"success": False, "message": f"密码更新失败: {str(e)}"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
@app.after_request("/")
def add_cors_headers(response):
"""添加CORS头,支持跨域请求"""
response.headers.update({
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With"
})
return response

182
controller/RegisterController.py

@ -0,0 +1,182 @@
from robyn import jsonify, Response
from app import app
import os
import uuid
from service.UserService import user_service
# 头像上传目录
AVATAR_UPLOAD_FOLDER = 'resource/avatar'
@app.post("/api/register")
def register_route(request):
"""用户注册接口"""
try:
# 获取表单数据
form_data = getattr(request, 'form_data', {}) if hasattr(request, 'form_data') else {}
# 获取文件上传
files = getattr(request, 'files', {}) if hasattr(request, 'files') else {}
username = form_data.get("username", "").strip()
password = form_data.get("password", "").strip()
# 验证必填字段
if not username or not password:
return Response(
status_code=400,
description=jsonify({"success": False, "message": "用户名和密码不能为空"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 检查用户名是否已存在
existing_user = user_service.get_user_by_username(username)
if existing_user:
return Response(
status_code=409,
description=jsonify({"success": False, "message": "用户名已存在"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 处理头像上传
avatar_path = "/resource/avatar/4.png" # 默认头像
# 获取头像文件
avatar_file = files.get('avatar')
# 如果有头像文件,处理上传
if avatar_file:
# 获取文件内容和文件名
file_content = None
filename = ""
# Robyn框架中,files字典的值通常是字节数据
if isinstance(avatar_file, bytes):
file_content = avatar_file
filename = "avatar.jpg"
elif hasattr(avatar_file, 'content'):
file_content = avatar_file.content
filename = getattr(avatar_file, 'filename', 'avatar.jpg')
elif hasattr(avatar_file, 'read'):
file_content = avatar_file.read()
filename = getattr(avatar_file, 'filename', 'avatar.jpg')
else:
filename = avatar_file if isinstance(avatar_file, str) else 'avatar.jpg'
# 如果我们有文件内容,继续处理
if file_content:
# 处理文件名
file_extension = filename.split('.')[-1] if '.' in filename else 'jpg'
# 验证文件类型
is_valid_image = False
# 通过扩展名验证
if file_extension.lower() in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']:
is_valid_image = True
# 如果扩展名验证失败,尝试读取文件头验证
if not is_valid_image:
try:
if (file_content.startswith(b'\xFF\xD8\xFF') or # JPEG
file_content.startswith(b'\x89PNG\r\n\x1a\n') or # PNG
file_content.startswith(b'GIF87a') or # GIF
file_content.startswith(b'GIF89a')): # GIF
is_valid_image = True
except:
pass
if not is_valid_image:
return Response(
status_code=400,
description=jsonify({"success": False, "message": "不支持的图片格式"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 确保上传目录存在
if not os.path.exists(AVATAR_UPLOAD_FOLDER):
os.makedirs(AVATAR_UPLOAD_FOLDER)
# 生成唯一文件名
unique_filename = f"{uuid.uuid4().hex}.{file_extension}"
file_path = os.path.join(AVATAR_UPLOAD_FOLDER, unique_filename)
# 保存文件
try:
with open(file_path, 'wb') as f:
f.write(file_content)
avatar_path = f"/{file_path}"
except Exception as e:
print(f"保存头像失败: {e}")
return Response(
status_code=500,
description=jsonify({"success": False, "message": "头像保存失败"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 创建用户
user_id = user_service.create_user(username, password, avatar_path)
if user_id:
return Response(
status_code=201,
description=jsonify({
"success": True,
"message": "注册成功",
"user": {
"id": user_id,
"username": username,
"avatar": avatar_path
}
}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
else:
return Response(
status_code=500,
description=jsonify({"success": False, "message": "注册失败,请稍后再试"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
except Exception as e:
print(f"注册异常: {e}")
return Response(
status_code=500,
description=jsonify({"success": False, "message": f"注册失败: {str(e)}"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
@app.get("/api/checkUsername")
def check_username_route(request):
"""检查用户名是否可用"""
try:
# 获取查询参数
username = ""
# 尝试从query_params获取
if hasattr(request, 'query_params') and request.query_params:
username = request.query_params.get("username", "").strip()
if not username:
return Response(
status_code=400,
description=jsonify({"success": False, "message": "用户名不能为空"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
# 检查用户名是否已存在
existing_user = user_service.get_user_by_username(username)
return Response(
status_code=200,
description=jsonify({
"success": True,
"available": existing_user is None,
"message": "用户名可用" if not existing_user else "用户名已存在"
}),
headers={"Content-Type": "application/json; charset=utf-8"}
)
except Exception as e:
print(f"检查用户名异常: {e}")
return Response(
status_code=500,
description=jsonify({"success": False, "message": f"检查失败: {str(e)}"}),
headers={"Content-Type": "application/json; charset=utf-8"}
)

BIN
resource/avatar/1.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

BIN
resource/avatar/1_1766477129_1706.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

BIN
resource/avatar/2.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

BIN
resource/avatar/4.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
resource/avatar/admin_1766388917_8519.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

BIN
resource/avatar/admin_1766389471_9334.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

BIN
resource/avatar/f8c6732809a04f74bc4f3856b949de5e.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

176
service/UserService.py

@ -0,0 +1,176 @@
import bcrypt
from typing import Dict, Any, Optional
from util.mysql_utils import mysql_client
class UserService:
"""用户服务类,处理用户相关的业务逻辑"""
def __init__(self):
self.mysql = mysql_client
def get_user_by_username(self, username: str) -> Optional[Dict[str, Any]]:
"""根据用户名获取用户信息"""
try:
sql = "SELECT * FROM users WHERE username = %s"
users = self.mysql.execute_query(sql, (username,))
return users[0] if users else None
except Exception as e:
print(f"查询用户失败: {e}")
return None
def verify_user(self, username: str, password: str) -> Optional[Dict[str, Any]]:
"""验证用户登录信息"""
try:
user = self.get_user_by_username(username)
if not user:
return None
stored_password = user.get("password")
# 验证密码 - 使用bcrypt验证
if bcrypt.checkpw(password.encode('utf-8'), stored_password.encode('utf-8')):
avatar_path = user.get("avatar")
# 如果头像为空,设置默认头像
if not avatar_path:
avatar_path = "/resource/avatar/4.png"
return {
"id": user.get("id"),
"username": user.get("username"),
"avatar": avatar_path
}
return None
except Exception as e:
print(f"验证用户失败: {e}")
return None
def get_user_info(self, username: str) -> Optional[Dict[str, Any]]:
"""获取用户信息(不验证密码)"""
try:
user = self.get_user_by_username(username)
if not user:
return None
avatar_path = user.get("avatar")
# 如果头像为空,设置默认头像
if not avatar_path:
avatar_path = "/resource/avatar/4.png"
return {
"id": user.get("id"),
"username": user.get("username"),
"avatar": avatar_path
}
except Exception as e:
print(f"获取用户信息失败: {e}")
return None
def update_user_avatar(self, username: str, avatar_path: str) -> bool:
"""更新用户头像"""
try:
# 检查数据库连接状态
if not self.mysql.is_connected():
print("数据库未连接,尝试重新连接...")
if not self.mysql.connect():
print("数据库连接失败")
return False
sql = "UPDATE users SET avatar = %s WHERE username = %s"
print(f"执行SQL: {sql}")
print(f"参数: {avatar_path}, {username}")
result = self.mysql.execute_update(sql, (avatar_path, username))
print(f"更新结果: {result}")
return result > 0
except Exception as e:
print(f"更新用户头像失败: {e}")
import traceback
traceback.print_exc()
return False
def update_user_password(self, username: str, new_password: str) -> bool:
"""更新用户密码"""
try:
# 检查数据库连接状态
if not self.mysql.is_connected():
print("数据库未连接,尝试重新连接...")
if not self.mysql.connect():
print("数据库连接失败")
return False
# 使用bcrypt加密新密码
hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
sql = "UPDATE users SET password = %s WHERE username = %s"
print(f"执行SQL: {sql}")
print(f"参数: {hashed_password}, {username}")
result = self.mysql.execute_update(sql, (hashed_password, username))
print(f"更新结果: {result}")
return result > 0
except Exception as e:
print(f"更新用户密码失败: {e}")
import traceback
traceback.print_exc()
return False
def verify_password(self, password: str, hashed_password: str) -> bool:
"""验证密码"""
try:
return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
except Exception as e:
print(f"验证密码失败: {e}")
return False
def create_user(self, username: str, password: str, avatar_path: str = None) -> int:
"""创建新用户"""
try:
# 检查数据库连接状态
if not self.mysql.is_connected():
print("数据库未连接,尝试重新连接...")
if not self.mysql.connect():
print("数据库连接失败")
return 0
# 使用bcrypt加密密码
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
# 设置默认头像
if not avatar_path:
avatar_path = "/resource/avatar/4.png"
# 插入新用户
sql = "INSERT INTO users (username, password, avatar) VALUES (%s, %s, %s)"
print(f"执行SQL: {sql}")
print(f"参数: {username}, {hashed_password}, {avatar_path}")
# 执行插入
result = self.mysql.execute_update(sql, (username, hashed_password, avatar_path))
if result > 0:
# 获取插入的用户ID
id_sql = "SELECT LAST_INSERT_ID() as user_id"
id_result = self.mysql.execute_query(id_sql)
if id_result:
user_id = id_result[0].get("user_id", 0)
print(f"插入结果,用户ID: {user_id}")
return user_id
return 0
except Exception as e:
print(f"创建用户失败: {e}")
import traceback
traceback.print_exc()
return 0
# 创建全局用户服务实例
user_service = UserService()
# 初始化MySQL连接
def init_mysql_connection():
"""初始化MySQL连接"""
try:
return user_service.mysql.connect()
except Exception as e:
print(f"初始化MySQL连接失败: {e}")
return False

69
util/mysql_utils.py

@ -0,0 +1,69 @@
import pymysql
from typing import List, Dict, Any
from config import MYSQL_CONFIG
class MySQLClient:
"""MySQL客户端类"""
def __init__(self):
self.connection = None
def connect(self):
"""建立数据库连接"""
try:
self.connection = pymysql.connect(
host=MYSQL_CONFIG["host"],
port=MYSQL_CONFIG["port"],
user=MYSQL_CONFIG["user"],
password=MYSQL_CONFIG["password"],
database=MYSQL_CONFIG["database"],
charset=MYSQL_CONFIG["charset"],
cursorclass=pymysql.cursors.DictCursor
)
print(f"MySQL数据库连接成功 - {MYSQL_CONFIG['host']}:{MYSQL_CONFIG['port']}/{MYSQL_CONFIG['database']}")
return True
except Exception as e:
print(f"MySQL数据库连接失败: {e}")
return False
def execute_query(self, sql: str, params: tuple = None) -> List[Dict[str, Any]]:
"""执行查询语句"""
if not self.connection and not self.connect():
return []
try:
with self.connection.cursor() as cursor:
cursor.execute(sql, params)
return cursor.fetchall()
except Exception as e:
print(f"执行查询失败: {e}")
return []
def execute_update(self, sql: str, params: tuple = None) -> int:
"""执行更新语句(INSERT, UPDATE, DELETE)"""
if not self.connection and not self.connect():
return 0
try:
with self.connection.cursor() as cursor:
result = cursor.execute(sql, params)
self.connection.commit()
print(f"执行更新成功,影响行数: {result}")
return result
except Exception as e:
print(f"执行更新失败: {e}")
self.connection.rollback()
return 0
def is_connected(self) -> bool:
"""检查数据库连接状态"""
if not self.connection:
return False
try:
self.connection.ping(reconnect=True)
return True
except:
return False
# 创建全局MySQL客户端实例
mysql_client = MySQLClient()

65
vue/src/App.vue

@ -1,69 +1,10 @@
<template>
<!-- 控制面板可选 -->
<!-- <div class="controls">-->
<!-- <button @click="toggleLabel">切换节点标签</button>-->
<!-- </div>-->
<!-- 知识图谱 -->
<GraphDemo
:graph-data="knowledgeData"
:node-style="nodeConfig"
:edge-style="edgeConfig"
ref="graphRef"
/>
<router-view />
</template>
<script>
import GraphDemo from './system/GraphDemo.vue';
export default {
name: 'App',
components: {
GraphDemo
},
data() {
return {
knowledgeData: {
nodes: [
{ id: 'entity1', label: '人工智能', style: { fill: '#FFD700' } },
{ id: 'entity2', label: '机器学习', style: { shape: 'rect', size: 80 } },
{ id: 'entity3', label: '深度学习' }
],
edges: [
{ source: 'entity1', target: 'entity2', label: '包含' },
{ source: 'entity2', target: 'entity3', label: '子领域' }
]
},
nodeConfig: {
shape: 'circle',
size: 70,
fill: '#9FD5FF',
stroke: '#5B8FF9',
lineWidth: 2,
showLabel: true,
labelFontFamily: 'Microsoft YaHei',
labelFontSize: 16,
labelColor: '#333'
},
edgeConfig: {
type: 'quadratic', // 线
stroke: '#666',
lineWidth: 2,
endArrow: true,
showLabel: true,
labelFontFamily: 'Microsoft YaHei',
labelFontSize: 14,
labelColor: '#888'
}
}
},
methods:{
toggleLabel() {
this.nodeConfig.showLabel = !this.nodeConfig.showLabel
}
}
name: 'App'
}
</script>
@ -75,4 +16,4 @@ export default {
text-align: center;
color: #2c3e50;
}
</style>
</style>

40
vue/src/api/login.js

@ -0,0 +1,40 @@
// src/api/login.js
import request from '@/utils/request';
/**
* 用户登录
* 后端接口POST /login
* @param {Object} data - 登录信息
* @param {string} data.username - 用户名
* @param {string} data.password - 密码
* @param {boolean} data.remember - 是否记住密码
*/
export function login(data) {
return request({
url: '/login',
method: 'post',
data
});
}
/**
* 用户登出
* 后端接口POST /logout
*/
export function logout() {
return request({
url: '/logout',
method: 'post'
});
}
/**
* 获取用户信息
* 后端接口GET /userInfo
*/
export function getUserInfo() {
return request({
url: '/userInfo',
method: 'get'
});
}

46
vue/src/api/profile.js

@ -0,0 +1,46 @@
// src/api/profile.js
import request from '@/utils/request';
/**
* 获取用户信息
* 后端接口GET /api/userInfo
* @param {string} token - 用户登录令牌
*/
export function getUserProfile(token) {
return request({
url: '/userInfo',
method: 'get',
params: {
token
}
});
}
/**
* 更新用户头像
* 后端接口POST /api/updateAvatar
* @param {FormData} formData - 包含头像文件和token的表单数据
*/
export function updateAvatar(formData) {
return request({
url: '/updateAvatar',
method: 'post',
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
}
});
}
/**
* 更新用户密码
* 后端接口POST /api/updatePassword
* @param {Object} data - 包含旧密码新密码和token的数据
*/
export function updatePassword(data) {
return request({
url: '/updatePassword',
method: 'post',
data
});
}

33
vue/src/api/register.js

@ -0,0 +1,33 @@
// src/api/register.js
import request from '@/utils/request';
/**
* 用户注册
* 后端接口POST /api/register
* @param {FormData} formData - 包含用户名密码和头像的表单数据
*/
export function register(formData) {
return request({
url: '/api/register',
method: 'post',
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
}
});
}
/**
* 检查用户名是否可用
* 后端接口GET /api/checkUsername
* @param {string} username - 要检查的用户名
*/
export function checkUsername(username) {
return request({
url: '/api/checkUsername',
method: 'get',
params: {
username
}
});
}

BIN
vue/src/assets/logo.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 724 B

BIN
vue/src/assets/登录.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 B

BIN
vue/src/assets/背景.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 675 KiB

423
vue/src/components/Menu.vue

@ -0,0 +1,423 @@
<template>
<div class="sidebar-container" :class="{ 'collapsed': isCollapsed }">
<!-- 折叠按钮 -->
<button @click="toggleCollapse" class="collapse-btn">
<span class="collapse-icon">{{ isCollapsed ? '▶' : '◀' }}</span>
</button>
<!-- 系统标题区域 -->
<div class="sidebar-header">
<h1 class="sidebar-title" v-show="!isCollapsed" @click="goToIndex">
面向疾病预测的知识图谱应用系统
</h1>
<h1 class="sidebar-title-collapsed" v-show="isCollapsed" @click="goToIndex">
医疗知识图谱
</h1>
</div>
<!-- 菜单列表 -->
<nav class="sidebar-nav">
<ul>
<li
v-for="(item, index) in menuItems"
:key="index"
class="menu-item"
>
<a
@click.prevent="handleMenuClick(index)"
class="menu-link"
:class="{ 'active': activeIndex === index }"
:title="isCollapsed ? item.name : ''"
>
<span class="menu-icon">{{ item.icon }}</span>
<span v-show="!isCollapsed">{{ item.name }}</span>
</a>
</li>
</ul>
</nav>
<!-- 底部用户信息和退出登录区域 -->
<div class="sidebar-footer">
<div class="user-info">
<div class="user-avatar">
<span class="avatar-text"></span>
</div>
<div class="user-details" v-show="!isCollapsed">
<p class="user-name">管理员</p>
<p class="user-email">admin@example.com</p>
</div>
<div class="action-buttons" v-show="!isCollapsed">
<button @click="handleProfile" class="profile-btn-inline" title="个人主页">
个人主页
</button>
<button @click="handleLogout" class="logout-btn-inline" title="退出登录">
退出登录
</button>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, defineProps, defineEmits } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();
//
const props = defineProps({
//
initialActive: {
type: Number,
default: 0
}
});
//
const emit = defineEmits(['menu-click']);
//
const menuItems = ref([
{
name: '医疗知识图谱',
path: '/medical-kg',
icon: '🏥'
},
{
name: '知识图谱构建',
path: '/kg-construction',
icon: '🔧'
},
{
name: '知识图谱问答',
path: '/kg-qa',
icon: '💬'
},
{
name: '知识图谱数据',
path: '/kg-data',
icon: '📊'
}
]);
//
const activeIndex = ref(props.initialActive);
//
const isCollapsed = ref(false);
//
const toggleCollapse = () => {
isCollapsed.value = !isCollapsed.value;
};
//
const handleMenuClick = (index) => {
activeIndex.value = index;
emit('menu-click', menuItems.value[index]);
};
//
const handleProfile = () => {
// 使Vue Router
router.push('/profile');
};
// 退
const handleLogout = () => {
// 使Vue Router
router.push('/login');
};
//
const goToIndex = () => {
router.push('/index');
};
</script>
<style scoped>
.sidebar-container {
width: 240px;
height: 100vh;
background-color: #1e40af;
color: white;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
position: relative;
transition: width 0.3s ease;
}
.sidebar-container.collapsed {
width: 60px;
}
.collapse-btn {
position: absolute;
top: 50%;
right: -15px;
width: 30px;
height: 30px;
background-color: #1e40af;
border: 2px solid white;
border-radius: 50%;
color: white;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
transform: translateY(-50%);
}
.collapse-btn:hover {
background-color: #1e3a8a;
}
.collapse-icon {
font-size: 14px;
line-height: 1;
}
.sidebar-header {
padding: 1.25rem;
border-bottom: 1px solid #1e3a8a;
}
.sidebar-title {
font-size: 1.25rem;
font-weight: bold;
letter-spacing: -0.025em;
transition: opacity 0.3s ease;
cursor: pointer;
}
.sidebar-title:hover {
color: #93c5fd;
}
.sidebar-title-collapsed {
font-size: 0.75rem;
font-weight: bold;
text-align: center;
margin: 0;
padding: 0.5rem 0;
writing-mode: vertical-rl;
text-orientation: mixed;
cursor: pointer;
}
.sidebar-title-collapsed:hover {
color: #93c5fd;
}
.sidebar-nav {
flex: 1;
overflow-y: auto;
padding: 1rem 0;
}
.sidebar-nav ul {
padding-left: 0;
margin: 0;
}
.menu-item {
margin-bottom: 0.25rem;
list-style-type: none;
}
.menu-link {
display: flex;
align-items: center;
padding: 0.75rem 1.25rem;
color: white;
text-decoration: none;
transition: background-color 0.2s;
font-size: 1.1rem;
}
.menu-link:hover {
background-color: #1e3a8a;
}
.menu-link.active {
background-color: #1e3a8a;
border-left: 4px solid #60a5fa;
}
.menu-icon {
margin-right: 0.75rem;
color: #93c5fd;
font-size: 1.4rem;
transition: margin 0.3s ease;
}
.sidebar-container.collapsed .menu-icon {
margin-right: 0;
justify-content: center;
display: flex;
}
.menu-link:hover .menu-icon {
color: white;
}
.sidebar-footer {
padding: 1rem;
border-top: 1px solid #1e3a8a;
}
.user-info {
display: flex;
align-items: center;
position: relative;
justify-content: center;
padding: 0.5rem 0;
}
.sidebar-container.collapsed .user-info {
flex-direction: column;
}
.action-buttons {
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
opacity: 0;
transition: opacity 0.3s ease, bottom 0.3s ease;
background-color: white;
border-radius: 8px;
padding: 8px 0;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
margin-bottom: 10px;
min-width: 120px;
}
.user-info:hover .action-buttons {
opacity: 1;
bottom: 100%;
}
.user-avatar {
width: 2rem;
height: 2rem;
border-radius: 50%;
background-color: #274eb8;
display: flex;
align-items: center;
justify-content: center;
margin-right: 0.75rem;
}
.avatar-text {
font-size: 0.875rem;
}
.user-details {
flex: 1;
}
.user-name {
font-size: 0.875rem;
font-weight: 500;
margin: 0;
}
.user-email {
font-size: 0.75rem;
color: #93c5fd;
margin: 0;
}
/* 退出登录按钮样式 */
.profile-btn-inline, .logout-btn-inline {
background: transparent;
border: none;
color: #333;
cursor: pointer;
padding: 10px 16px;
transition: all 0.2s;
display: block;
width: 100%;
text-align: left;
font-size: 14px;
}
.profile-btn-inline:hover, .logout-btn-inline:hover {
background-color: #f5f7fa;
color: #1e40af;
}
.profile-icon, .logout-icon {
font-size: 1.2rem;
}
/* 响应式调整 */
@media (max-width: 768px) {
.sidebar-container {
width: 70px;
}
.sidebar-container.collapsed {
width: 60px;
}
.collapse-btn {
right: -10px;
width: 25px;
height: 25px;
}
.sidebar-title,
.sidebar-title-collapsed,
.menu-link span:not(.menu-icon),
.user-details {
display: none;
}
.menu-link {
justify-content: center;
padding: 0.5rem;
}
.menu-icon {
margin-right: 0;
font-size: 1.2rem;
}
.menu-link.active {
border-left-width: 2px;
}
.action-buttons {
position: static;
opacity: 1;
transform: none;
background-color: transparent;
padding: 0;
box-shadow: none;
margin-top: 0.5rem;
flex-direction: row;
justify-content: center;
min-width: auto;
}
.user-info:hover .action-buttons {
bottom: auto;
}
.profile-btn-inline, .logout-btn-inline {
padding: 6px 8px;
font-size: 12px;
margin: 0 2px;
display: inline-block;
width: auto;
}
}
</style>

39
vue/src/router/index.js

@ -0,0 +1,39 @@
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../system/Login.vue'
import Register from '../system/Register.vue'
import Index from '../system/Index.vue'
import Profile from '../system/Profile.vue'
const routes = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/register',
name: 'Register',
component: Register
},
{
path: '/index',
name: 'Index',
component: Index
},
{
path: '/profile',
name: 'Profile',
component: Profile
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router

60
vue/src/system/Index.vue

@ -0,0 +1,60 @@
<template>
<div class="app-container">
<!-- 引入侧边栏组件 -->
<Menu
:initial-active="0"
@menu-click="handleSidebarClick"
/>
<!-- 主内容区域 -->
<div class="main-content">
<h1 class="text-2xl font-bold mb-4">首页</h1>
<div class="bg-white p-6 rounded-lg shadow">
<p>欢迎使用面向疾病预测的知识图谱应用系统</p>
</div>
</div>
</div>
</template>
<script setup>
import Menu from '../components/Menu.vue';
//
const handleSidebarClick = (menuItem) => {
console.log('点击了菜单项:', menuItem);
//
};
</script>
<style scoped>
.app-container {
display: flex;
height: 100vh;
overflow: hidden;
}
.main-content {
flex: 1;
padding: 1.5rem;
overflow-y: auto;
height: 100%;
}
/* 确保左侧导航栏完全固定 */
.app-container > :first-child {
position: fixed;
height: 100vh;
z-index: 10;
}
/* 为右侧内容添加左边距,避免被固定导航栏遮挡 */
.main-content {
margin-left: 240px; /* 与Menu.vue中的sidebar-container宽度相同 */
transition: margin-left 0.3s ease;
}
/* 当菜单折叠时调整内容区域 */
.app-container:has(.sidebar-container.collapsed) .main-content {
margin-left: 60px;
}
</style>

548
vue/src/system/Login.vue

@ -0,0 +1,548 @@
<template>
<div class="login-container">
<!-- 左上角Logo和标题 -->
<div class="logo-header">
<img src="@/assets/logo.png" alt="Logo" class="logo">
<h1 class="login-title">面向疾病预测的知识图谱应用系统</h1>
</div>
<!-- 左侧登录区域 -->
<div class="login-form-container">
<div class="login-header">
</div>
<div class="login-form">
<h2 class="form-title">登录</h2>
<p class="form-description">请输入您的电子邮件地址和密码以访问账户</p>
<form class="form" @submit.prevent="handleLogin">
<!-- 错误信息显示 -->
<div v-if="errorMessage" class="error-message">
{{ errorMessage }}
</div>
<div class="form-group">
<label for="username" class="form-label">用户名</label>
<input
type="text"
id="username"
v-model="loginForm.username"
placeholder="输入您的用户名"
class="form-input"
>
</div>
<div class="form-group">
<div class="password-header">
<label for="password" class="form-label">密码</label>
<a href="#" class="forgot-password">忘记密码?</a>
</div>
<input
type="password"
id="password"
v-model="loginForm.password"
placeholder="输入您的密码"
class="form-input"
>
</div>
<div class="form-checkbox">
<input
type="checkbox"
id="remember"
v-model="loginForm.remember"
class="checkbox"
>
<label for="remember" class="checkbox-label">记住密码</label>
</div>
<button
type="submit"
class="login-button"
:disabled="loading"
>
<img v-if="!loading" src="@/assets/登录.png" alt="登录" class="login-icon">
<span v-if="!loading">登录</span>
<span v-else>登录中...</span>
</button>
</form>
<div class="social-login">
<p class="social-text">使用其他方式登录</p>
</div>
<div class="register-link">
<p>还没有账户? <a href="#" class="register" @click.prevent="goToRegister"> 立即注册</a></p>
</div>
</div>
</div>
<!-- 右侧知识图谱可视化区域 -->
<div class="graph-container">
<!-- 背景装饰 -->
<div class="background-decoration">
<div class="bg-circle circle-1"></div>
<div class="bg-circle circle-2"></div>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { login } from '@/api/login';
const router = useRouter();
//
const loginForm = ref({
username: '',
password: '',
remember: false
});
//
const loading = ref(false);
const errorMessage = ref('');
//
const handleLogin = async () => {
//
if (!loginForm.value.username || !loginForm.value.password) {
errorMessage.value = '请输入用户名和密码';
return;
}
try {
loading.value = true;
errorMessage.value = '';
// API
const response = await login({
username: loginForm.value.username,
password: loginForm.value.password,
remember: loginForm.value.remember
});
//
console.log('登录成功:', response);
// tokenlocalStorage
if (response.token) {
localStorage.setItem('token', response.token);
}
//
if (loginForm.value.remember) {
localStorage.setItem('username', loginForm.value.username);
} else {
localStorage.removeItem('username');
}
// index
router.push('/index');
} catch (error) {
//
console.error('登录失败:', error);
errorMessage.value = error.response?.data?.message || '登录失败,请检查用户名和密码';
} finally {
loading.value = false;
}
};
//
const goToRegister = () => {
router.push('/register');
};
</script>
<style>
/* 全局样式,防止页面滚动 */
body, html {
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
}
</style>
<style scoped>
/* 基础容器样式 */
.login-container {
display: flex;
height: 100vh;
overflow: hidden;
flex-direction: row;
font-family: 'SimSun', '宋体', serif;
}
/* 左上角Logo和标题样式 */
.logo-header {
position: fixed;
top: 40px;
left: 25px;
display: flex;
align-items: center;
z-index: 10;
}
.logo {
height: 15px;
width: 15px;
margin-right: 7px;
}
.login-title {
font-size: 17px;
font-weight: 900;
font-family: 'SimSun Bold', '宋体', serif;
color: #1f2937;
margin: 0;
white-space: nowrap;
text-shadow: 0.4px 0.4px 0 #1f2937;
}
/* 左侧登录区域样式 */
.login-form-container {
width: 25%;
background-color: #ffffff;
padding: 2rem;
padding-left: 40px;
display: flex;
flex-direction: column;
justify-content: center;
position: relative;
}
.login-header {
margin-bottom: 1.5rem;
width: 100%;
max-width: 24rem;
margin-top: 20px;
}
.login-form {
max-width: 24rem;
width: 100%;
text-align: left;
}
.form-title {
font-size: 18px;
font-weight: 900;
color: #333333;
margin-top: -7px;
margin-bottom: 10px;
margin-left: 13px;
text-shadow: 0.2px 0.2px 0 #1f2937;
text-align: left;
font-family: 'SimSun', '宋体', serif;
}
.form-description {
color: #B5B5B5;
margin-bottom: 2rem;
margin-left: 13px;
text-align: left;
font-size: 11px;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.form {
display: flex;
flex-direction: column;
gap: 1rem;
width: 100%;
}
.error-message {
color: #ef4444;
font-size: 11px;
padding: 0.5rem;
background-color: #fef2f2;
border: 1px solid #fecaca;
border-radius: 0.375rem;
margin-bottom: 0.5rem;
}
.form-group {
display: flex;
flex-direction: column;
width: 100%;
margin-bottom: 0.5rem;
}
.form-label {
display: block;
font-size: 11px;
font-weight: 700;
color: #374151;
margin-bottom: 0.3rem;
text-align: left;
font-family:'STSong', '宋体', serif;
}
.form-input {
width: 100%;
padding: 0.6rem 0.8rem;
border-radius: 0.5rem;
border: 2px solid #A3A3A3;
transition: all 0.2s;
font-size: 9px;
box-sizing: border-box;
font-family: 'SimSun', '宋体', serif;
background-color: #FFFFFF;
}
.form-input:focus {
outline: none;
border-color: #2563eb;
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2);
}
.form-input::placeholder {
color: #9ca3af;
}
.password-header {
display: flex;
justify-content: space-between;
margin-bottom: 0.1rem;
}
.forgot-password {
font-size: 9px;
color: #B5B5B5;
text-decoration: none;
font-family: 'SimSun', '宋体', serif;
}
.forgot-password:hover {
color: #1d4ed8;
}
.form-checkbox {
display: flex;
align-items: center;
margin-top: -5px;
margin-bottom: -5px;
}
.checkbox {
height: 0.8rem;
width: 0.8rem;
color: #2563eb;
border-radius: 0.25rem;
border: 1px solid #d1d5db;
}
.checkbox-label {
margin-left: 0.1rem;
font-size: 11px;
color: #444040ba;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.login-button {
width: 100%;
background-color: #409EFF;
color: white;
font-weight: 500;
font-size: 11px;
padding: 0.6rem 0.8rem;
border-radius: 0;
border: none;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
font-family: 'SimSun', '宋体', 'STSong', '华文宋体', serif;
box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.2);
}
.login-icon {
height: 0.9rem;
width: auto;
margin-right: 8px;
}
.login-button:hover {
background-color: #1d4ed8;
}
.arrow-icon {
margin-left: 0.5rem;
}
/* 分割线样式 */
.divider {
display: flex;
align-items: center;
margin: 1.5rem 0;
font-family: 'SimSun', '宋体', serif;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
height: 1px;
background-color: #e5e7eb;
}
.divider span {
padding: 0 1rem;
font-size: 11px;
color: #B5B5B5;
font-family: 'SimSun', '宋体', serif;
}
.social-login {
margin-top: 2rem;
}
.social-text {
text-align: center;
color: #B5B5B5;
margin-bottom: 1rem;
font-size: 11px;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.social-icons {
display: flex;
justify-content: center;
gap: 1rem;
}
.social-icon {
width: 2.5rem;
height: 2.5rem;
border-radius: 50%;
background-color: #f3f4f6;
border: none;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
color: #6b7280;
font-weight: bold;
}
.social-icon:hover {
background-color: #e5e7eb;
}
.register-link {
position: absolute;
bottom: 7px;
left: 50%;
transform: translateX(-50%);
text-align: center;
}
.register-link p {
color: #B5B5B5;
font-size: 11px;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.register {
color: #B5B5B5;
font-weight: 500;
text-decoration: none;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.register:hover {
color: #1d4ed8;
}
/* 右侧知识图谱可视化区域样式 */
.graph-container {
width: 75%;
background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%),
url('@/assets/背景.png');
background-size: cover;
background-position: center;
background-blend-mode: overlay;
padding: 2rem;
position: relative;
overflow: hidden;
}
.background-decoration {
position: absolute;
inset: 0;
opacity: 0.2;
}
.bg-circle {
position: absolute;
border-radius: 50%;
filter: blur(3rem);
}
.circle-1 {
top: 25%;
left: 25%;
width: 16rem;
height: 16rem;
background-color: #60a5fa;
}
.circle-2 {
bottom: 33%;
right: 33%;
width: 20rem;
height: 20rem;
background-color: #818cf8;
}
.graph-content {
position: relative;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-family: 'SimSun', '宋体', serif;
}
.graph-wrapper {
position: relative;
width: 100%;
max-width: 48rem;
aspect-ratio: 1 / 1;
}
/* 响应式设计 */
@media (max-width: 768px) {
.login-container {
flex-direction: column;
}
.login-form-container,
.graph-container {
width: 100%;
}
.login-form-container {
padding: 2rem;
}
.graph-container {
min-height: 400px;
}
}
</style>

671
vue/src/system/Profile.vue

@ -0,0 +1,671 @@
<template>
<div class="app-container">
<!-- 引入侧边栏组件 -->
<Menu
:initial-active="0"
@menu-click="handleSidebarClick"
/>
<!-- 主内容区域 -->
<div class="main-content">
<div class="profile-container">
<!-- 页面标题 -->
<div class="page-header">
<h1 class="page-title">个人主页</h1>
<p class="page-subtitle">管理您的个人信息和账户设置</p>
</div>
<!-- 个人信息卡片 -->
<div class="profile-card">
<!-- 头像区域 -->
<div class="avatar-section">
<div class="avatar-container">
<img
:src="userProfile.avatar"
alt="用户头像"
class="avatar-image"
@error="handleAvatarError"
>
<div class="avatar-overlay" @click="triggerFileInput">
<span class="camera-icon">📷</span>
<span class="overlay-text">更换头像</span>
</div>
<input
type="file"
ref="fileInput"
@change="handleAvatarChange"
accept="image/*"
class="hidden-input"
>
</div>
<div class="username-display">{{ userProfile.username }}</div>
<div class="avatar-status">
<p v-if="avatarUploading" class="uploading-text">上传中...</p>
<p v-if="avatarUploadSuccess" class="success-text">头像更新成功</p>
</div>
</div>
<!-- 用户信息表单 -->
<div class="info-section">
<h2 class="section-title">修改密码</h2>
<form class="password-form" @submit.prevent="changePassword">
<div class="form-group">
<label for="currentPassword" class="form-label">当前密码</label>
<input
type="password"
id="currentPassword"
v-model="passwordForm.currentPassword"
class="form-input"
placeholder="请输入当前密码"
required
>
</div>
<div class="form-group">
<label for="newPassword" class="form-label">新密码</label>
<input
type="password"
id="newPassword"
v-model="passwordForm.newPassword"
class="form-input"
placeholder="请输入新密码"
required
>
</div>
<div class="form-group">
<label for="confirmPassword" class="form-label">确认新密码</label>
<input
type="password"
id="confirmPassword"
v-model="passwordForm.confirmPassword"
class="form-input"
placeholder="请再次输入新密码"
required
>
<p v-if="passwordMismatch" class="error-text">两次输入的密码不一致</p>
</div>
<div class="form-actions">
<button type="submit" class="save-button" :disabled="passwordSaving || passwordMismatch">
<span v-if="!passwordSaving">修改密码</span>
<span v-else>修改中...</span>
</button>
</div>
</form>
</div>
</div>
<!-- 操作反馈 -->
<div v-if="successMessage" class="success-message">
{{ successMessage }}
</div>
<div v-if="errorMessage" class="error-message">
{{ errorMessage }}
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import Menu from '../components/Menu.vue';
import { getUserProfile, updateAvatar, updatePassword } from '../api/profile';
//
const handleSidebarClick = (menuItem) => {
console.log('点击了菜单项:', menuItem);
};
//
const userProfile = ref({
username: '用户',
avatar: '/resource/avatar/4.png'
});
//
const passwordForm = ref({
currentPassword: '',
newPassword: '',
confirmPassword: ''
});
//
const fileInput = ref(null);
const avatarUploading = ref(false);
const avatarUploadSuccess = ref(false);
const profileSaving = ref(false);
const passwordSaving = ref(false);
const successMessage = ref('');
const errorMessage = ref('');
//
const passwordMismatch = computed(() => {
return passwordForm.value.newPassword &&
passwordForm.value.confirmPassword &&
passwordForm.value.newPassword !== passwordForm.value.confirmPassword;
});
//
const triggerFileInput = () => {
fileInput.value.click();
};
//
const handleAvatarError = (event) => {
console.error('头像加载失败:', userProfile.value.avatar);
//
userProfile.value.avatar = '/resource/avatar/4.png';
};
//
const handleAvatarChange = async (event) => {
const file = event.target.files[0];
if (file) {
//
if (!file.type.startsWith('image/')) {
errorMessage.value = '请选择图片文件';
return;
}
// (2MB)
if (file.size > 2 * 1024 * 1024) {
errorMessage.value = '图片大小不能超过2MB';
return;
}
//
avatarUploading.value = true;
avatarUploadSuccess.value = false;
errorMessage.value = '';
try {
// localStoragetoken
const token = localStorage.getItem('token');
if (!token) {
errorMessage.value = '用户未登录,请先登录';
avatarUploading.value = false;
return;
}
// FormData
const formData = new FormData();
formData.append('avatar', file);
formData.append('token', token);
console.log('准备上传头像文件:', file.name);
console.log('Token:', token);
// API
const response = await updateAvatar(formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log('收到响应:', response);
if (response.success) {
// 使
// URL
let avatarPath = response.avatar;
if (avatarPath.startsWith('/resource/')) {
// 访
avatarPath = avatarPath;
}
userProfile.value.avatar = avatarPath;
//
avatarUploadSuccess.value = true;
successMessage.value = '头像更新成功';
// 3
setTimeout(() => {
avatarUploadSuccess.value = false;
successMessage.value = '';
}, 3000);
} else {
errorMessage.value = response.message || '头像更新失败';
}
} catch (error) {
console.error('头像上传失败:', error);
console.error('错误详情:', {
message: error.message,
stack: error.stack,
name: error.name
});
//
if (error.response) {
//
console.error('服务器响应:', error.response.status, error.response.data);
errorMessage.value = `服务器错误 ${error.response.status}: ${JSON.stringify(error.response.data)}`;
} else if (error.request) {
//
console.error('网络错误,未收到响应:', error.request);
errorMessage.value = '网络错误,请检查网络连接和服务器状态';
} else {
//
errorMessage.value = `请求配置错误: ${error.message}`;
}
} finally {
avatarUploading.value = false;
}
}
};
//
const updateProfile = () => {
profileSaving.value = true;
errorMessage.value = '';
successMessage.value = '';
// API
setTimeout(() => {
profileSaving.value = false;
successMessage.value = '个人信息更新成功';
// 3
setTimeout(() => {
successMessage.value = '';
}, 3000);
}, 1000);
};
//
const changePassword = async () => {
if (passwordMismatch.value) {
return;
}
passwordSaving.value = true;
errorMessage.value = '';
successMessage.value = '';
try {
// localStoragetoken
const token = localStorage.getItem('token');
if (!token) {
errorMessage.value = '用户未登录,请先登录';
passwordSaving.value = false;
return;
}
// API
const response = await updatePassword({
token,
currentPassword: passwordForm.value.currentPassword,
newPassword: passwordForm.value.newPassword
});
if (response.success) {
successMessage.value = '密码修改成功';
//
passwordForm.value = {
currentPassword: '',
newPassword: '',
confirmPassword: ''
};
// 3
setTimeout(() => {
successMessage.value = '';
}, 3000);
} else {
errorMessage.value = response.message || '密码修改失败';
}
} catch (error) {
console.error('密码修改失败:', error);
errorMessage.value = '密码修改时发生错误';
} finally {
passwordSaving.value = false;
}
};
//
onMounted(async () => {
try {
// localStoragetoken
const token = localStorage.getItem('token');
console.log('Profile组件挂载,获取到的token:', token);
if (token) {
// API
const response = await getUserProfile(token);
console.log('获取用户信息响应:', response);
if (response.success) {
//
//
let avatarUrl = response.user.avatar || '/resource/avatar/4.png';
if (avatarUrl.startsWith('/resource/')) {
avatarUrl = avatarUrl; // 使
}
console.log('设置头像URL:', avatarUrl);
userProfile.value = {
username: response.user.username,
avatar: avatarUrl
};
} else {
console.error('获取用户信息失败:', response.message);
errorMessage.value = response.message || '获取用户信息失败';
// tokentoken
if (response.message && response.message.includes('登录')) {
localStorage.removeItem('token');
//
}
}
} else {
console.log('用户未登录');
errorMessage.value = '用户未登录,请先登录';
}
} catch (error) {
console.error('获取用户信息失败:', error);
errorMessage.value = '获取用户信息时发生错误';
}
});
</script>
<style scoped>
.app-container {
display: flex;
height: 100vh;
overflow: hidden;
}
.main-content {
flex: 1;
padding: 1.5rem;
overflow-y: auto;
height: 100%;
background-color: #f5f7fa;
transition: margin-left 0.3s ease;
}
/* 确保左侧导航栏完全固定 */
.app-container > :first-child {
position: fixed;
height: 100vh;
z-index: 10;
}
/* 为右侧内容添加左边距,避免被固定导航栏遮挡 */
.main-content {
margin-left: 240px; /* 与Menu.vue中的sidebar-container宽度相同 */
}
/* 当菜单折叠时调整内容区域 */
.app-container:has(.sidebar-container.collapsed) .main-content {
margin-left: 60px;
}
.profile-container {
max-width: 700px;
margin: 0 auto;
}
/* 页面标题样式 */
.page-header {
margin-bottom: 1.5rem;
}
.page-title {
font-size: 1.5rem;
font-weight: 600;
color: #1f2937;
margin: 0 0 0.5rem 0;
}
.page-subtitle {
color: #6b7280;
margin: 0;
font-size: 0.875rem;
}
/* 密码修改卡片 */
.password-card {
background-color: #fff;
border-radius: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
padding: 1.5rem;
margin-bottom: 1.5rem;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
.password-card .section-title {
text-align: center;
}
/* 个人信息卡片 */
.profile-card {
background-color: #fff;
border-radius: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
padding: 1.5rem;
margin-bottom: 1.5rem;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
/* 头像区域样式 */
.avatar-section {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 2rem;
padding-bottom: 1.5rem;
border-bottom: 1px solid #e5e7eb;
}
.avatar-container {
position: relative;
width: 100px;
height: 100px;
margin-bottom: 1rem;
}
.avatar-image {
width: 100%;
height: 100%;
border-radius: 50%;
object-fit: cover;
border: 3px solid #e5e7eb;
}
.avatar-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 50%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.2s;
cursor: pointer;
}
.avatar-container:hover .avatar-overlay {
opacity: 1;
}
.camera-icon {
font-size: 1.5rem;
margin-bottom: 0.25rem;
}
.overlay-text {
font-size: 0.75rem;
color: white;
}
.hidden-input {
display: none;
}
.avatar-status {
text-align: center;
}
.username-display {
text-align: center;
font-size: 1.125rem;
font-weight: 600;
color: #1f2937;
margin-top: 0.75rem;
margin-bottom: 0.5rem;
}
.uploading-text, .success-text {
font-size: 0.875rem;
margin: 0.25rem 0;
}
.uploading-text {
color: #3b82f6;
}
.success-text {
color: #10b981;
}
/* 信息区域样式 */
.info-section {
margin-bottom: 1.5rem;
}
.section-title {
font-size: 1.125rem;
font-weight: 600;
color: #1f2937;
margin: 0 0 1rem 0;
padding-bottom: 0.5rem;
border-bottom: 1px solid #e5e7eb;
text-align: center;
}
/* 表单样式 */
.profile-form, .password-form {
display: flex;
flex-direction: column;
gap: 1rem;
max-width: 400px;
margin: 0 auto;
}
.form-group {
flex: 1;
display: flex;
flex-direction: column;
}
.form-label {
font-size: 0.875rem;
font-weight: 500;
color: #374151;
margin-bottom: 0.5rem;
}
.form-input {
padding: 0.625rem 0.875rem;
border: 1px solid #d1d5db;
border-radius: 0.375rem;
font-size: 0.875rem;
transition: border-color 0.2s;
width: 100%;
box-sizing: border-box;
}
.form-input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.form-input[readonly] {
background-color: #f9fafb;
color: #6b7280;
}
.form-input::placeholder {
color: #9ca3af;
}
.form-actions {
display: flex;
justify-content: center;
margin-top: 1rem;
}
.save-button {
background-color: #3b82f6;
color: white;
border: none;
border-radius: 0.375rem;
padding: 0.625rem 1.25rem;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
transition: background-color 0.2s;
min-width: 120px;
}
.save-button:hover:not(:disabled) {
background-color: #2563eb;
}
.save-button:disabled {
background-color: #9ca3af;
cursor: not-allowed;
}
/* 错误和成功消息样式 */
.error-text {
color: #ef4444;
font-size: 0.75rem;
margin-top: 0.25rem;
}
.success-message, .error-message {
padding: 0.75rem 1rem;
border-radius: 0.375rem;
margin-top: 1rem;
font-size: 0.875rem;
}
.success-message {
background-color: #d1fae5;
color: #065f46;
border: 1px solid #a7f3d0;
}
.error-message {
background-color: #fee2e2;
color: #991b1b;
border: 1px solid #fca5a5;
}
/* 响应式调整 */
@media (max-width: 768px) {
.main-content {
margin-left: 70px; /* 移动端侧边栏宽度 */
}
}
</style>

763
vue/src/system/Register.vue

@ -0,0 +1,763 @@
<template>
<div class="register-container">
<!-- 左上角Logo和标题 -->
<div class="logo-header">
<img src="@/assets/logo.png" alt="Logo" class="logo">
<h1 class="register-title">面向疾病预测的知识图谱应用系统</h1>
</div>
<!-- 左侧注册区域 -->
<div class="register-form-container">
<div class="register-header">
</div>
<div class="register-form">
<h2 class="form-title">注册</h2>
<p class="form-description">创建您的账户以访问系统功能</p>
<form class="form" @submit.prevent="handleRegister">
<!-- 错误信息显示 -->
<div v-if="errorMessage" class="error-message">
{{ errorMessage }}
</div>
<!-- 头像上传区域 -->
<div class="avatar-upload-container">
<div class="avatar-container">
<img
:src="avatarPreview"
alt="用户头像"
class="avatar-image"
@error="handleAvatarError"
>
<div class="avatar-overlay" @click="triggerFileInput">
<span class="camera-icon">📷</span>
<span class="overlay-text">上传头像</span>
</div>
<input
type="file"
ref="fileInput"
@change="handleAvatarChange"
accept="image/*"
class="hidden-input"
>
</div>
<div class="avatar-status">
<p v-if="avatarUploading" class="uploading-text">上传中...</p>
<p v-if="avatarUploadError" class="error-text">{{ avatarUploadError }}</p>
</div>
</div>
<div class="form-group">
<label for="username" class="form-label">用户名</label>
<input
type="text"
id="username"
v-model="registerForm.username"
placeholder="输入您的用户名"
class="form-input"
:class="{ 'error': errors.username }"
>
<p v-if="errors.username" class="error-text">{{ errors.username }}</p>
</div>
<div class="form-group">
<label for="password" class="form-label">密码</label>
<input
type="password"
id="password"
v-model="registerForm.password"
placeholder="输入您的密码"
class="form-input"
:class="{ 'error': errors.password }"
>
<p v-if="errors.password" class="error-text">{{ errors.password }}</p>
</div>
<div class="form-group">
<label for="confirmPassword" class="form-label">确认密码</label>
<input
type="password"
id="confirmPassword"
v-model="registerForm.confirmPassword"
placeholder="再次输入您的密码"
class="form-input"
:class="{ 'error': errors.confirmPassword }"
>
<p v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</p>
</div>
<div class="form-checkbox">
<input
type="checkbox"
id="agree"
v-model="registerForm.agree"
class="checkbox"
>
<label for="agree" class="checkbox-label">我同意服务条款和隐私政策</label>
</div>
<button
type="submit"
class="register-button"
:disabled="loading || !isFormValid"
>
<span v-if="!loading">注册</span>
<span v-else>注册中...</span>
</button>
</form>
<div class="social-login">
<p class="social-text">使用其他方式注册</p>
</div>
<div class="login-link">
<p>已有账户? <a href="#" class="login" @click.prevent="goToLogin"> 立即登录</a></p>
</div>
</div>
</div>
<!-- 右侧知识图谱可视化区域 -->
<div class="graph-container">
<!-- 背景装饰 -->
<div class="background-decoration">
<div class="bg-circle circle-1"></div>
<div class="bg-circle circle-2"></div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { register } from '@/api/register';
const router = useRouter();
//
const registerForm = ref({
username: '',
password: '',
confirmPassword: '',
agree: false,
avatar: null
});
//
const fileInput = ref(null);
const avatarUploading = ref(false);
const avatarUploadError = ref('');
const loading = ref(false);
const errorMessage = ref('');
const errors = ref({
username: '',
password: '',
confirmPassword: ''
});
//
const defaultAvatar = '/resource/avatar/4.png';
const avatarPreview = ref(defaultAvatar);
// -
const isFormValid = computed(() => {
return registerForm.value.username &&
registerForm.value.password &&
registerForm.value.confirmPassword &&
registerForm.value.agree &&
!errors.value.username &&
!errors.value.password &&
!errors.value.confirmPassword &&
registerForm.value.password === registerForm.value.confirmPassword;
});
//
const triggerFileInput = () => {
fileInput.value.click();
};
//
const handleAvatarError = (event) => {
avatarPreview.value = defaultAvatar;
};
//
const handleAvatarChange = (event) => {
const file = event.target.files[0];
if (file) {
//
if (!file.type.startsWith('image/')) {
avatarUploadError.value = '请选择图片文件';
return;
}
// (2MB)
if (file.size > 2 * 1024 * 1024) {
avatarUploadError.value = '图片大小不能超过2MB';
return;
}
avatarUploadError.value = '';
//
const reader = new FileReader();
reader.onload = (e) => {
avatarPreview.value = e.target.result;
registerForm.value.avatar = file;
};
reader.readAsDataURL(file);
}
};
//
const validateForm = () => {
errors.value = {
username: '',
password: '',
confirmPassword: ''
};
//
if (!registerForm.value.username) {
errors.value.username = '用户名不能为空';
}
//
if (!registerForm.value.password) {
errors.value.password = '密码不能为空';
}
//
if (!registerForm.value.confirmPassword) {
errors.value.confirmPassword = '请确认密码';
} else if (registerForm.value.password !== registerForm.value.confirmPassword) {
errors.value.confirmPassword = '两次输入的密码不一致';
}
return !errors.value.username && !errors.value.password && !errors.value.confirmPassword;
};
//
const handleRegister = async () => {
if (!validateForm()) {
return;
}
if (!registerForm.value.agree) {
errorMessage.value = '请同意服务条款和隐私政策';
return;
}
loading.value = true;
errorMessage.value = '';
try {
// FormData
const formData = new FormData();
formData.append('username', registerForm.value.username);
formData.append('password', registerForm.value.password);
// FormData
if (registerForm.value.avatar) {
formData.append('avatar', registerForm.value.avatar);
}
// API
const response = await register(formData);
if (response.success) {
//
router.push('/login');
} else {
errorMessage.value = response.message || '注册失败';
}
} catch (error) {
console.error('注册失败:', error);
errorMessage.value = error.response?.data?.message || '注册过程中发生错误';
} finally {
loading.value = false;
}
};
//
const goToLogin = () => {
router.push('/login');
};
</script>
<style>
/* 全局样式,防止页面滚动 */
body, html {
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
}
</style>
<style scoped>
/* 基础容器样式 */
.register-container {
display: flex;
height: 100vh;
overflow: hidden;
flex-direction: row;
font-family: 'SimSun', '宋体', serif;
}
/* 左上角Logo和标题样式 */
.logo-header {
position: fixed;
top: 40px;
left: 25px;
display: flex;
align-items: center;
z-index: 10;
}
.logo {
height: 15px;
width: 15px;
margin-right: 7px;
}
.register-title {
font-size: 17px;
font-weight: 900;
font-family: 'SimSun Bold', '宋体', serif;
color: #1f2937;
margin: 0;
white-space: nowrap;
text-shadow: 0.4px 0.4px 0 #1f2937;
}
/* 左侧注册区域样式 */
.register-form-container {
width: 25%;
background-color: #ffffff;
padding: 2rem;
padding-left: 40px;
display: flex;
flex-direction: column;
justify-content: center;
position: relative;
}
.register-header {
margin-bottom: 1.5rem;
width: 100%;
max-width: 24rem;
margin-top: 20px;
}
.register-form {
max-width: 24rem;
width: 100%;
text-align: left;
}
.form-title {
font-size: 18px;
font-weight: 900;
color: #333333;
margin-top: -7px;
margin-bottom: 10px;
margin-left: 13px;
text-shadow: 0.2px 0.2px 0 #1f2937;
text-align: left;
font-family: 'SimSun', '宋体', serif;
}
.form-description {
color: #B5B5B5;
margin-bottom: 2rem;
margin-left: 13px;
text-align: left;
font-size: 11px;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
/* 头像上传区域 */
.avatar-upload-container {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 25px;
margin-left: 13px;
}
.avatar-container {
position: relative;
width: 80px;
height: 80px;
margin-bottom: 10px;
}
.avatar-image {
width: 100%;
height: 100%;
border-radius: 50%;
object-fit: cover;
border: 3px solid #e5e7eb;
}
.avatar-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 50%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.2s;
cursor: pointer;
}
.avatar-container:hover .avatar-overlay {
opacity: 1;
}
.camera-icon {
font-size: 1.2rem;
margin-bottom: 0.2rem;
}
.overlay-text {
font-size: 0.6rem;
color: white;
}
.hidden-input {
display: none;
}
.avatar-status {
text-align: center;
}
.uploading-text, .error-text {
font-size: 9px;
margin: 0.25rem 0;
}
.uploading-text {
color: #3b82f6;
}
.form {
display: flex;
flex-direction: column;
gap: 1rem;
width: 100%;
}
.error-message {
color: #ef4444;
font-size: 11px;
padding: 0.5rem;
background-color: #fef2f2;
border: 1px solid #fecaca;
border-radius: 0.375rem;
margin-bottom: 0.5rem;
}
.form-group {
display: flex;
flex-direction: column;
width: 100%;
margin-bottom: 0.5rem;
}
.form-label {
display: block;
font-size: 11px;
font-weight: 700;
color: #374151;
margin-bottom: 0.3rem;
text-align: left;
font-family:'STSong', '宋体', serif;
}
.form-input {
width: 100%;
padding: 0.6rem 0.8rem;
border-radius: 0.5rem;
border: 2px solid #A3A3A3;
transition: all 0.2s;
font-size: 9px;
box-sizing: border-box;
font-family: 'SimSun', '宋体', serif;
background-color: #FFFFFF;
}
.form-input:focus {
outline: none;
border-color: #2563eb;
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2);
}
.form-input.error {
border-color: #ef4444;
}
.form-input::placeholder {
color: #9ca3af;
}
.password-header {
display: flex;
justify-content: space-between;
margin-bottom: 0.1rem;
}
.forgot-password {
font-size: 9px;
color: #B5B5B5;
text-decoration: none;
font-family: 'SimSun', '宋体', serif;
}
.forgot-password:hover {
color: #1d4ed8;
}
.form-checkbox {
display: flex;
align-items: center;
margin-top: -5px;
margin-bottom: -5px;
}
.checkbox {
height: 0.8rem;
width: 0.8rem;
color: #2563eb;
border-radius: 0.25rem;
border: 1px solid #d1d5db;
}
.checkbox-label {
margin-left: 0.1rem;
font-size: 11px;
color: #444040ba;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.register-button {
width: 100%;
background-color: #409EFF;
color: white;
font-weight: 500;
font-size: 11px;
padding: 0.6rem 0.8rem;
border-radius: 0;
border: none;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
font-family: 'SimSun', '宋体', 'STSong', '华文宋体', serif;
box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.2);
}
.login-icon {
height: 0.9rem;
width: auto;
margin-right: 8px;
}
.register-button:hover:not(:disabled) {
background-color: #1d4ed8;
}
.register-button:disabled {
background-color: #bdc3c7;
cursor: not-allowed;
}
.arrow-icon {
margin-left: 0.5rem;
}
/* 分割线样式 */
.divider {
display: flex;
align-items: center;
margin: 1.5rem 0;
font-family: 'SimSun', '宋体', serif;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
height: 1px;
background-color: #e5e7eb;
}
.divider span {
padding: 0 1rem;
font-size: 11px;
color: #B5B5B5;
font-family: 'SimSun', '宋体', serif;
}
.social-login {
margin-top: 2rem;
}
.social-text {
text-align: center;
color: #B5B5B5;
margin-bottom: 1rem;
font-size: 11px;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.social-icons {
display: flex;
justify-content: center;
gap: 1rem;
}
.social-icon {
width: 2.5rem;
height: 2.5rem;
border-radius: 50%;
background-color: #f3f4f6;
border: none;
cursor: pointer;
transition: background-color 0.2s;
display: flex;
align-items: center;
justify-content: center;
color: #6b7280;
font-weight: bold;
}
.social-icon:hover {
background-color: #e5e7eb;
}
.login-link {
position: absolute;
bottom: 7px;
left: 50%;
transform: translateX(-50%);
text-align: center;
}
.login-link p {
color: #B5B5B5;
font-size: 11px;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.login {
color: #B5B5B5;
font-weight: 500;
text-decoration: none;
font-weight: bold;
font-family: 'SimSun', '宋体', serif;
}
.login:hover {
color: #1d4ed8;
}
/* 右侧知识图谱可视化区域样式 */
.graph-container {
width: 75%;
background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%),
url('@/assets/背景.png');
background-size: cover;
background-position: center;
background-blend-mode: overlay;
padding: 2rem;
position: relative;
overflow: hidden;
}
.background-decoration {
position: absolute;
inset: 0;
opacity: 0.2;
}
.bg-circle {
position: absolute;
border-radius: 50%;
filter: blur(3rem);
}
.circle-1 {
top: 25%;
left: 25%;
width: 16rem;
height: 16rem;
background-color: #60a5fa;
}
.circle-2 {
bottom: 33%;
right: 33%;
width: 20rem;
height: 20rem;
background-color: #818cf8;
}
.graph-content {
position: relative;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-family: 'SimSun', '宋体', serif;
}
.graph-wrapper {
position: relative;
width: 100%;
max-width: 48rem;
aspect-ratio: 1 / 1;
}
.error-text {
color: #ef4444;
font-size: 9px;
margin-top: 5px;
}
/* 响应式设计 */
@media (max-width: 768px) {
.register-container {
flex-direction: column;
}
.register-form-container,
.graph-container {
width: 100%;
}
.register-form-container {
padding: 2rem;
}
.graph-container {
min-height: 400px;
}
}
</style>

48
vue/src/utils/request.js

@ -1,65 +1,25 @@
// src/utils/request.js
import axios from 'axios';
// 创建 axios 实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 10000, // 请求超时时间(10秒)
baseURL: '/',
timeout: 10000,
});
// 请求拦截器
service.interceptors.request.use(
(config) => {
// 可在此添加 token、loading 等逻辑
// 例如:config.headers.Authorization = `Bearer ${token}`;
return config;
},
(error) => {
console.error('请求发送失败:', error);
return Promise.reject(error);
}
);
// 响应拦截器
service.interceptors.response.use(
(response) => {
// 根据你的后端结构调整
// 如果后端直接返回 { nodes: [...], edges: [...] },可直接返回 data
return response.data; // 直接返回数据部分
return response.data;
},
(error) => {
const { response } = error;
if (response) {
// 服务器返回了状态码但不是 2xx
const status = response.status;
let msg = '请求失败';
switch (status) {
case 400:
msg = '请求参数错误';
break;
case 401:
msg = '未授权,请登录';
break;
case 403:
msg = '拒绝访问';
break;
case 404:
msg = '请求地址不存在';
break;
case 500:
msg = '服务器内部错误';
break;
default:
msg = `请求失败 (${status})`;
}
console.error(msg, response.data);
} else if (error.request) {
// 请求已发出但没收到响应(如网络断开)
console.error('网络错误,请检查连接');
} else {
// 其他错误
console.error('请求配置错误:', error.message);
}
console.error('请求错误拦截器:', error);
return Promise.reject(error);
}
);

58
vue/vue.config.js

@ -8,17 +8,67 @@ module.exports = defineConfig({
],
devServer: {
host: '0.0.0.0',
port: 80,
port: 81,
open: true,
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: 'http://localhost:8088',
'/login': {
target: 'http://localhost:8088', // 更新为8088端口
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: '/'
'^/login': '/api/login'
}
},
'/logout': {
target: 'http://localhost:8088', // 更新为8088端口
changeOrigin: true,
pathRewrite: {
'^/logout': '/api/logout'
}
},
'/userInfo': {
target: 'http://localhost:8088', // 更新为8088端口
changeOrigin: true,
pathRewrite: {
'^/userInfo': '/api/userInfo'
}
},
'/updateAvatar': {
target: 'http://localhost:8088', // 更新为8088端口
changeOrigin: true,
pathRewrite: {
'^/updateAvatar': '/api/updateAvatar'
}
},
'/updatePassword': {
target: 'http://localhost:8088', // 更新为8088端口
changeOrigin: true,
pathRewrite: {
'^/updatePassword': '/api/updatePassword'
}
},
'/register': {
target: 'http://localhost:8088', // 注册接口代理
changeOrigin: true,
pathRewrite: {
'^/register': '/api/register'
}
},
'/checkUsername': {
target: 'http://localhost:8088', // 检查用户名接口代理
changeOrigin: true,
pathRewrite: {
'^/checkUsername': '/api/checkUsername'
}
},
'/resource': {
target: 'http://localhost:8088', // 更新为8088端口
changeOrigin: true
}
},
historyApiFallback: {
disableDotRule: true,
verbose: true
},
// 替代 disableHostCheck: true
allowedHosts: 'all' // 允许所有 Host 访问(开发环境安全)
},

15
web_main.py

@ -0,0 +1,15 @@
from app import app
import controller.LoginController
import controller.RegisterController
from service.UserService import init_mysql_connection
import os
# 添加静态文件服务
current_dir = os.path.dirname(os.path.abspath(__file__))
resource_dir = os.path.join(current_dir, "resource")
if os.path.exists(resource_dir):
app.serve_directory("/resource", resource_dir)
print(f"静态资源目录已配置: {resource_dir}")
if __name__ == "__main__":
init_mysql_connection() and app.start(host="0.0.0.0", port=8088)
Loading…
Cancel
Save