@@ -20,73 +20,40 @@ Based on FastAPI-SQLAlchemy
2020### Examples
2121
2222
23- ### Usage inside of a route
23+ #### Usage inside of a route
2424
2525Note that the session object provided by `` db.session `` is based on the Python3.7+ `` ContextVar `` . This means that
2626each session is linked to the individual request context in which it was created.
2727
2828``` python
2929
30- from fastapi import FastAPI
31- from fastapi_async_sqlalchemy import SQLAlchemyMiddleware # middleware helper
32- from fastapi_async_sqlalchemy import db # an object to provide global access to a database session
30+ from fastapi import FastAPI
31+ from fastapi_async_sqlalchemy import SQLAlchemyMiddleware # middleware helper
32+ from fastapi_async_sqlalchemy import db # an object to provide global access to a database session
33+ from sqlalchemy import column
34+ from sqlalchemy import table
3335
34- from app.models import User
36+ app = FastAPI()
37+ app.add_middleware(SQLAlchemyMiddleware,
db_url = " postgresql+asyncpg://user:[email protected] :5432/primary_db" )
3538
36- app = FastAPI( )
39+ foo = table( " ms_files " , column( " id " ) )
3740
38- app.add_middleware(SQLAlchemyMiddleware, db_url = " sqlite+aiosqlite://" )
3941
40- # once the middleware is applied, any route can then access the database session
41- # from the global ``db``
42+ @app.get (" /" )
43+ async def get_files ():
44+ result = await db.session.execute(foo.select())
45+ return result.fetchall()
4246
43- @app.get (" /users" )
44- def get_users ():
45- users = db.session.query(User).all()
4647
47- return users
48- ```
49-
50-
51- ### Usage outside of a route
52-
53- Sometimes it is useful to be able to access the database outside the context of a request, such as in scheduled tasks which run in the background:
54-
55- ``` python
56-
57- import pytz
58- from apscheduler.schedulers.asyncio import AsyncIOScheduler # other schedulers are available
59- from fastapi import FastAPI
60- from fastapi_async_sqlalchemy import db
61-
62- from app.models import User, UserCount
48+ @app.get (" /db_context" )
49+ async def db_context ():
50+ async with db():
51+ result = await db.session.execute(foo.select())
52+ return result.fetchall()
6353
64- app = FastAPI()
6554
66- app.add_middleware(DBSessionMiddleware, db_url = " sqlite+aiosqlite://" )
55+ if __name__ == " __main__" :
56+ import uvicorn
57+ uvicorn.run(app, host = " 0.0.0.0" , port = 8002 )
6758
68-
69- @app.on_event (' startup' )
70- async def startup_event ():
71- scheduler = AsyncIOScheduler(timezone = pytz.utc)
72- scheduler.start()
73- scheduler.add_job(count_users_task, " cron" , hour = 0 ) # runs every night at midnight
74-
75-
76- def count_users_task ():
77- """ Count the number of users in the database and save it into the user_counts table."""
78-
79- # we are outside of a request context, therefore we cannot rely on ``DBSessionMiddleware``
80- # to create a database session for us. Instead, we can use the same ``db`` object and
81- # use it as a context manager, like so:
82-
83- with db():
84- user_count = db.session.query(User).count()
85-
86- db.session.add(UserCount(user_count))
87- db.session.commit()
88-
89- # no longer able to access a database session once the db() context manager has ended
90-
91- return users
92- ```
59+ ```
0 commit comments