fastapi-async-sqlalchemy icon indicating copy to clipboard operation
fastapi-async-sqlalchemy copied to clipboard

Dynamically update password

Open MarkusDressel opened this issue 10 months ago • 1 comments

I'am using a Azure PostgreSql with a managed identity. This means, the password is a bearer token which expires after 4 hours. I need to fetch a new token once expires and pass this to your middleware. Is there a (hacky) way for it ?

Any help, highly appreciated

MarkusDressel avatar Mar 29 '24 18:03 MarkusDressel

you can try use custom_engine,

ps not tested just idea

from sqlalchemy.engine.create import create_engine
from sqlalchemy.ext.asyncio import AsyncEngine
from sqlalchemy.ext.asyncio.engine import create_async_engine

def create_custom_engine(url, **kwargs):
    class CustomAsyncEngine(AsyncEngine):
        async def _update_token(self):
            # your recv token logic
            new_token = fetch_bearer_token()
            self.url = self.url.set(password=new_token)

        async def connect(self, *args, **kwargs):
            await self._update_token()
            return await super().connect(*args, **kwargs)

    return create_async_engine(url, class_=CustomAsyncEngine, **kwargs)


custom_engine = create_custom_engine(db_url, **engine_args)
SQLAlchemyMiddleware(app, custom_engine=custom_engine)

h0rn3t avatar Apr 09 '24 06:04 h0rn3t