Movatterモバイル変換


[0]ホーム

URL:


Skip to content
❤️ Support Starlette viasponsors! 📚 Do you like the new docs?Let us know!

Websockets

Starlette includes aWebSocket class that fulfils a similar roleto the HTTP request, but that allows sending and receiving data on a websocket.

WebSocket

Signature:WebSocket(scope, receive=None, send=None)

fromstarlette.websocketsimportWebSocketasyncdefapp(scope,receive,send):websocket=WebSocket(scope=scope,receive=receive,send=send)awaitwebsocket.accept()awaitwebsocket.send_text('Hello, world!')awaitwebsocket.close()

WebSockets present a mapping interface, so you can use them in the sameway as ascope.

For instance:websocket['path'] will return the ASGI path.

URL

The websocket URL is accessed aswebsocket.url.

The property is actually a subclass ofstr, and also exposes all thecomponents that can be parsed out of the URL.

For example:websocket.url.path,websocket.url.port,websocket.url.scheme.

Headers

Headers are exposed as an immutable, case-insensitive, multi-dict.

For example:websocket.headers['sec-websocket-version']

Query Parameters

Query parameters are exposed as an immutable multi-dict.

For example:websocket.query_params['search']

Path Parameters

Router path parameters are exposed as a dictionary interface.

For example:websocket.path_params['username']

Accepting the connection

  • await websocket.accept(subprotocol=None, headers=None)

Sending data

  • await websocket.send_text(data)
  • await websocket.send_bytes(data)
  • await websocket.send_json(data)

JSON messages default to being sent over text data frames, from version 0.10.0 onwards.Usewebsocket.send_json(data, mode="binary") to send JSON over binary data frames.

Receiving data

  • await websocket.receive_text()
  • await websocket.receive_bytes()
  • await websocket.receive_json()

May raisestarlette.websockets.WebSocketDisconnect().

JSON messages default to being received over text data frames, from version 0.10.0 onwards.Usewebsocket.receive_json(data, mode="binary") to receive JSON over binary data frames.

Iterating data

  • websocket.iter_text()
  • websocket.iter_bytes()
  • websocket.iter_json()

Similar toreceive_text,receive_bytes, andreceive_json but returns anasync iterator.

fromstarlette.websocketsimportWebSocketasyncdefapp(scope,receive,send):websocket=WebSocket(scope=scope,receive=receive,send=send)awaitwebsocket.accept()asyncformessageinwebsocket.iter_text():awaitwebsocket.send_text(f"Message text was:{message}")awaitwebsocket.close()

Whenstarlette.websockets.WebSocketDisconnect is raised, the iterator will exit.

Closing the connection

  • await websocket.close(code=1000, reason=None)

Sending and receiving messages

If you need to send or receive raw ASGI messages then you should usewebsocket.send() andwebsocket.receive() rather than using the rawsend andreceive callables. This will ensure that the websocket's state is keptcorrectly updated.

  • await websocket.send(message)
  • await websocket.receive()

Send Denial Response

If you callwebsocket.close() before callingwebsocket.accept() thenthe server will automatically send a HTTP 403 error to the client.

If you want to send a different error response, you can use thewebsocket.send_denial_response() method. This will send the responseand then close the connection.

  • await websocket.send_denial_response(response)

This requires the ASGI server to support the WebSocket Denial Responseextension. If it is not supported aRuntimeError will be raised.

In the context ofStarlette, you can also use theHTTPException to achieve the same result.

fromstarlette.applicationsimportStarlettefromstarlette.exceptionsimportHTTPExceptionfromstarlette.routingimportWebSocketRoutefromstarlette.websocketsimportWebSocketdefis_authorized(subprotocols:list[str]):iflen(subprotocols)!=2:returnFalseifsubprotocols[0]!="Authorization":returnFalse# Here we are hard coding the token, in a real application you would validate the token# against a database or an external service.ifsubprotocols[1]!="token":returnFalsereturnTrueasyncdefwebsocket_endpoint(websocket:WebSocket):subprotocols=websocket.scope["subprotocols"]ifnotis_authorized(subprotocols):raiseHTTPException(status_code=401,detail="Unauthorized")awaitwebsocket.accept("Authorization")awaitwebsocket.send_text("Hello, world!")awaitwebsocket.close()app=Starlette(debug=True,routes=[WebSocketRoute("/ws",websocket_endpoint)])

[8]ページ先頭

©2009-2026 Movatter.jp