Version 0.1.1 rise to flask app factory
This commit is contained in:
42
Html/apps/services/user_service.py
Normal file
42
Html/apps/services/user_service.py
Normal file
@@ -0,0 +1,42 @@
|
||||
# myapp/services/user_service.py
|
||||
import os
|
||||
from typing import Tuple
|
||||
from flask import current_app, session
|
||||
|
||||
# 假设你已有这两个 loader
|
||||
from db.user import load_user_from_json
|
||||
|
||||
def _username_from_session() -> str:
|
||||
"""通过 session['user_id'] -> username"""
|
||||
user_uuid = session.get("user_id")
|
||||
if not user_uuid:
|
||||
return None
|
||||
uuid2username = current_app.extensions["uuid2username"]
|
||||
return uuid2username.get(user_uuid)
|
||||
|
||||
def get_or_load_current_user():
|
||||
"""
|
||||
返回当前用户对象(如 user_id2UserClass 中没有则从 JSON 载入并缓存)
|
||||
"""
|
||||
user_uuid = session.get("user_id")
|
||||
if not user_uuid:
|
||||
return None
|
||||
|
||||
username = _username_from_session()
|
||||
if not username:
|
||||
return None
|
||||
|
||||
user_map = current_app.extensions["user_id2UserClass"]
|
||||
if user_uuid not in user_map:
|
||||
user_map[user_uuid] = load_user_from_json(
|
||||
username, user_data_dir=current_app.config["USER_DATA_DIR"]
|
||||
)
|
||||
return user_map[user_uuid]
|
||||
|
||||
def add_course_for_current_user(course_id: str, course_data):
|
||||
user_obj = get_or_load_current_user()
|
||||
if user_obj is None:
|
||||
return False
|
||||
# 你的 UserClass 应该有 select_new_course 接口
|
||||
user_obj.select_new_course(course_id, course_data)
|
||||
return True
|
||||
Reference in New Issue
Block a user