写了个开源项目:py-seal
前言
平常一些小项目我都会用 python 来写,为了提高开发效率,我把很多地方的代码包装之后发现它可以当作一个框架来使用,于是我就把代码重新组织成了一个框架,并且推送到了 pypi,源代码也在 github 上开源了。
github地址:
https://github.com/tian-gua/py-seal
py-seal
py-seal 从功能上来讲,就是围绕着3个功能做增强
数据库操作部分,py-seal提供了一个装饰器(Decorator)来增强用户定义的 model,并且提供了一个动态构建 sql 的包(借鉴 mybatis-plus 的操作方式), 支持 sqlite3 和 mysql
http 路由部分,py-seal 同样提供了几个常用的装饰器来提供用户定义接口,装饰器的功能主要是包装了 fastapi的路由功能
并且,py-seal 还包装了一些常用功能,例如 jwt、请求上下文、全局异常处理等等
安装py-seal
从 pypi 安装最新版的 py-seal
pip install py-seal案例
场景:登录和获取当前登录用户接口
import jwtimport uvicornfrom datetime import datetime, timedeltafrom seal.db.sqlite import Queryfrom seal.router import app, postfrom seal import init_seal, get_sealfrom seal.exception import BusinessExceptionfrom seal.wrapper import entityfrom seal.model import BaseEntityclass UserLoginParam(BaseModel): username: str password: str@post(path="/login/submit")async def submit(param: UserLoginParam): user = Query(User).eq("username", param.username).first() if user is None or user.password != param.password: raise BusinessException(message="用户名或密码错误!") return jwt.encode({"uid": user.id, "username": user.username, "exp": datetime.now() + timedelta(hours=2)}, get_seal().get_config('jwt_key'), algorithm="HS256") @entity(table='user')class User(BaseEntity): id: int username: str password: str nick_name: str avatar: str | None role_id: int | None status: int @get("/user/current")async def current_user(): return ChainedQuery(User).eq('id', WebContext().uid()).first() if __name__ == "__main__": init_seal('./config.yaml') uvicorn.run(app, host="0.0.0.0", port=8080)配置文件config.yaml:
seal: authorization: jwt_key: py-seal expire: 3600 excludes: - /** loguru: path: logs/seal.log level: INFO rotation: 00:00 retention: 10 days sqlite: path: ./db.sqlite这个demo可以说是用到了 py-seal 包装的大部分功能
@post :装饰器会把 submit 函数作为一个 http post 接口的处理函数,它的 uri 为/login/submit
Query :Query是一个构建sql查询语句的对象,类似 mybatis-plus中的 LambdaQuery 提供的功能,提供了列表查询,单行查询,分页查询等功能
@entity :entity 装饰器用来增强 model,并为 model 增加了 orm 库需要使用的一些属性
Response:所有py-seal 接口的响应都会被一个 Response 对象包装
Yaml 配置:py-seal 需要通过 yaml配置来初始化,初始化之后才能适用 orm 功能
