Skip to content

Commit b59bd5d

Browse files
committed
refactor: replace hardcode sendEchoMessage method in py websocket client
1 parent d39b8c7 commit b59bd5d

File tree

8 files changed

+103
-119
lines changed

8 files changed

+103
-119
lines changed

packages/templates/clients/websocket/python/components/ClientClass.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ import { Connect } from './Connect';
44
import { RegisterMessageHandler } from './RegisterMessageHandler';
55
import { RegisterErrorHandler } from './RegisterErrorHandler';
66
import { HandleMessage } from './HandleMessage';
7-
import { SendEchoMessage } from './SendEchoMessage';
7+
import { SendOperation } from './SendOperation';
8+
import { Send } from './Send';
89
import { CloseConnection } from './CloseConnection';
910
import { RegisterOutgoingProcessor } from './RegisterOutgoingProcessor';
1011
import { HandleError } from './HandleError';
1112

12-
export function ClientClass({ clientName, serverUrl, title, queryParams }) {
13+
export function ClientClass({ clientName, serverUrl, title, queryParams, sendOperations }) {
1314
return (
1415
<Text>
1516
<Text newLines={2}>
@@ -22,7 +23,8 @@ export function ClientClass({ clientName, serverUrl, title, queryParams }) {
2223
<RegisterOutgoingProcessor />
2324
<HandleMessage />
2425
<HandleError />
25-
<SendEchoMessage />
26+
<SendOperation sendOperations={sendOperations} clientName={clientName} />
27+
{sendOperations.length > 0 && <Send />}
2628
<CloseConnection />
2729
</Text>
2830
);
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { Text } from '@asyncapi/generator-react-sdk';
2+
3+
export function Send() {
4+
return (
5+
<Text newLines={2} indent={2}>
6+
{
7+
`
8+
@staticmethod
9+
async def _send(message, socket):
10+
"""
11+
Internal helper to handle the actual sending logic.
12+
13+
Args:
14+
message (dict or str): The message to send.
15+
socket (websockets.WebSocketCommonProtocol): The WebSocket to send through.
16+
17+
Notes:
18+
If message is a dictionary, it will be automatically converted to JSON.
19+
"""
20+
try:
21+
if isinstance(message, dict):
22+
message = json.dumps(message)
23+
await socket.send(message)
24+
except Exception as e:
25+
print("Error sending:", e)`
26+
}
27+
</Text>
28+
);
29+
}

packages/templates/clients/websocket/python/components/SendEchoMessage.js

Lines changed: 0 additions & 54 deletions
This file was deleted.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { Text } from '@asyncapi/generator-react-sdk';
2+
3+
export function SendOperation({ sendOperations, clientName }) {
4+
if (!sendOperations || sendOperations.length === 0) {
5+
return null;
6+
}
7+
8+
return (
9+
<>
10+
{
11+
sendOperations.map((operation) => {
12+
const staticMethodName = `${operation.id()}_static`;
13+
14+
return (
15+
<Text newLines={2} indent={2}>
16+
{`async def ${operation.id()}(self, message):
17+
"""
18+
Send a ${operation.id()} message using the WebSocket connection attached to this instance.
19+
20+
Args:
21+
message (dict or str): The message to send. Will be serialized to JSON if it's a dictionary.
22+
23+
Raises:
24+
Exception: If sending fails or the socket is not connected.
25+
"""
26+
await self._send(message, self.ws_app)
27+
28+
@staticmethod
29+
async def ${staticMethodName}(message, socket):
30+
"""
31+
Send a ${operation.id()} message using a provided WebSocket connection, without needing an instance.
32+
33+
Args:
34+
message (dict or str): The message to send.
35+
socket (websockets.WebSocketCommonProtocol): The WebSocket to send through.
36+
37+
Raises:
38+
Exception: If sending fails or the socket is not connected.
39+
"""
40+
await ${clientName}._send(message, socket)
41+
`}
42+
</Text>
43+
);
44+
})
45+
}
46+
</>
47+
);
48+
}

packages/templates/clients/websocket/python/example.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def main():
3131
# Send multiple messages to test stream handling
3232
for i in range(5):
3333
message = f'Hello, Echo Yo! {i}'
34-
client.send_message(message)
34+
client.sendEchoMessage(message)
3535
time.sleep(2) # Wait for a response
3636

3737
# Keep program alive for a while to allow message processing

packages/templates/clients/websocket/python/template/client.py.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export default function ({ asyncapi, params }) {
1111
const queryParams = getQueryParams(asyncapi.channels());
1212
const clientName = getClientName(info, params.appendClientSuffix, params.customClientName);
1313
const serverUrl = getServerUrl(server);
14+
const sendOperations = asyncapi.operations().filterBySend();
1415
return (
1516
// The clientFileName default values can be found and modified under the package.json
1617
<File name={params.clientFileName}>
@@ -19,7 +20,7 @@ export default function ({ asyncapi, params }) {
1920
server={server}
2021
/>
2122
<Requires query={queryParams} />
22-
<ClientClass clientName={clientName} serverUrl={serverUrl} title={title} queryParams={queryParams} />
23+
<ClientClass clientName={clientName} serverUrl={serverUrl} title={title} queryParams={queryParams} sendOperations={sendOperations} />
2324
</File>
2425
);
2526
}

packages/templates/clients/websocket/python/test/__snapshots__/integration.test.js.snap

Lines changed: 17 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -723,51 +723,6 @@ class SlackWebsocketAPIClient:
723723
for handler in self.error_handlers:
724724
handler(error)
725725
726-
async def send_message(self, message):
727-
\\"\\"\\"
728-
Send a message using the WebSocket connection attached to this instance.
729-
730-
Args:
731-
message (dict or str): The message to send. Will be serialized to JSON if it's a dictionary.
732-
733-
Raises:
734-
Exception: If sending fails or the socket is not connected.
735-
\\"\\"\\"
736-
await self._send(message, self.ws_app)
737-
738-
@staticmethod
739-
async def send_message_static(message, socket):
740-
\\"\\"\\"
741-
Send a message using a provided WebSocket connection, without needing an instance.
742-
743-
Args:
744-
message (dict or str): The message to send.
745-
socket (websockets.WebSocketCommonProtocol): The WebSocket to send through.
746-
747-
Raises:
748-
Exception: If sending fails or the socket is not connected.
749-
\\"\\"\\"
750-
await HoppscotchEchoWebSocketClient._send(message, socket)
751-
752-
@staticmethod
753-
async def _send(message, socket):
754-
\\"\\"\\"
755-
Internal helper to handle the actual sending logic.
756-
757-
Args:
758-
message (dict or str): The message to send.
759-
socket (websockets.WebSocketCommonProtocol): The WebSocket to send through.
760-
761-
Notes:
762-
If message is a dictionary, it will be automatically converted to JSON.
763-
\\"\\"\\"
764-
try:
765-
if isinstance(message, dict):
766-
message = json.dumps(message)
767-
await socket.send(message)
768-
except Exception as e:
769-
print(\\"Error sending:\\", e)
770-
771726
def close(self):
772727
\\"\\"\\"Cleanly close the WebSocket connection.\\"\\"\\"
773728
self._stop_event.set()
@@ -904,9 +859,9 @@ class HoppscotchClient:
904859
for handler in self.error_handlers:
905860
handler(error)
906861
907-
async def send_message(self, message):
862+
async def sendEchoMessage(self, message):
908863
\\"\\"\\"
909-
Send a message using the WebSocket connection attached to this instance.
864+
Send a sendEchoMessage message using the WebSocket connection attached to this instance.
910865
911866
Args:
912867
message (dict or str): The message to send. Will be serialized to JSON if it's a dictionary.
@@ -917,9 +872,9 @@ class HoppscotchClient:
917872
await self._send(message, self.ws_app)
918873
919874
@staticmethod
920-
async def send_message_static(message, socket):
875+
async def sendEchoMessage_static(message, socket):
921876
\\"\\"\\"
922-
Send a message using a provided WebSocket connection, without needing an instance.
877+
Send a sendEchoMessage message using a provided WebSocket connection, without needing an instance.
923878
924879
Args:
925880
message (dict or str): The message to send.
@@ -928,7 +883,8 @@ class HoppscotchClient:
928883
Raises:
929884
Exception: If sending fails or the socket is not connected.
930885
\\"\\"\\"
931-
await HoppscotchEchoWebSocketClient._send(message, socket)
886+
await HoppscotchClient._send(message, socket)
887+
932888
933889
@staticmethod
934890
async def _send(message, socket):
@@ -1085,9 +1041,9 @@ class HoppscotchEchoWebSocketClient:
10851041
for handler in self.error_handlers:
10861042
handler(error)
10871043
1088-
async def send_message(self, message):
1044+
async def sendEchoMessage(self, message):
10891045
\\"\\"\\"
1090-
Send a message using the WebSocket connection attached to this instance.
1046+
Send a sendEchoMessage message using the WebSocket connection attached to this instance.
10911047
10921048
Args:
10931049
message (dict or str): The message to send. Will be serialized to JSON if it's a dictionary.
@@ -1098,9 +1054,9 @@ class HoppscotchEchoWebSocketClient:
10981054
await self._send(message, self.ws_app)
10991055
11001056
@staticmethod
1101-
async def send_message_static(message, socket):
1057+
async def sendEchoMessage_static(message, socket):
11021058
\\"\\"\\"
1103-
Send a message using a provided WebSocket connection, without needing an instance.
1059+
Send a sendEchoMessage message using a provided WebSocket connection, without needing an instance.
11041060
11051061
Args:
11061062
message (dict or str): The message to send.
@@ -1111,6 +1067,7 @@ class HoppscotchEchoWebSocketClient:
11111067
\\"\\"\\"
11121068
await HoppscotchEchoWebSocketClient._send(message, socket)
11131069
1070+
11141071
@staticmethod
11151072
async def _send(message, socket):
11161073
\\"\\"\\"
@@ -1267,9 +1224,9 @@ class PostmanEchoWebSocketClientClient:
12671224
for handler in self.error_handlers:
12681225
handler(error)
12691226
1270-
async def send_message(self, message):
1227+
async def sendEchoMessage(self, message):
12711228
\\"\\"\\"
1272-
Send a message using the WebSocket connection attached to this instance.
1229+
Send a sendEchoMessage message using the WebSocket connection attached to this instance.
12731230
12741231
Args:
12751232
message (dict or str): The message to send. Will be serialized to JSON if it's a dictionary.
@@ -1280,9 +1237,9 @@ class PostmanEchoWebSocketClientClient:
12801237
await self._send(message, self.ws_app)
12811238
12821239
@staticmethod
1283-
async def send_message_static(message, socket):
1240+
async def sendEchoMessage_static(message, socket):
12841241
\\"\\"\\"
1285-
Send a message using a provided WebSocket connection, without needing an instance.
1242+
Send a sendEchoMessage message using a provided WebSocket connection, without needing an instance.
12861243
12871244
Args:
12881245
message (dict or str): The message to send.
@@ -1291,7 +1248,8 @@ class PostmanEchoWebSocketClientClient:
12911248
Raises:
12921249
Exception: If sending fails or the socket is not connected.
12931250
\\"\\"\\"
1294-
await HoppscotchEchoWebSocketClient._send(message, socket)
1251+
await PostmanEchoWebSocketClientClient._send(message, socket)
1252+
12951253
12961254
@staticmethod
12971255
async def _send(message, socket):

packages/templates/clients/websocket/test/python/test_acceptance.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ async def handler(websocket):
6363
# Most improtant part of test where we test clients send message
6464
#
6565
###############
66-
await HoppscotchEchoWebSocketClient.send_message_static(expected_outgoing_message, websocket)
66+
await HoppscotchEchoWebSocketClient.sendEchoMessage_static(expected_outgoing_message, websocket)
6767

6868
# Start the WebSocket server
6969
server = await websockets.serve(handler, port=port)

0 commit comments

Comments
 (0)