Movatterモバイル変換


[0]ホーム

URL:


Saltar a contenido
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

WebSockets

When defining WebSockets, you normally declare a parameter of typeWebSocket and with it you can read data from the client and send data to it.

Read more about it in theFastAPI docs for WebSockets

It is provided directly by Starlette, but you can import it fromfastapi:

fromfastapiimportWebSocket

Tip

When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes anHTTPConnection instead of aRequest or aWebSocket.

fastapi.WebSocket

WebSocket(scope,receive,send)

Bases:HTTPConnection

Source code instarlette/websockets.py
27282930313233
def__init__(self,scope:Scope,receive:Receive,send:Send)->None:super().__init__(scope)assertscope["type"]=="websocket"self._receive=receiveself._send=sendself.client_state=WebSocketState.CONNECTINGself.application_state=WebSocketState.CONNECTING

scopeinstance-attribute

scope=scope

appproperty

app

urlproperty

url

base_urlproperty

base_url

headersproperty

headers

query_paramsproperty

query_params

path_paramsproperty

path_params

cookiesproperty

cookies

clientproperty

client

stateproperty

state

client_stateinstance-attribute

client_state=CONNECTING

application_stateinstance-attribute

application_state=CONNECTING

url_for

url_for(name,/,**path_params)
Source code instarlette/requests.py
192193194195196197
defurl_for(self,name:str,/,**path_params:Any)->URL:url_path_provider:Router|Starlette|None=self.scope.get("router")orself.scope.get("app")ifurl_path_providerisNone:raiseRuntimeError("The `url_for` method can only be used inside a Starlette application or with a router.")url_path=url_path_provider.url_path_for(name,**path_params)returnurl_path.make_absolute_url(base_url=self.base_url)

receiveasync

receive()

Receive ASGI websocket messages, ensuring valid state transitions.

Source code instarlette/websockets.py
3536373839404142434445464748495051525354555657
asyncdefreceive(self)->Message:"""    Receive ASGI websocket messages, ensuring valid state transitions.    """ifself.client_state==WebSocketState.CONNECTING:message=awaitself._receive()message_type=message["type"]ifmessage_type!="websocket.connect":raiseRuntimeError(f'Expected ASGI message "websocket.connect", but got{message_type!r}')self.client_state=WebSocketState.CONNECTEDreturnmessageelifself.client_state==WebSocketState.CONNECTED:message=awaitself._receive()message_type=message["type"]ifmessage_typenotin{"websocket.receive","websocket.disconnect"}:raiseRuntimeError(f'Expected ASGI message "websocket.receive" or "websocket.disconnect", but got{message_type!r}')ifmessage_type=="websocket.disconnect":self.client_state=WebSocketState.DISCONNECTEDreturnmessageelse:raiseRuntimeError('Cannot call "receive" once a disconnect message has been received.')

sendasync

send(message)

Send ASGI websocket messages, ensuring valid state transitions.

Source code instarlette/websockets.py
59606162636465666768697071727374757677787980818283848586878889909192939495969798
asyncdefsend(self,message:Message)->None:"""    Send ASGI websocket messages, ensuring valid state transitions.    """ifself.application_state==WebSocketState.CONNECTING:message_type=message["type"]ifmessage_typenotin{"websocket.accept","websocket.close","websocket.http.response.start"}:raiseRuntimeError('Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", 'f"but got{message_type!r}")ifmessage_type=="websocket.close":self.application_state=WebSocketState.DISCONNECTEDelifmessage_type=="websocket.http.response.start":self.application_state=WebSocketState.RESPONSEelse:self.application_state=WebSocketState.CONNECTEDawaitself._send(message)elifself.application_state==WebSocketState.CONNECTED:message_type=message["type"]ifmessage_typenotin{"websocket.send","websocket.close"}:raiseRuntimeError(f'Expected ASGI message "websocket.send" or "websocket.close", but got{message_type!r}')ifmessage_type=="websocket.close":self.application_state=WebSocketState.DISCONNECTEDtry:awaitself._send(message)exceptOSError:self.application_state=WebSocketState.DISCONNECTEDraiseWebSocketDisconnect(code=1006)elifself.application_state==WebSocketState.RESPONSE:message_type=message["type"]ifmessage_type!="websocket.http.response.body":raiseRuntimeError(f'Expected ASGI message "websocket.http.response.body", but got{message_type!r}')ifnotmessage.get("more_body",False):self.application_state=WebSocketState.DISCONNECTEDawaitself._send(message)else:raiseRuntimeError('Cannot call "send" once a close message has been sent.')

acceptasync

