2018-08-30 12:53:37 +00:00
|
|
|
|
2018-09-05 09:29:04 +00:00
|
|
|
Starlette includes an `HTTPEndpoint` class that provides a class-based view pattern which
|
2018-08-30 12:53:37 +00:00
|
|
|
handles HTTP method dispatching.
|
|
|
|
|
2018-09-05 09:29:04 +00:00
|
|
|
The `HTTPEndpoint` class can be used as an ASGI application:
|
2018-08-30 12:53:37 +00:00
|
|
|
|
|
|
|
```python
|
2018-09-05 09:29:04 +00:00
|
|
|
from starlette.responses import PlainTextResponse
|
|
|
|
from starlette.endpoints import HTTPEndpoint
|
2018-08-30 12:53:37 +00:00
|
|
|
|
|
|
|
|
2018-09-05 09:29:04 +00:00
|
|
|
class App(HTTPEndpoint):
|
2018-08-30 12:53:37 +00:00
|
|
|
async def get(self, request):
|
|
|
|
return PlainTextResponse(f"Hello, world!")
|
|
|
|
```
|
|
|
|
|
|
|
|
If you're using a Starlette application instance to handle routing, you can
|
2018-09-05 09:29:04 +00:00
|
|
|
dispatch to an `HTTPEndpoint` class by using the `@app.route()` decorator, or the
|
2018-08-30 12:53:37 +00:00
|
|
|
`app.add_route()` function. Make sure to dispatch to the class itself, rather
|
|
|
|
than to an instance of the class:
|
|
|
|
|
|
|
|
```python
|
2018-09-05 11:50:00 +00:00
|
|
|
from starlette.applications import Starlette
|
|
|
|
from starlette.responses import PlainTextResponse
|
2018-09-05 09:29:04 +00:00
|
|
|
from starlette.endpoints import HTTPEndpoint
|
2018-08-30 12:53:37 +00:00
|
|
|
|
|
|
|
|
2018-09-05 09:29:04 +00:00
|
|
|
app = Starlette()
|
2018-08-30 12:53:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
@app.route("/")
|
2018-09-05 09:29:04 +00:00
|
|
|
class Homepage(HTTPEndpoint):
|
2018-08-30 12:53:37 +00:00
|
|
|
async def get(self, request):
|
|
|
|
return PlainTextResponse(f"Hello, world!")
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/{username}")
|
2018-09-05 09:29:04 +00:00
|
|
|
class User(HTTPEndpoint):
|
2018-08-30 12:53:37 +00:00
|
|
|
async def get(self, request, username):
|
|
|
|
return PlainTextResponse(f"Hello, {username}")
|
|
|
|
```
|
|
|
|
|
2018-09-05 09:29:04 +00:00
|
|
|
HTTP endpoint classes will respond with "405 Method not allowed" responses for any
|
2018-08-30 12:53:37 +00:00
|
|
|
request methods which do not map to a corresponding handler.
|