2018-10-05 11:04:11 +00:00
|
|
|
|
2018-09-05 12:45:39 +00:00
|
|
|
Starlette includes an application class `Starlette` that nicely ties together all of
|
2018-08-28 14:11:53 +00:00
|
|
|
its other functionality.
|
|
|
|
|
|
|
|
```python
|
2018-09-05 10:39:38 +00:00
|
|
|
from starlette.applications import Starlette
|
2018-09-05 09:29:04 +00:00
|
|
|
from starlette.responses import PlainTextResponse
|
2019-11-13 12:25:18 +00:00
|
|
|
from starlette.routing import Route, Mount, WebSocketRoute
|
2018-08-28 14:11:53 +00:00
|
|
|
from starlette.staticfiles import StaticFiles
|
|
|
|
|
|
|
|
|
|
|
|
def homepage(request):
|
|
|
|
return PlainTextResponse('Hello, world!')
|
|
|
|
|
2018-12-18 12:33:32 +00:00
|
|
|
def user_me(request):
|
|
|
|
username = "John Doe"
|
|
|
|
return PlainTextResponse('Hello, %s!' % username)
|
2018-08-28 14:11:53 +00:00
|
|
|
|
2018-10-29 09:22:45 +00:00
|
|
|
def user(request):
|
|
|
|
username = request.path_params['username']
|
2018-08-28 14:11:53 +00:00
|
|
|
return PlainTextResponse('Hello, %s!' % username)
|
|
|
|
|
2018-09-05 09:29:04 +00:00
|
|
|
async def websocket_endpoint(websocket):
|
|
|
|
await websocket.accept()
|
|
|
|
await websocket.send_text('Hello, websocket!')
|
|
|
|
await websocket.close()
|
2018-10-09 14:47:51 +00:00
|
|
|
|
|
|
|
def startup():
|
|
|
|
print('Ready to go')
|
2018-08-28 14:11:53 +00:00
|
|
|
|
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
routes = [
|
|
|
|
Route('/', homepage),
|
|
|
|
Route('/user/me', user_me),
|
|
|
|
Route('/user/{username}', user),
|
|
|
|
WebSocketRoute('/ws', websocket_endpoint),
|
|
|
|
Mount('/static', StaticFiles(directory="static")),
|
|
|
|
]
|
2018-09-04 10:52:29 +00:00
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
app = Starlette(debug=True, routes=routes, on_startup=[startup])
|
|
|
|
```
|
2018-09-04 10:52:29 +00:00
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
### Instantiating the application
|
2018-09-04 10:52:29 +00:00
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
::: starlette.applications.Starlette
|
|
|
|
:docstring:
|
2019-08-27 08:41:04 +00:00
|
|
|
|
|
|
|
### Storing state on the app instance
|
|
|
|
|
|
|
|
You can store arbitrary extra state on the application instance, using the
|
2019-09-04 01:56:26 +00:00
|
|
|
generic `app.state` attribute.
|
2019-08-27 08:41:04 +00:00
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
```python
|
|
|
|
app.state.ADMIN_EMAIL = 'admin@example.org'
|
|
|
|
```
|
2019-09-04 01:56:26 +00:00
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
### Accessing the app instance
|
2019-09-04 01:56:26 +00:00
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
Where a `request` is available (i.e. endpoints and middleware), the app is available on `request.app`.
|