Skip to content

Commit 2ed4e0d

Browse files
committed
tutorial refactoring
1 parent c5fc1bc commit 2ed4e0d

File tree

18 files changed

+98
-65
lines changed

18 files changed

+98
-65
lines changed

examples/tutorial/reactivex/chat_client.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
import json
32
import logging
43
import resource
54
from asyncio import Task, Queue
@@ -9,7 +8,8 @@
98
from reactivex import operators
109

1110
from examples.tutorial.reactivex.models import (Message, chat_filename_mimetype, ServerStatistics, ClientStatistics,
12-
ServerStatisticsRequest, encode_dataclass, dataclass_to_payload)
11+
ServerStatisticsRequest, encode_dataclass, dataclass_to_payload,
12+
decode_dataclass)
1313
from rsocket.extensions.helpers import composite, route, metadata_item
1414
from rsocket.extensions.mimetypes import WellKnownMimeTypes
1515
from rsocket.frame_helpers import ensure_bytes
@@ -59,7 +59,7 @@ async def leave(self, channel_name: str):
5959

6060
def listen_for_messages(self):
6161
def print_message(data: bytes):
62-
message = Message(**json.loads(data))
62+
message = decode_dataclass(data, Message)
6363
print(f'{self._username}: from {message.user} ({message.channel}): {message.content}')
6464

6565
async def listen_for_messages():
@@ -82,7 +82,7 @@ async def send_statistics(self):
8282

8383
def listen_for_statistics(self) -> StatisticsControl:
8484
def print_statistics(value: bytes):
85-
statistics = ServerStatistics(**json.loads(utf8_decode(value)))
85+
statistics = decode_dataclass(value, ServerStatistics)
8686
print(f'users: {statistics.user_count}, channels: {statistics.channel_count}')
8787

8888
control = StatisticsControl()

examples/tutorial/reactivex/chat_server.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
import json
32
import logging
43
import uuid
54
from asyncio import Queue
@@ -13,7 +12,8 @@
1312
from reactivex import Observable, operators, Subject, Observer
1413

1514
from examples.tutorial.reactivex.models import (Message, chat_filename_mimetype, ClientStatistics,
16-
ServerStatisticsRequest, ServerStatistics, dataclass_to_payload)
15+
ServerStatisticsRequest, ServerStatistics, dataclass_to_payload,
16+
decode_dataclass)
1717
from rsocket.extensions.composite_metadata import CompositeMetadata
1818
from rsocket.extensions.helpers import composite, metadata_item
1919
from rsocket.frame_helpers import ensure_bytes
@@ -119,14 +119,14 @@ async def login(payload: Payload) -> Observable:
119119

120120
@router.response('channel.join')
121121
async def join_channel(payload: Payload) -> Observable:
122-
channel_name = payload.data.decode('utf-8')
122+
channel_name = utf8_decode(payload.data)
123123
ensure_channel_exists(channel_name)
124124
chat_data.channel_users[channel_name].add(self._session.session_id)
125125
return reactivex.empty()
126126

127127
@router.response('channel.leave')
128128
async def leave_channel(payload: Payload) -> Observable:
129-
channel_name = payload.data.decode('utf-8')
129+
channel_name = utf8_decode(payload.data)
130130
chat_data.channel_users[channel_name].discard(self._session.session_id)
131131
return reactivex.empty()
132132

@@ -159,7 +159,7 @@ async def get_channels() -> Observable:
159159

160160
@router.fire_and_forget('statistics')
161161
async def receive_statistics(payload: Payload):
162-
statistics = ClientStatistics(**json.loads(utf8_decode(payload.data)))
162+
statistics = decode_dataclass(payload.data, ClientStatistics)
163163

164164
logging.info('Received client statistics. memory usage: %s', statistics.memory_usage)
165165

@@ -176,8 +176,8 @@ async def statistics_generator():
176176
except Exception:
177177
logging.error('Statistics', exc_info=True)
178178

179-
def on_next(value: Payload):
180-
request = ServerStatisticsRequest(**json.loads(utf8_decode(value.data)))
179+
def on_next(payload: Payload):
180+
request = decode_dataclass(payload.data, ServerStatisticsRequest)
181181

182182
logging.info(f'Received statistics request {request.ids}, {request.period_seconds}')
183183

@@ -199,7 +199,7 @@ def on_next(value: Payload):
199199

200200
@router.response('message')
201201
async def send_message(payload: Payload) -> Observable:
202-
message = Message(**json.loads(payload.data))
202+
message = decode_dataclass(payload.data, Message)
203203

204204
logging.info('Received message for user: %s, channel: %s', message.user, message.channel)
205205

examples/tutorial/reactivex/models.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import json
22
from dataclasses import dataclass, field
3-
from typing import Optional, List
3+
from typing import Optional, List, Type, TypeVar
44

55
from rsocket.frame_helpers import ensure_bytes
6+
from rsocket.helpers import utf8_decode
67
from rsocket.payload import Payload
78

89

@@ -39,3 +40,10 @@ def encode_dataclass(obj) -> bytes:
3940

4041
def dataclass_to_payload(obj) -> Payload:
4142
return Payload(encode_dataclass(obj))
43+
44+
45+
T = TypeVar('T')
46+
47+
48+
def decode_dataclass(data: bytes, cls: Type[T]) -> T:
49+
return cls(**json.loads(utf8_decode(data)))

examples/tutorial/step3/chat_client.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import asyncio
2-
import json
32
import logging
43
from typing import Optional
54

6-
from examples.tutorial.step3.models import Message, encode_dataclass
5+
from examples.tutorial.step3.models import Message, encode_dataclass, decode_dataclass
76
from reactivestreams.subscriber import DefaultSubscriber
87
from reactivestreams.subscription import DefaultSubscription
98
from rsocket.extensions.helpers import composite, route
@@ -30,7 +29,7 @@ async def login(self, username: str):
3029

