From 49f76ab5e9ef0ce5d966485553ad6019a9d37da5 Mon Sep 17 00:00:00 2001 From: Alexander Botello Date: Sun, 21 Oct 2018 02:37:29 -0500 Subject: [PATCH] Add documentation to reflect `add_event_handler` (#129) * Update applications docs * Update events docs * slight reword * make requested changes * split into two examples --- docs/applications.md | 11 ++++++++++- docs/events.md | 19 ++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/applications.md b/docs/applications.md index c22cf0cd..2cce4abb 100644 --- a/docs/applications.md +++ b/docs/applications.md @@ -45,10 +45,19 @@ You can use any of the following to add handled routes to the application: * `app.add_route(path, func, methods=["GET"])` - Add an HTTP route. The function may be either a coroutine or a regular function, with a signature like `func(request, **kwargs) -> response`. * `app.add_websocket_route(path, func)` - Add a websocket session route. The function must be a coroutine, with a signature like `func(session, **kwargs)`. -* `app.add_graphql_route(path, schema, executor=None) - Add a GraphQL route. +* `app.add_graphql_route(path, schema, executor=None)` - Add a GraphQL route. * `@app.route(path)` - Add an HTTP route, decorator style. * `@app.websocket_route(path)` - Add a WebSocket route, decorator style. +### Adding event handlers to the application + +There are two ways to add event handlers: + +* `@app.on_event(event_type)` - Add an event, decorator style +* `app.add_event_handler(event_type, func)` - Add an event through a function call. + +`event_type` must be specified as either `'startup'` or `'cleanup'`. + ### Submounting other applications Submounting applications is a powerful way to include reusable ASGI applications. diff --git a/docs/events.md b/docs/events.md index be90efad..b6696bb0 100644 --- a/docs/events.md +++ b/docs/events.md @@ -8,7 +8,7 @@ is shutting down. These event handlers can either be `async` coroutines, or regular syncronous functions. -The event handlers are registered with a decorator syntax, like so: +The event handlers can be registered with a decorator syntax, like so: ```python from starlette.applications import Starlette @@ -23,6 +23,23 @@ async def open_database_connection_pool(): @app.on_event('cleanup') async def close_database_connection_pool(): ... +``` +Or as a regular function call: + +```python +from starlette.applications import Starlette + + +app = Starlette() + +async def open_database_connection_pool(): + ... + +async def close_database_connection_pool(): + ... + +app.add_event_handler('startup', open_database_connection_pool) +app.add_event_handler('cleanup', close_database_connection_pool) ```