Applications
API Reference
starlette.applications.Starlette
Starlette(debug:bool=False,routes:Sequence[BaseRoute]|None=None,middleware:Sequence[Middleware]|None=None,exception_handlers:(Mapping[Any,ExceptionHandler]|None)=None,on_startup:Sequence[Callable[[],Any]]|None=None,on_shutdown:Sequence[Callable[[],Any]]|None=None,lifespan:Lifespan[AppType]|None=None,)Creates an Starlette application.
Parameters:
debug(bool, default:False) –Boolean indicating if debug tracebacks should be returned on errors.
routes(Sequence[BaseRoute] | None, default:None) –A list of routes to serve incoming HTTP and WebSocket requests.
middleware(Sequence[Middleware] | None, default:None) –A list of middleware to run for every request. A starletteapplication will always automatically include two middleware classes.
ServerErrorMiddlewareis added as the very outermost middleware, to handleany uncaught errors occurring anywhere in the entire stack.ExceptionMiddlewareis added as the very innermost middleware, to dealwith handled exception cases occurring in the routing or endpoints.exception_handlers(Mapping[Any,ExceptionHandler] | None, default:None) –A mapping of either integer status codes,or exception class types onto callables which handle the exceptions.Exception handler callables should be of the form
handler(request, exc) -> responseand may be either standard functions, orasync functions.on_startup(Sequence[Callable[[],Any]] | None, default:None) –A list of callables to run on application startup.Startup handler callables do not take any arguments, and may be eitherstandard functions, or async functions.
on_shutdown(Sequence[Callable[[],Any]] | None, default:None) –A list of callables to run on application shutdown.Shutdown handler callables do not take any arguments, and may be eitherstandard functions, or async functions.
lifespan(Lifespan[AppType] | None, default:None) –A lifespan context function, which can be used to performstartup and shutdown tasks. This is a newer style that replaces the
on_startupandon_shutdownhandlers. Use one or the other, not both.
Starlette includes an application classStarlette that nicely ties together all ofits other functionality.
fromcontextlibimportasynccontextmanagerfromstarlette.applicationsimportStarlettefromstarlette.responsesimportPlainTextResponsefromstarlette.routingimportRoute,Mount,WebSocketRoutefromstarlette.staticfilesimportStaticFilesdefhomepage(request):returnPlainTextResponse('Hello, world!')defuser_me(request):username="John Doe"returnPlainTextResponse('Hello,%s!'%username)defuser(request):username=request.path_params['username']returnPlainTextResponse('Hello,%s!'%username)asyncdefwebsocket_endpoint(websocket):awaitwebsocket.accept()awaitwebsocket.send_text('Hello, websocket!')awaitwebsocket.close()@asynccontextmanagerasyncdeflifespan(app):print('Startup')yieldprint('Shutdown')routes=[Route('/',homepage),Route('/user/me',user_me),Route('/user/{username}',user),WebSocketRoute('/ws',websocket_endpoint),Mount('/static',StaticFiles(directory="static")),]app=Starlette(debug=True,routes=routes,lifespan=lifespan)Storing state on the app instance
You can store arbitrary extra state on the application instance, using thegenericapp.state attribute.
For example:
app.state.ADMIN_EMAIL='[email protected]'Accessing the app instance
Where arequest is available (i.e. endpoints and middleware), the app is available onrequest.app.