向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确保BUnit包和测试包不包含在生产代码中   java如何使JTextField更小,而不是填满整个空间?   javaawt的矩形交点   用户连续登录应用程序的java条纹(Android)   maven如何在服务器上运行java项目,并将其作为jar添加到EAR项目中   java如何在jar/war的资源文件夹中创建png?   swing在Java中未选择列表项时禁用按钮   java GridView x BaseAdapter并在onItemClick中重新加载   java Apache POI未应用某些颜色索引   java创建URL使用uri有什么区别。解析/uri。生成器/连接字符串?   java JavaFX jfoenix运行时错误(JFXDatePicker)   右旋转二叉搜索树   在Java标准版中运行Java移动应用程序   java为什么要为每个实例创建静态hashmap?   java如何使用RTC唤醒和报警意图   java获取对象中的JSON表达式   (Java)服务器不接受多个连接   java为什么我的目的地为null?   java使用多个参数执行存储过程,并使用spring数据jpa将结果集映射到非实体类