3130
def listen_for_messages(self):
3231
def print_message(data: bytes):
33-
message = Message(**json.loads(data))
32+
message = decode_dataclass(data, Message)
3433
print(f'{self._username}: from {message.user}: {message.content}')
3534

3635
class MessageListener(DefaultSubscriber, DefaultSubscription):

examples/tutorial/step3/chat_server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ async def login(payload: Payload) -> Awaitable[Payload]:
6767

6868
@router.response('message')
6969
async def send_message(payload: Payload) -> Awaitable[Payload]:
70-
message = decode_dataclass(payload, Message)
70+
message = decode_dataclass(payload.data, Message)
7171

7272
logging.info('Received message for user: %s', message.user)
7373

examples/tutorial/step3/models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,5 @@ def dataclass_to_payload(obj) -> Payload:
2424
T = TypeVar('T')
2525

2626

27-
def decode_dataclass(payload: Payload, cls: Type[T]) -> T:
28-
return cls(**json.loads(utf8_decode(payload.data)))
27+
def decode_dataclass(data: bytes, cls: Type[T]) -> T:
28+
return cls(**json.loads(utf8_decode(data)))

examples/tutorial/step4/chat_client.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import asyncio
2-
import json
32
import logging
43
from typing import List, Optional
54

6-
from examples.tutorial.step4.models import Message, encode_dataclass
5+
from examples.tutorial.step4.models import Message, encode_dataclass, decode_dataclass
76
from reactivestreams.subscriber import DefaultSubscriber
87
from reactivestreams.subscription import DefaultSubscription
98
from rsocket.awaitable.awaitable_rsocket import AwaitableRSocket
@@ -41,7 +40,7 @@ async def leave(self, channel_name: str):
4140

4241
def listen_for_messages(self):
4342
def print_message(data: bytes):
44-
message = Message(**json.loads(data))
43+
message = decode_dataclass(data, Message)
4544
print(f'{self._username}: from {message.user} ({message.channel}): {message.content}')
4645

4746
class MessageListener(DefaultSubscriber, DefaultSubscription):

examples/tutorial/step4/chat_server.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
import json
32
import logging
43
import uuid
54
from asyncio import Queue
@@ -10,7 +9,7 @@
109

1110
from more_itertools import first
1211

13-
from examples.tutorial.step4.models import (Message, chat_filename_mimetype, dataclass_to_payload)
12+
from examples.tutorial.step4.models import (Message, chat_filename_mimetype, dataclass_to_payload, decode_dataclass)
1413
from reactivestreams.publisher import DefaultPublisher, Publisher
1514
from reactivestreams.subscriber import Subscriber
1615
from reactivestreams.subscription import DefaultSubscription
@@ -103,14 +102,14 @@ async def login(payload: Payload) -> Awaitable[Payload]:
103102

104103
@router.response('channel.join')
105104
async def join_channel(payload: Payload) -> Awaitable[Payload]:
106-
channel_name = payload.data.decode('utf-8')
105+
channel_name = utf8_decode(payload.data)
107106
ensure_channel_exists(channel_name)
108107
chat_data.channel_users[channel_name].add(self._session.session_id)
109108
return create_response()
110109

111110
@router.response('channel.leave')
112111
async def leave_channel(payload: Payload) -> Awaitable[Payload]:
113-
channel_name = payload.data.decode('utf-8')
112+
channel_name = utf8_decode(payload.data)
114113
chat_data.channel_users[channel_name].discard(self._session.session_id)
115114
return create_response()
116115

@@ -123,7 +122,7 @@ async def get_channels() -> Publisher:
123122

124123
@router.response('message')
125124
async def send_message(payload: Payload) -> Awaitable[Payload]:
126-
message = Message(**json.loads(payload.data))
125+
message = decode_dataclass(payload.data, Message)
127126

128127
logging.info('Received message for user: %s, channel: %s', message.user, message.channel)
129128

examples/tutorial/step4/models.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import json
22
from dataclasses import dataclass
3-
from typing import Optional
3+
from typing import Optional, TypeVar, Type
44

55
from rsocket.frame_helpers import ensure_bytes
6+
from rsocket.helpers import utf8_decode
67
from rsocket.payload import Payload
78

89

@@ -22,3 +23,10 @@ def encode_dataclass(obj):
2223

2324
def dataclass_to_payload(obj) -> Payload:
2425
return Payload(encode_dataclass(obj))
26+
27+
28+
T = TypeVar('T')
29+
30+
31+
def decode_dataclass(data: bytes, cls: Type[T]) -> T:
32+
return cls(**json.loads(utf8_decode(data)))

examples/tutorial/step5/chat_client.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import asyncio
2-
import json
32
import logging
43
from typing import List, Optional
54

6-
from examples.tutorial.step5.models import Message, chat_filename_mimetype, encode_dataclass
5+
from examples.tutorial.step5.models import Message, chat_filename_mimetype, encode_dataclass, decode_dataclass
76
from reactivestreams.subscriber import DefaultSubscriber
87
from reactivestreams.subscription import DefaultSubscription
98
from rsocket.awaitable.awaitable_rsocket import AwaitableRSocket
@@ -46,7 +45,7 @@ async def get_users(self, channel_name: str) -> List[str]:
4645

4746
def listen_for_messages(self):
4847
def print_message(data: bytes):
49-
message = Message(**json.loads(data))
48+
message = decode_dataclass(data, Message)
5049
print(f'{self._username}: from {message.user} ({message.channel}): {message.content}')
5150

5251
class MessageListener(DefaultSubscriber, DefaultSubscription):

0 commit comments

Comments
 (0)