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

How to replace deprecated on_event by lifespan()? #3

Open
stephane-rbn opened this issue Mar 10, 2024 · 2 comments
Open

How to replace deprecated on_event by lifespan()? #3

stephane-rbn opened this issue Mar 10, 2024 · 2 comments

Comments

@stephane-rbn
Copy link

@codesensei-courses Hi!

I'm currently at the point in the course where we're connecting to a SQLite database for the first time. You're using on_event() from SQLModel to add an event handler for the application on startup like so: https://github.com/codesensei-courses/fastapi_fundamentals/blob/c4de006900b495acdf4b973154027f24d790b370/carsharing.py#L32C1-L32C24

However, it is indicated as deprecated on FastAPI's documentation: https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated

Still, I am not sure how to reproduce this behavior using lifespan() instead. Would you show us how you would do it in your code?

Thanks!

@stephane-rbn
Copy link
Author

I guess it should be something like this:

from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # startup logic
    SQLModel.metadata.create_all(engine)
    yield
    # shutdown logic

app = FastAPI(title="Car Sharing", lifespan=lifespan)

engine = create_engine(
    "sqlite:///carsharing.db",
    connect_args={"check_same_thread": False},  # Needed for SQLite
    echo=True  # Log generated SQL
)

I will continue to progress with the project, and if I encounter no difficulties, it means that this code is correct (or was correct at that time of the course). In that case, I will close the ticket unless you have already done so.

@rjekker
Copy link
Collaborator

rjekker commented Mar 12, 2024

Thank you @stephane-rbn for bringing this to my attention. At first glance, your code seems correct to me.

Although the events are currently deprecated, I guess they will keep working for now though. When I update the course - hopefully later this year - I will update this as well.

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

No branches or pull requests

2 participants