Minimal working application
app.py script defines a minimal working application:
from bocadillo import App, configure app = App() configure(app)
- First, we import the
Appclass and the
configurehelper from the
- Then, we instanciate an application.
- Finally, the application is configured so that it can be served by an ASGI web server.
Although this script could be served as-is, we recommend you adopt a package-style project structure.
To do so, place the
app.py script in a folder containing an
. └── myproject ├── __init__.py └── app.py
We'll assume that you use a package-style project structure in the rest of the documentation.
Serving an application
The officially recommended ASGI web server for Bocadillo is uvicorn. It comes installed with the
bocadillo package, so you can use it right away!
The minimal working app above can be served using:
You can use any of the uvicorn settings to configure the server.
For example, you can tell uvicorn to use port 5000 using:
uvicorn myproject.app:app --port 5000
Hot reload is baked into uvicorn! 🚀 Use the uvicorn
--reload argument and uvicorn will watch your files and automatically reload the whole application on each file change! This is extremely useful in a development setting.
uvicorn myproject.app:app --reload
Bocadillo applications implement the ASGI Lifespan protocol, which allows you to hook into the application's lifecycle via event handlers.
This is especially useful to setup resources on startup and make sure they get cleaned up when the server stops.
An event handler is an asynchronous function with the signature
() -> None.
Event handlers can be registered using the
@app.on("startup") async def setup(): # Perform setup when server boots pass @app.on("shutdown") async def cleanup(): # Perform cleanup when server shuts down pass
A non-decorator syntax is also available:
from somelib import setup_stuff app.on("startup", setup_stuff)