codesensei-courses / fastapi_fundamentals

Demo code for the Pluralsight course "FastAPI Fundamentals"
51 stars 48 forks source link

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

Open stephane-rbn opened 8 months ago

stephane-rbn commented 8 months ago

@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 commented 8 months ago

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 commented 8 months ago

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.