向FastAPI添加简单的SQLAlchemy支持
FastAPI-SQLAlchem的Python项目详细描述
fastapisqlalchemy提供了应用程序中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
- 项目
标签: