Applications
Starlette contains an application class Starlette that ties all its other functions together nicely.
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route, Mount, WebSocketRoute
from starlette.staticfiles import StaticFiles
def homepage(request):
return PlainTextResponse('Hello, world!')
def user_me(request):
username = "John Doe"
return PlainTextResponse('Hello, %s!' % username)
def user(request):
username = request.path_params['username']
return PlainTextResponse('Hello, %s!' % username)
async def websocket_endpoint(websocket):
await websocket.accept()
await websocket.send_text('Hello, websocket!')
await websocket.close()
def startup():
print('Ready to go')
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, on_startup=[startup])
Instantiate an application
::: starlette.applications.Starlette :文档字符串
Storing state on application instances
You can use the generic app.state attribute to store any additional state on an application instance.
For example:
app.state.ADMIN_EMAIL = 'admin@example.org'
Access to application instances
Where request is available (i.e. endpoints and middleware), the application is available on request.app.