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

Refactor on startup configuration, sqlalchemy session maker, and email sender factory. #103

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Akin01
Copy link

@Akin01 Akin01 commented May 29, 2024

There are 3 refactors that happens to this PR:

  • change session maker to use async_sessionmaker instead of sessionmaker
# async_sessionmaker import from sqlalchemy.ext.asyncio
AsyncSessionFactory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionFactory() as session:
        yield session
  • Fastapi doesn't provide on_event now to setup lifespan event. But It can be setup directly to fastapi instance as lifespan attributes. Just create context manager generator to setup lifespan event. Ref: https://fastapi.tiangolo.com/advanced/events/
@asynccontextmanager
async def lifespan(_fastapi: FastAPI):
    if broker.is_worker_process:
        # TaskIQ configurartion so we can share FastAPI dependencies in tasks
        await broker.startup()
    
    yield

    if broker.is_worker_process:
        # On shutdown, we need to shutdown the broker
        await broker.shutdown()
  • The last is provide custom factory to enable setter for sender globally
# Custom factory to be able to set the sender globally
class EmailSenderFactory(EmailSender):
    @property
    def sender(self):
        return self.sender
    
    @sender.setter
    def sender(self, sender: str):
        self.sender = sender

Akin01 added 3 commits May 29, 2024 15:27
…create `Async Session` and add `AsyncAttrs` to Base Metadata to provide accessor to awaitable attributes (ref: https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#sqlalchemy.ext.asyncio.AsyncAttrs)
…cated. Pass context manager lifespan to fastapi instance instead and configure taskiq broker setup to lifespan context manager.
@devraj devraj self-assigned this May 30, 2024
@devraj
Copy link
Member

devraj commented May 30, 2024

Hey @Akin01 thank you so much for this and pointing out those changes in SQLAlchemy and FastAPI. I will review this and merge it in.

Seeing you forked the repository, I am interested to know if you are using any portion of the template. Would love to learn more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants