Skip to content

Commit 26fef0f

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent c9ed082 commit 26fef0f

File tree

3 files changed

+60
-50
lines changed

3 files changed

+60
-50
lines changed

integration_tests/base_routes.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from typing import Optional
88

99
from integration_tests.subroutes import di_subrouter, sub_router
10-
from robyn import Headers, Request, Response, Robyn, SSEMessage, SSEResponse, WebSocketConnector, WebSocketDisconnect, jsonify, serve_file, serve_html
10+
from robyn import Headers, Request, Response, Robyn, SSEMessage, SSEResponse, WebSocketDisconnect, jsonify, serve_file, serve_html
1111
from robyn.authentication import AuthenticationHandler, BearerGetter, Identity
1212
from robyn.robyn import QueryParams, Url
1313
from robyn.templating import JinjaTemplate
@@ -28,14 +28,14 @@
2828
@app.websocket("/web_socket")
2929
async def websocket_endpoint(websocket):
3030
await websocket.accept()
31-
31+
3232
try:
3333
while True:
3434
msg = await websocket.receive_text()
3535
websocket_id = websocket._connector.id
3636
global websocket_state
3737
state = websocket_state[websocket_id]
38-
38+
3939
if state == 0:
4040
await websocket._connector.async_broadcast("This is a broadcast message")
4141
await websocket.send_text("This is a message to self")
@@ -50,9 +50,9 @@ async def websocket_endpoint(websocket):
5050
await websocket.send_text("Connection closed")
5151
await websocket.close()
5252
break
53-
53+
5454
websocket_state[websocket_id] = (state + 1) % 4
55-
55+
5656
except WebSocketDisconnect:
5757
pass
5858

@@ -62,7 +62,7 @@ def websocket_on_connect(websocket):
6262
return "Hello world, from ws"
6363

6464

65-
@websocket_endpoint.on_close
65+
@websocket_endpoint.on_close
6666
def websocket_on_close(websocket):
6767
return "GoodBye world, from ws"
6868

@@ -71,25 +71,25 @@ def websocket_on_close(websocket):
7171
@app.websocket("/web_socket_json")
7272
async def json_websocket_endpoint(websocket):
7373
await websocket.accept()
74-
74+
7575
try:
7676
while True:
7777
msg = await websocket.receive_text()
7878
websocket_id = websocket._connector.id
7979
response = {"ws_id": websocket_id, "resp": "", "msg": msg}
8080
global websocket_state
8181
state = websocket_state[websocket_id]
82-
82+
8383
if state == 0:
8484
response["resp"] = "Whaaat??"
8585
elif state == 1:
8686
response["resp"] = "Whooo??"
8787
elif state == 2:
8888
response["resp"] = "*chika* *chika* Slim Shady."
89-
89+
9090
websocket_state[websocket_id] = (state + 1) % 3
9191
await websocket.send_json(response)
92-
92+
9393
except WebSocketDisconnect:
9494
pass
9595

@@ -108,13 +108,13 @@ def json_websocket_on_close(websocket):
108108
@app.websocket("/web_socket_di")
109109
async def di_websocket_endpoint(websocket):
110110
await websocket.accept()
111-
111+
112112
try:
113113
while True:
114114
await websocket.receive_text()
115115
# Just echo back an empty response for DI test
116116
await websocket.send_text("")
117-
117+
118118
except WebSocketDisconnect:
119119
pass
120120

robyn/__init__.py

Lines changed: 38 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
class WebSocketDisconnect(Exception):
3434
"""Exception raised when a WebSocket connection is disconnected."""
35-
35+
3636
def __init__(self, code: int = 1000, reason: str = ""):
3737
self.code = code
3838
self.reason = reason
@@ -44,28 +44,28 @@ class WebSocketAdapter:
4444
Adapter class that provides a modern WebSocket interface
4545
wrapping Robyn's WebSocketConnector for compatibility.
4646
"""
47-
47+
4848
def __init__(self, websocket_connector: WebSocketConnector, message: str = None):
4949
self._connector = websocket_connector
5050
self._message = message
5151
self._accepted = False
52-
52+
5353
async def accept(self):
5454
"""Accept the WebSocket connection (no-op in Robyn as it's auto-accepted)"""
5555
self._accepted = True
56-
56+
5757
async def close(self, code: int = 1000):
5858
"""Close the WebSocket connection"""
5959
self._connector.close()
60-
60+
6161
async def send_text(self, data: str):
6262
"""Send text data to the WebSocket"""
6363
await self._connector.async_send_to(self._connector.id, data)
64-
64+
6565
async def send_bytes(self, data: bytes):
6666
"""Send binary data to the WebSocket"""
67-
await self._connector.async_send_to(self._connector.id, data.decode('utf-8'))
68-
67+
await self._connector.async_send_to(self._connector.id, data.decode("utf-8"))
68+
6969
async def receive_text(self) -> str:
7070
"""Receive text data from the WebSocket"""
7171
if self._message is not None:
@@ -75,42 +75,44 @@ async def receive_text(self) -> str:
7575
# Note: In a real implementation, this would need to handle the message queue
7676
# For now, we return the current message if available
7777
return ""
78-
78+
7979
async def receive_bytes(self) -> bytes:
8080
"""Receive binary data from the WebSocket"""
8181
text = await self.receive_text()
82-
return text.encode('utf-8')
83-
82+
return text.encode("utf-8")
83+
8484
async def send_json(self, data):
8585
"""Send JSON data to the WebSocket"""
8686
import json
87+
8788
await self.send_text(json.dumps(data))
88-
89+
8990
async def receive_json(self):
9091
"""Receive JSON data from the WebSocket"""
9192
import json
93+
9294
text = await self.receive_text()
9395
return json.loads(text) if text else None
94-
96+
9597
@property
9698
def query_params(self):
9799
"""Access query parameters"""
98100
return self._connector.query_params
99-
101+
100102
@property
101103
def path_params(self):
102104
"""Access path parameters"""
103-
return getattr(self._connector, 'path_params', {})
104-
105+
return getattr(self._connector, "path_params", {})
106+
105107
@property
106108
def headers(self):
107109
"""Access request headers"""
108-
return getattr(self._connector, 'headers', {})
109-
110+
return getattr(self._connector, "headers", {})
111+
110112
@property
111113
def client(self):
112114
"""Client information"""
113-
return getattr(self._connector, 'client', None)
115+
return getattr(self._connector, "client", None)
114116

115117

116118
def _normalize_endpoint(endpoint: str) -> str:
@@ -367,28 +369,29 @@ def websocket(self, endpoint: str):
367369
"""
368370
Modern WebSocket decorator that accepts a single handler function.
369371
The handler function receives a WebSocket object and can optionally have on_connect and on_close callbacks.
370-
372+
371373
Usage:
372374
@app.websocket("/ws")
373375
async def websocket_endpoint(websocket):
374376
await websocket.accept()
375377
while True:
376378
data = await websocket.receive_text()
377379
await websocket.send_text(f"Echo: {data}")
378-
380+
379381
# With optional callbacks:
380382
@websocket_endpoint.on_connect
381383
async def on_connect(websocket):
382384
await websocket.send_text("Connected!")
383-
384-
@websocket_endpoint.on_close
385+
386+
@websocket_endpoint.on_close
385387
async def on_close(websocket):
386388
print("Disconnected")
387389
"""
390+
388391
def decorator(handler):
389392
# Dictionary to store handlers for this WebSocket endpoint
390393
handlers = {}
391-
394+
392395
# Create the main message handler
393396
async def message_handler(websocket_connector, msg, *args, **kwargs):
394397
# Convert WebSocketConnector to modern WebSocket interface
@@ -405,53 +408,53 @@ async def message_handler(websocket_connector, msg, *args, **kwargs):
405408
if "connection closed" in str(e).lower() or "websocket" in str(e).lower():
406409
return ""
407410
raise e
408-
411+
409412
# Create FunctionInfo for the message handler
410413
params = dict(inspect.signature(message_handler).parameters)
411414
num_params = len(params)
412415
is_async = asyncio.iscoroutinefunction(message_handler)
413416
injected_dependencies = self.dependencies.get_dependency_map(self)
414-
417+
415418
handlers["message"] = FunctionInfo(message_handler, is_async, num_params, params, kwargs=injected_dependencies)
416-
419+
417420
# Add methods to the handler to allow attaching on_connect and on_close
418421
def add_on_connect(connect_handler):
419422
def connect_wrapper(websocket_connector, *args, **kwargs):
420423
websocket_adapter = WebSocketAdapter(websocket_connector)
421424
if asyncio.iscoroutinefunction(connect_handler):
422425
return asyncio.create_task(connect_handler(websocket_adapter))
423426
return connect_handler(websocket_adapter)
424-
427+
425428
# Create FunctionInfo for connect handler
426429
connect_params = dict(inspect.signature(connect_wrapper).parameters)
427430
connect_num_params = len(connect_params)
428431
connect_is_async = asyncio.iscoroutinefunction(connect_wrapper)
429432
handlers["connect"] = FunctionInfo(connect_wrapper, connect_is_async, connect_num_params, connect_params, kwargs=injected_dependencies)
430433
return connect_handler
431-
434+
432435
def add_on_close(close_handler):
433436
def close_wrapper(websocket_connector, *args, **kwargs):
434437
websocket_adapter = WebSocketAdapter(websocket_connector)
435438
if asyncio.iscoroutinefunction(close_handler):
436439
return asyncio.create_task(close_handler(websocket_adapter))
437440
return close_handler(websocket_adapter)
438-
441+
439442
# Create FunctionInfo for close handler
440443
close_params = dict(inspect.signature(close_wrapper).parameters)
441444
close_num_params = len(close_params)
442445
close_is_async = asyncio.iscoroutinefunction(close_wrapper)
443446
handlers["close"] = FunctionInfo(close_wrapper, close_is_async, close_num_params, close_params, kwargs=injected_dependencies)
444447
return close_handler
445-
448+
446449
# Attach methods to the handler function
447450
handler.on_connect = add_on_connect
448451
handler.on_close = add_on_close
449452
handler._ws_handlers = handlers # Store reference to handlers dict
450-
453+
451454
# Add the WebSocket to the router
452455
self.add_web_socket(endpoint, handlers)
453456
return handler
454-
457+
455458
return decorator
456459

457460
def _add_event_handler(self, event_type: Events, handler: Callable) -> None:
@@ -859,15 +862,15 @@ def websocket(self, endpoint: str):
859862
"""
860863
Modern WebSocket decorator for SubRouter that accepts a single handler function.
861864
Works the same as the main Robyn websocket decorator but with prefix support.
862-
865+
863866
Usage:
864867
@subrouter.websocket("/ws")
865868
async def websocket_endpoint(websocket):
866869
await websocket.accept()
867870
while True:
868871
data = await websocket.receive_text()
869872
await websocket.send_text(f"Echo: {data}")
870-
873+
871874
# With optional callbacks:
872875
@websocket_endpoint.on_connect
873876
async def on_connect(websocket):

websocket_example.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@
77

88
app = Robyn(__file__)
99

10+
1011
# Define the main WebSocket handler
1112
@app.websocket("/ws")
1213
async def websocket_endpoint(websocket):
1314
await websocket.accept()
14-
15+
1516
try:
1617
while True:
1718
data = await websocket.receive_text()
@@ -24,23 +25,28 @@ async def websocket_endpoint(websocket):
2425
except WebSocketDisconnect:
2526
print("Client disconnected")
2627

28+
2729
# Now you can add on_connect and on_close handlers to websocket_endpoint
2830
@websocket_endpoint.on_connect
2931
async def on_connect(websocket):
3032
await websocket.send_text("Welcome! You are now connected.")
3133
print("New client connected")
3234

33-
@websocket_endpoint.on_close
35+
36+
@websocket_endpoint.on_close
3437
async def on_close(websocket):
3538
print("Client disconnected from WebSocket")
3639

40+
3741
# You can also add handlers programmatically:
3842
def another_connect_handler(websocket):
3943
print("Another connect handler called")
4044

45+
4146
# This would override the previous on_connect handler
4247
# websocket_endpoint.on_connect(another_connect_handler)
4348

49+
4450
@app.get("/")
4551
def index():
4652
return """
@@ -50,7 +56,8 @@ def index():
5056
<p>Send 'close' to disconnect</p>
5157
"""
5258

59+
5360
if __name__ == "__main__":
5461
print("Starting WebSocket server...")
5562
print("Connect to: ws://localhost:8080/ws")
56-
app.start(host="0.0.0.0", port=8080)
63+
app.start(host="0.0.0.0", port=8080)

0 commit comments

Comments
 (0)