2018-08-30 12:53:37 +00:00
|
|
|
|
2018-10-02 10:26:19 +00:00
|
|
|
Starlette includes the classes `HTTPEndpoint` and `WebSocketEndpoint` that provide a class-based view pattern for
|
|
|
|
handling HTTP method dispatching and WebSocket sessions.
|
|
|
|
|
|
|
|
### HTTPEndpoint
|
2018-08-30 12:53:37 +00:00
|
|
|
|
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.
|
2018-10-02 10:26:19 +00:00
|
|
|
|
|
|
|
### WebSocketEndpoint
|
|
|
|
|
|
|
|
The `WebSocketEndpoint` class is an ASGI application that presents a wrapper around
|
2018-10-02 10:30:54 +00:00
|
|
|
the functionality of a `WebSocket` instance.
|
2018-10-02 10:26:19 +00:00
|
|
|
|
|
|
|
The ASGI connection scope is accessible on the endpoint instance via `.scope` and
|
2018-10-02 10:30:54 +00:00
|
|
|
has an attribute `encoding` which may optionally be set, in order to validate the expected websocket data in the `on_receive` method.
|
2018-10-02 10:26:19 +00:00
|
|
|
|
|
|
|
The encoding types are:
|
|
|
|
|
2018-10-02 10:30:54 +00:00
|
|
|
* `'json'`
|
|
|
|
* `'bytes'`
|
|
|
|
* `'text'`
|
2018-10-02 10:26:19 +00:00
|
|
|
|
|
|
|
There are three overridable methods for handling specific ASGI websocket message types:
|
|
|
|
|
|
|
|
* `async def on_connect(websocket, **kwargs)`
|
|
|
|
* `async def on_receive(websocket, data)`
|
|
|
|
* `async def on_disconnect(websocket, close_code)`
|
|
|
|
|
|
|
|
```python
|
|
|
|
from starlette.endpoints import WebSocketEndpoint
|
|
|
|
|
|
|
|
|
|
|
|
class App(WebSocketEndpoint):
|
|
|
|
encoding = 'bytes'
|
|
|
|
|
|
|
|
async def on_connect(self, websocket, **kwargs):
|
|
|
|
await websocket.accept()
|
|
|
|
|
|
|
|
async def on_receive(self, websocket, data):
|
2018-10-02 10:30:54 +00:00
|
|
|
await websocket.send_bytes(b"Message: " + data)
|
2018-10-02 10:26:19 +00:00
|
|
|
|
|
|
|
async def on_disconnect(self, websocket, close_code):
|
2018-10-02 10:30:54 +00:00
|
|
|
pass
|
2018-10-02 10:26:19 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
The `WebSocketEndpoint` can also be used with the `Starlette` application class:
|
|
|
|
|
|
|
|
```python
|
|
|
|
import uvicorn
|
|
|
|
from starlette.applications import Starlette
|
|
|
|
from starlette.endpoints import WebSocketEndpoint, HTTPEndpoint
|
|
|
|
from starlette.responses import HTMLResponse
|
|
|
|
|
|
|
|
app = Starlette()
|
|
|
|
|
|
|
|
html = """
|
|
|
|
<!DOCTYPE html>
|
|
|
|
<html>
|
|
|
|
<head>
|
|
|
|
<title>Chat</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>WebSocket Chat</h1>
|
|
|
|
<form action="" onsubmit="sendMessage(event)">
|
|
|
|
<input type="text" id="messageText" autocomplete="off"/>
|
|
|
|
<button>Send</button>
|
|
|
|
</form>
|
|
|
|
<ul id='messages'>
|
|
|
|
</ul>
|
|
|
|
<script>
|
|
|
|
var ws = new WebSocket("ws://localhost:8000/ws");
|
|
|
|
ws.onmessage = function(event) {
|
|
|
|
var messages = document.getElementById('messages')
|
|
|
|
var message = document.createElement('li')
|
|
|
|
var content = document.createTextNode(event.data)
|
|
|
|
message.appendChild(content)
|
|
|
|
messages.appendChild(message)
|
|
|
|
};
|
|
|
|
function sendMessage(event) {
|
|
|
|
var input = document.getElementById("messageText")
|
|
|
|
ws.send(input.value)
|
|
|
|
input.value = ''
|
|
|
|
event.preventDefault()
|
|
|
|
}
|
|
|
|
</script>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/")
|
2018-10-02 10:30:54 +00:00
|
|
|
class Homepage(HTTPEndpoint):
|
2018-10-02 10:26:19 +00:00
|
|
|
async def get(self, request):
|
|
|
|
return HTMLResponse(html)
|
|
|
|
|
|
|
|
|
|
|
|
@app.websocket_route("/ws")
|
2018-10-02 10:30:54 +00:00
|
|
|
class Echo(WebSocketEndpoint):
|
2018-10-02 10:26:19 +00:00
|
|
|
|
|
|
|
encoding = "text"
|
|
|
|
|
|
|
|
async def on_receive(self, websocket, data):
|
|
|
|
await websocket.send_text(f"Message text was: {data}")
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
```
|