Skip to content

Commit

Permalink
fix README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
h0rn3t committed Apr 20, 2021
1 parent 46c3209 commit 5a31ae5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 57 deletions.
77 changes: 22 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,73 +20,40 @@ Based on FastAPI-SQLAlchemy
### Examples


### Usage inside of a route
#### Usage inside of a route

Note that the session object provided by ``db.session`` is based on the Python3.7+ ``ContextVar``. This means that
each session is linked to the individual request context in which it was created.

```python

from fastapi import FastAPI
from fastapi_async_sqlalchemy import SQLAlchemyMiddleware # middleware helper
from fastapi_async_sqlalchemy import db # an object to provide global access to a database session
from fastapi import FastAPI
from fastapi_async_sqlalchemy import SQLAlchemyMiddleware # middleware helper
from fastapi_async_sqlalchemy import db # an object to provide global access to a database session
from sqlalchemy import column
from sqlalchemy import table

from app.models import User
app = FastAPI()
app.add_middleware(SQLAlchemyMiddleware, db_url="postgresql+asyncpg://user:[email protected]:5432/primary_db")

app = FastAPI()
foo = table("ms_files", column("id"))

app.add_middleware(SQLAlchemyMiddleware, db_url="sqlite+aiosqlite://")

# once the middleware is applied, any route can then access the database session
# from the global ``db``
@app.get("/")
async def get_files():
result = await db.session.execute(foo.select())
return result.fetchall()

@app.get("/users")
def get_users():
users = db.session.query(User).all()

return users
```


### Usage outside of a route

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:

```python

import pytz
from apscheduler.schedulers.asyncio import AsyncIOScheduler # other schedulers are available
from fastapi import FastAPI
from fastapi_async_sqlalchemy import db

from app.models import User, UserCount
@app.get("/db_context")
async def db_context():
async with db():
result = await db.session.execute(foo.select())
return result.fetchall()

app = FastAPI()

app.add_middleware(DBSessionMiddleware, db_url="sqlite+aiosqlite://")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8002)


@app.on_event('startup')
async def startup_event():
scheduler = AsyncIOScheduler(timezone=pytz.utc)
scheduler.start()
scheduler.add_job(count_users_task, "cron", hour=0) # runs every night at midnight


def count_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:

with db():
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 ended

return users
```
```
2 changes: 1 addition & 1 deletion fastapi_async_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

__all__ = ["db", "SQLAlchemyMiddleware"]

__version__ = "0.3.1.dev1"
__version__ = "0.3.1.dev2"
2 changes: 1 addition & 1 deletion fastapi_async_sqlalchemy/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def __init__(
engine = custom_engine

global _Session
_Session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession, **session_args)
_Session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, **session_args)

async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
async with db(commit_on_exit=self.commit_on_exit):
Expand Down

0 comments on commit 5a31ae5

Please sign in to comment.