Skip to content

端点

Starlette 包含 HTTPEndpointWebSocketEndpoint 类,它们为处理 HTTP 方法调度和 WebSocket 会话提供了基于类的视图模式。

HTTP 端点

HTTPEndpoint 类可用作 ASGI 应用程序:

from starlette.responses import PlainTextResponse
from starlette.endpoints import HTTPEndpoint


class App(HTTPEndpoint):
    async def get(self, request):
        return PlainTextResponse(f"Hello, world!")

如果您正在使用 Starlette 应用程序实例来处理路由,您可以调度到一个 HTTPEndpoint 类。请确保调度到类本身,而不是类的实例:

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.endpoints import HTTPEndpoint
from starlette.routing import Route


class Homepage(HTTPEndpoint):
    async def get(self, request):
        return PlainTextResponse(f"Hello, world!")


class User(HTTPEndpoint):
    async def get(self, request):
        username = request.path_params['username']
        return PlainTextResponse(f"Hello, {username}")

routes = [
    Route("/", Homepage),
    Route("/{username}", User)
]

app = Starlette(routes=routes)

对于任何未映射到相应处理程序的请求方法,HTTP 端点类将以“405 方法不允许”响应进行响应。

WebSocket 端点

WebSocketEndpoint 类是一个 ASGI 应用程序,它围绕 WebSocket 实例的功能提供了一个包装器。

在端点实例上可通过 .scope 访问 ASGI 连接范围,并且它具有一个属性 encoding ,为了在 on_receive 方法中验证预期的 WebSocket 数据,该属性可以选择进行设置。

编码类型为:

  • 'json'
  • 'bytes'
  • 'text'

有三种可重写的方法来处理特定的 ASGI WebSocket 消息类型:

  • async def on_connect(websocket, **kwargs)
  • async def on_receive(websocket, data)
  • async def on_disconnect(websocket, close_code)

    from starlette.endpoints import WebSocketEndpoint

    class App(WebSocketEndpoint): encoding = 'bytes'

    async def on_connect(self, websocket):
        await websocket.accept()
    
    async def on_receive(self, websocket, data):
        await websocket.send_bytes(b"Message: " + data)
    
    async def on_disconnect(self, websocket, close_code):
        pass
    

WebSocketEndpoint 也可与 Starlette 应用程序类一起使用:

import uvicorn
from starlette.applications import Starlette
from starlette.endpoints import WebSocketEndpoint, HTTPEndpoint
from starlette.responses import HTMLResponse
from starlette.routing import Route, WebSocketRoute


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>
"""

class Homepage(HTTPEndpoint):
    async def get(self, request):
        return HTMLResponse(html)

class Echo(WebSocketEndpoint):
    encoding = "text"

    async def on_receive(self, websocket, data):
        await websocket.send_text(f"Message text was: {data}")

routes = [
    Route("/", Homepage),
    WebSocketRoute("/ws", Echo)
]

app = Starlette(routes=routes)