fastapi_asyncpg icon indicating copy to clipboard operation
fastapi_asyncpg copied to clipboard

Best practice for big application

Open sycured opened this issue 4 years ago • 0 comments

It'll be good to add best practice for big application like https://fastapi.tiangolo.com/tutorial/bigger-applications/

Is it better to have a separate file (database.py) or importing from main.py or another way?

Also adding the snippet of code, it'll be useful for people moving from another framework to fastapi with asyncpg.

edit: it's how actually I do it (/ = root project directory)

  • I put the POSTGRES_DNS inside the file /local_settings.py (managing by consul-template or saltstack)
  • inside my main.app:
from local_settings import POSTGRES_DNS

from fastapi_asyncpg import configure_asyncpg

db = configure_asyncpg(app, POSTGRES_DNS)


@db.on_init
async def initialization(conn):
    await conn.execute('SELECT 1')


@app.on_event('startup')
async def startup():
    app.extra['pool'] = await db.pool
  • inside all files that I need the database, I use like:
from fastapi_asyncpg.sql import select, update

async def test(request: Request):
    pool = request.app.state.pool
    async with pool.acquire() as db:
 return await select(conn=db, table='test1', fields='id, name, slug')


async def update_name(slug, body: Skill, request: Request):
    pool = request.app.state.pool
    if uuid := await find_id_from_slug(pool=pool, id_name='id', slug=f'{slug}', table='test1'):

I think that it's possible to have a better way of how I can obtain the db_pool without using request like a function get_db_pool.

It's why I created this issue to add some information inside the documentation about using fastapi-asyncpg with some retex.

sycured avatar Apr 08 '21 18:04 sycured