bocadillo.applications

App

App(self, name:str=None)

The all-mighty application class.

This class implements the ASGI protocol.

Example

>>> from bocadillo import App
>>> app = App()

Parameters

  • name (str): An optional name for the app.

include_router

App.include_router(self, router:bocadillo.routing.Router, prefix:str='')

Include routes from another router.

Parameters

  • router (Router): a router object.
  • prefix (str): a string prefixed to the URL pattern of each route.

mount

App.mount(self, prefix:str, app:Union[_ForwardRef('App'), bocadillo.app_types.ASGIApp, Callable[[dict, Callable[[str, List[str]], NoneType]], List[bytes]]])

Mount another WSGI or ASGI app at the given prefix.

Parameters

  • prefix (str): a path prefix where the app should be mounted, e.g. "/myapp".
  • app: an object implementing the WSGI or ASGI protocol.

route

App.route(self, pattern:str, methods:List[str]=None)

Register an HTTP route by decorating a view.

Parameters

  • pattern (str): an URL pattern.

websocket_route

App.websocket_route(self, pattern:str, *, auto_accept:bool=True, value_type:str=None, receive_type:str=None, send_type:str=None, caught_close_codes:Tuple[int]=None)

Register a WebSocket route by decorating a view.

See WebSocket for a description of keyword parameters.

Parameters

  • pattern (str): an URL pattern.

add_error_handler

App.add_error_handler(self, exception_cls:Type[BaseException], handler:Callable[[bocadillo.request.Request, bocadillo.response.Response, BaseException], Awaitable[NoneType]])

Register a new error handler.

Parameters

  • exception_cls (exception class): The type of exception that should be handled.
  • handler (callable): The actual error handler, which is called when an instance of exception_cls is caught. Should accept a request, response and exception parameters.

error_handler

App.error_handler(self, exception_cls:Type[Exception])

Register a new error handler (decorator syntax).

See Also

add_middleware

App.add_middleware(self, middleware_cls, **kwargs)

Register a middleware class.

Parameters

  • middleware_cls: a subclass of #::bocadillo.middleware#Middleware.

See Also

on

App.on(self, event:str, handler:Union[Callable[[], Awaitable[NoneType]], NoneType]=None)

Register an event handler.

Parameters

  • event (str): Either "startup" (when the server boots) or "shutdown" (when the server stops).
  • handler (callback, optional): The event handler. If not given, this should be used as a decorator.

Example

@app.on("startup")
async def startup():
    pass

async def shutdown():
    pass

app.on("shutdown", shutdown)