向FastAPI添加简单的SQLAlchemy支持

FastAPI-SQLAlchem的Python项目详细描述


https://github.com/mfreeborn/fastapi-sqlalchemy/workflows/ci/badge.svghttps://codecov.io/gh/mfreeborn/fastapi-sqlalchemy/branch/master/graph/badge.svghttps://img.shields.io/pypi/v/fastapi_sqlalchemy?color=blue

fastapisqlalchemy提供了应用程序中FastAPISQLAlchemy之间的简单集成。它允许访问有用的助手,以帮助完成常见任务。在

安装

使用pip安装和更新:

$ pip install fastapi-sqlalchemy

示例

路线内部使用

^{pr2}$

注意,db.session提供的session对象基于Python3.7+ContextVar。这意味着 每个会话都链接到创建它的单个请求上下文。在

路线外使用

有时,能够在请求上下文之外访问数据库是很有用的,例如在后台运行的计划任务中:

importpytzfromapscheduler.schedulers.asyncioimportAsyncIOScheduler# other schedulers are availablefromfastapiimportFastAPIfromfastapi_sqlalchemyimportdbfromapp.modelsimportUser,UserCountapp=FastAPI()app.add_middleware(DBSessionMiddleware,db_url="sqlite://")@app.on_event('startup')asyncdefstartup_event():scheduler=AsyncIOScheduler(timezone=pytz.utc)scheduler.start()scheduler.add_job(count_users_task,"cron",hour=0)# runs every night at midnightdefcount_users_task():"""Count the number of users in the database and save it into the user_counts table."""# we are outside of a request context, therefore we cannot rely on ``DBSessionMiddleware``# to create a database session for us. Instead, we can use the same ``db`` object and# use it as a context manager, like so:withdb():user_count=db.session.query(User).count()db.session.add(UserCount(user_count))db.session.commit()# no longer able to access a database session once the db() context manager has endedreturnusers

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
Java中的开源字典组件   即使在成功执行删除查询之后,java更新的列表也不会显示在jsp页面中   java Apache:无法启动上下文路径/网站上的失败应用程序   java验证CSV中的特定列   对于具有专用内存的java应用程序,最小堆大小低于最大堆大小有意义吗?   java将数组中的值转换为多维数组   java在给定程序中,垃圾收集器在对象被取消引用之前正在运行。。。使用jre 7(32位)   java在运行时动态刷新文件夹   eclipse如何解决“java.net.BindException:地址已在使用:JVM_Bind”错误?   Java数组与数组   每次任务完成任务时,Java多线程都会安排任务   java部分编译时使用maven编织第三方jar   java Dokku单一回购中的多个应用程序   用apachevelocity生成javac/C++语言文件   java如何使用spring应用程序上下文中的属性文件实例化列表   java访问智能卡文件结构   具有GlobalMethodSecurity的java自定义UserDetailService循环引用   java如何集成Spring和JSF