Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NEW] Async db engine #12

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/app/api/crud.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
from app.api.models import NoteSchema
from app.db import notes, database
from app.db import notes, async_session


async def post(payload: NoteSchema):
query = notes.insert().values(title=payload.title, description=payload.description)
return await database.execute(query=query)

with async_session() as db:
response = await db.execute(query=query)

return response


async def get(id: int):
query = notes.select().where(id == notes.c.id)
return await database.fetch_one(query=query)

with async_session() as db:
response = await db.execute(query=query)

return response


async def get_all():
query = notes.select()
return await database.fetch_all(query=query)
with async_session() as db:
response = await db.execute(query=query)

return response


async def put(id: int, payload: NoteSchema):
Expand All @@ -25,9 +36,17 @@ async def put(id: int, payload: NoteSchema):
.values(title=payload.title, description=payload.description)
.returning(notes.c.id)
)
return await database.execute(query=query)

with async_session() as db:
response = await db.execute(query=query)

return response


async def delete(id: int):
query = notes.delete().where(id == notes.c.id)
return await database.execute(query=query)

with async_session() as db:
response = await db.execute(query=query)

return response
18 changes: 11 additions & 7 deletions src/app/db.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import os

import logging
logger = logging.getLogger(__name__)
from sqlalchemy import (
Column,
DateTime,
Integer,
MetaData,
String,
Table,
create_engine
)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.sql import func

from databases import Database

DATABASE_URL = os.getenv("DATABASE_URL")
DATABASE_URL = os.getenv("DATABASE_URL").replace('postgresql', 'postgresql+asyncpg')
logger.debug(DATABASE_URL, 'DATABASE_URL')

# SQLAlchemy
engine = create_engine(DATABASE_URL)
engine = create_async_engine(DATABASE_URL, echo=True)
metadata = MetaData()
notes = Table(
"notes",
Expand All @@ -27,5 +29,7 @@
Column("created_date", DateTime, default=func.now(), nullable=False),
)

# databases query builder
database = Database(DATABASE_URL)
# sessionmaker version
async_session = sessionmaker(
engine, expire_on_commit=False, class_=AsyncSession
)
17 changes: 13 additions & 4 deletions src/app/main.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
import asyncio
from fastapi import FastAPI

from app.api import notes, ping
from app.db import database, engine, metadata
from app.db import engine, metadata


"""async def async_main():
async with engine.begin() as conn:
await conn.run_sync(metadata.create_all)

await engine.dispose()

asyncio.run(async_main())"""

metadata.create_all(engine)

app = FastAPI()


@app.on_event("startup")
async def startup():
await database.connect()
await engine.connect()


@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
await engine.dispose()


app.include_router(ping.router)
Expand Down
2 changes: 1 addition & 1 deletion src/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
databases[postgresql]==0.6.2
psycopg2-binary==2.9.5
SQLAlchemy==1.4.41
asyncpg==0.27.0
fastapi==0.87.0
uvicorn==0.20.0
asyncpg

# dev
pytest==7.2.0
Expand Down