import functools # 导入: import json from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import redis redis_store = redis.Redis(host='127.0.0.1', port=6379, db=0) # *** 作的redis配置 # 创建对象的基类: Base = declarative_base() # 定义User对象: class Admin(Base): __tablename__ = "admin" # 表的结构: id = Column(String(20), primary_key=True) username = Column(String(20)) def get_dict(self): return {"id": self.id, "username": self.username} # 初始化数据库连接: engine = create_engine('mysql+pymysql://root:123456@localhost:3306/caiji_dev') # 创建DBSession类型: DBSession = sessionmaker(bind=engine) session = DBSession() def admin_login_required(view_func): # wraps 函数的作用是将wrapper内层函数的属性设置为被装饰函数view_func的属性 @functools.wraps(view_func) def wrapper(*args, **kwargs): key = "admin:" + str(kwargs["id"]) print(key) cache_info = redis_store.get(key) if cache_info: return json.loads(cache_info) user_info = view_func(*args, **kwargs) redis_store.set(key, json.dumps(user_info), ex=100) return user_info return wrapper @admin_login_required def get_user(id: int): ## 这个写法是错误的,在flask alchemy中可以,但是原生的不行 ## aaa = Admin.query().filter(Admin.id == id).one() user = session.query(Admin).filter(Admin.id == id).one() return {"id": user.id, "username": user.username} if __name__ == '__main__': res = get_user(id=1) pass
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)