accept(subprotocol=None,headers=None)
Source code instarlette/websockets.py
100101102103104105106107108109110
asyncdefaccept(self,subprotocol:str|None=None,headers:Iterable[tuple[bytes,bytes]]|None=None,)->None:headers=headersor[]ifself.client_state==WebSocketState.CONNECTING:# pragma: no branch# If we haven't yet seen the 'connect' message, then wait for it first.awaitself.receive()awaitself.send({"type":"websocket.accept","subprotocol":subprotocol,"headers":headers})

receive_textasync

receive_text()
Source code instarlette/websockets.py
116117118119120121
asyncdefreceive_text(self)->str:ifself.application_state!=WebSocketState.CONNECTED:raiseRuntimeError('WebSocket is not connected. Need to call "accept" first.')message=awaitself.receive()self._raise_on_disconnect(message)returncast(str,message["text"])

receive_bytesasync

receive_bytes()
Source code instarlette/websockets.py
123124125126127128
asyncdefreceive_bytes(self)->bytes:ifself.application_state!=WebSocketState.CONNECTED:raiseRuntimeError('WebSocket is not connected. Need to call "accept" first.')message=awaitself.receive()self._raise_on_disconnect(message)returncast(bytes,message["bytes"])

receive_jsonasync

receive_json(mode='text')
Source code instarlette/websockets.py
130131132133134135136137138139140141142
asyncdefreceive_json(self,mode:str="text")->Any:ifmodenotin{"text","binary"}:raiseRuntimeError('The "mode" argument should be "text" or "binary".')ifself.application_state!=WebSocketState.CONNECTED:raiseRuntimeError('WebSocket is not connected. Need to call "accept" first.')message=awaitself.receive()self._raise_on_disconnect(message)ifmode=="text":text=message["text"]else:text=message["bytes"].decode("utf-8")returnjson.loads(text)

iter_textasync

iter_text()
Source code instarlette/websockets.py
144145146147148149
asyncdefiter_text(self)->AsyncIterator[str]:try:whileTrue:yieldawaitself.receive_text()exceptWebSocketDisconnect:pass

iter_bytesasync

iter_bytes()
Source code instarlette/websockets.py
151152153154155156
asyncdefiter_bytes(self)->AsyncIterator[bytes]:try:whileTrue:yieldawaitself.receive_bytes()exceptWebSocketDisconnect:pass

iter_jsonasync

iter_json()
Source code instarlette/websockets.py
158159160161162163
asyncdefiter_json(self)->AsyncIterator[Any]:try:whileTrue:yieldawaitself.receive_json()exceptWebSocketDisconnect:pass

send_textasync

send_text(data)
Source code instarlette/websockets.py
165166
asyncdefsend_text(self,data:str)->None:awaitself.send({"type":"websocket.send","text":data})

send_bytesasync

send_bytes(data)
Source code instarlette/websockets.py
168169
asyncdefsend_bytes(self,data:bytes)->None:awaitself.send({"type":"websocket.send","bytes":data})

send_jsonasync

send_json(data,mode='text')
Source code instarlette/websockets.py
171172173174175176177178
asyncdefsend_json(self,data:Any,mode:str="text")->None:ifmodenotin{"text","binary"}:raiseRuntimeError('The "mode" argument should be "text" or "binary".')text=json.dumps(data,separators=(",",":"),ensure_ascii=False)ifmode=="text":awaitself.send({"type":"websocket.send","text":text})else:awaitself.send({"type":"websocket.send","bytes":text.encode("utf-8")})

closeasync

close(code=1000,reason=None)
Source code instarlette/websockets.py
180181
asyncdefclose(self,code:int=1000,reason:str|None=None)->None:awaitself.send({"type":"websocket.close","code":code,"reason":reasonor""})

WebSockets - additional classes

Additional classes for handling WebSockets.

Provided directly by Starlette, but you can import it fromfastapi:

fromfastapi.websocketsimportWebSocketDisconnect,WebSocketState

fastapi.websockets.WebSocketDisconnect

WebSocketDisconnect(code=1000,reason=None)

Bases:Exception

Source code instarlette/websockets.py
212223
def__init__(self,code:int=1000,reason:str|None=None)->None:self.code=codeself.reason=reasonor""

codeinstance-attribute

code=code

reasoninstance-attribute

reason=reasonor''

When a client disconnects, aWebSocketDisconnect exception is raised, you can catch it.

You can import it directly formfastapi:

fromfastapiimportWebSocketDisconnect

Read more about it in theFastAPI docs for WebSockets

fastapi.websockets.WebSocketState

Bases:Enum

CONNECTINGclass-attributeinstance-attribute

CONNECTING=0

CONNECTEDclass-attributeinstance-attribute

CONNECTED=1

DISCONNECTEDclass-attributeinstance-attribute

DISCONNECTED=2

RESPONSEclass-attributeinstance-attribute

RESPONSE=3

WebSocketState is an enumeration of the possible states of a WebSocket connection.


[8]ページ先頭

©2009-2026 Movatter.jp