Skip to content

Commit 07c9321

Browse files
authored
Merge pull request #30 from tarasko/feature/fix_lint_errors
Feature/fix lint errors
2 parents f1a6d38 + 1827779 commit 07c9321

File tree

11 files changed

+169
-110
lines changed

11 files changed

+169
-110
lines changed

.flake8

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[flake8]
2+
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist
3+
max-complexity = 10
4+
max-line-length = 127

.github/workflows/run-tests.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ jobs:
3232
# stop the build if there are Python syntax errors or undefined names
3333
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
3434
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
35-
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
35+
flake8 . --count --statistics
3636
3737
mypy-checks:
3838
strategy:

README.rst

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ Connects to an echo server, sends a message and disconnect upon reply.
7878
.. code-block:: python
7979
8080
import asyncio
81-
import uvloop
8281
from picows import ws_connect, WSFrame, WSTransport, WSListener, WSMsgType, WSCloseCode
8382
8483
class ClientListener(WSListener):
@@ -97,7 +96,6 @@ Connects to an echo server, sends a message and disconnect upon reply.
9796
9897
9998
if __name__ == '__main__':
100-
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
10199
asyncio.run(main("ws://127.0.0.1:9001"))
102100
103101
This prints:
@@ -112,7 +110,6 @@ Echo server
112110
.. code-block:: python
113111
114112
import asyncio
115-
import uvloop
116113
from picows import ws_create_server, WSFrame, WSTransport, WSListener, WSMsgType, WSUpgradeRequest
117114
118115
class ServerClientListener(WSListener):
@@ -138,7 +135,6 @@ Echo server
138135
await server.serve_forever()
139136
140137
if __name__ == '__main__':
141-
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
142138
asyncio.run(main())
143139
144140

examples/echo_client_benchmark.py

Lines changed: 113 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,16 @@
1515
from picows import WSFrame, WSTransport, WSListener, ws_connect, WSMsgType
1616
from time import time
1717

18-
_logger = getLogger(__name__)
18+
19+
try:
20+
from examples.echo_client_cython import picows_main_cython
21+
except ImportError:
22+
picows_main_cython = None
1923

2024

2125
RPS: Dict[str, List[float]] = {"ssl": [], "plain": []}
2226
NAMES: List[str] = []
27+
_logger = getLogger(__name__)
2328

2429

2530
def create_client_ssl_context():
@@ -116,7 +121,101 @@ async def aiohttp_main(url: str, data: bytes, duration: int, ssl_context):
116121
break
117122

118123

119-
if __name__ == '__main__':
124+
def run_for_websockets_library(plain_url, ssl_url, ssl_context, msg, duration):
125+
global NAMES, RPS
126+
_, rps = asyncio.run(websockets_main(plain_url, msg, duration, None))
127+
RPS["plain"].append(rps)
128+
name, rps = asyncio.run(websockets_main(ssl_url, msg, duration, ssl_context))
129+
RPS["ssl"].append(rps)
130+
NAMES.append(name)
131+
132+
133+
def run_for_aiohttp_library(plain_url, ssl_url, ssl_context, msg, duration):
134+
global NAMES, RPS
135+
_, rps = asyncio.run(aiohttp_main(plain_url, msg, duration, None))
136+
RPS["plain"].append(rps)
137+
name, rps = asyncio.run(aiohttp_main(ssl_url, msg, duration, ssl_context))
138+
RPS["ssl"].append(rps)
139+
NAMES.append(name)
140+
141+
142+
def run_picows_client(plain_url, ssl_url, ssl_context, msg, duration):
143+
global NAMES, RPS
144+
_, rps = asyncio.run(picows_main(plain_url, msg, duration, None))
145+
RPS["plain"].append(rps)
146+
name, rps = asyncio.run(picows_main(ssl_url, msg, duration, ssl_context))
147+
RPS["ssl"].append(rps)
148+
NAMES.append(name)
149+
150+
151+
def run_picows_cython_plain_client(plain_url, ssl_url, ssl_context, msg, duration):
152+
global NAMES, RPS
153+
print("Run picows cython plain client")
154+
rps = asyncio.run(picows_main_cython(plain_url, msg, duration, None))
155+
RPS["plain"].append(rps)
156+
157+
158+
def run_picows_cython_ssl_client(plain_url, ssl_url, ssl_context, msg, duration):
159+
global NAMES, RPS
160+
print("Run picows cython ssl client")
161+
rps = asyncio.run(picows_main_cython(ssl_url, msg, duration, ssl_context))
162+
RPS["ssl"].append(rps)
163+
164+
165+
def run_boost_beast_client(args):
166+
global NAMES, RPS
167+
168+
print("Run boost.beast plain client")
169+
pr = subprocess.run([args.boost_client, b"0",
170+
args.host.encode(),
171+
args.plain_port.encode(),
172+
args.msg_size, args.duration],
173+
shell=False, check=True, capture_output=True)
174+
_, rps = pr.stdout.split(b":", 2)
175+
RPS["plain"].append(int(rps.decode()))
176+
177+
print("Run boost.beast ssl client")
178+
pr = subprocess.run([args.boost_client, b"1",
179+
args.host.encode(),
180+
args.ssl_port.encode(),
181+
args.msg_size, args.duration],
182+
shell=False, check=True, capture_output=True)
183+
name, rps = pr.stdout.split(b":", 2)
184+
RPS["ssl"].append(int(rps.decode()))
185+
NAMES.append("c++ boost.beast")
186+
187+
188+
def print_result_and_plot(loop_name, msg_size):
189+
for k, v in RPS.items():
190+
print(k.replace("\n", " "), v)
191+
192+
print("names:", " | ".join(n.replace("\n", " ") for n in NAMES))
193+
194+
try:
195+
import matplotlib.pyplot as plt
196+
197+
fig, ax = plt.subplots(layout='constrained')
198+
199+
x = np.arange(len(NAMES))
200+
width = 0.25 # the width of the bars
201+
multiplier = 0
202+
203+
for cl_type, measurement in RPS.items():
204+
offset = width * multiplier
205+
ax.bar(x + offset, measurement, width, label=cl_type)
206+
multiplier += 1
207+
208+
ax.set_ylabel('request/second')
209+
ax.set_title(f'Echo round-trip performance \n({loop_name}, msg_size={msg_size})')
210+
ax.set_xticks(x + width, NAMES)
211+
ax.legend(loc='upper left', ncols=3)
212+
213+
plt.show()
214+
except ImportError:
215+
pass
216+
217+
218+
def main():
120219
parser = argparse.ArgumentParser(description="Benchmark for the various websocket clients",
121220
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
122221
parser.add_argument("--host", default="127.0.0.1", help="Server host")
@@ -146,87 +245,27 @@ async def aiohttp_main(url: str, data: bytes, duration: int, ssl_context):
146245
ssl_url = f"wss://{args.host}:{args.ssl_port}/"
147246

148247
if not args.picows_plain_only and not args.picows_ssl_only:
149-
_, rps = asyncio.run(websockets_main(plain_url, msg, duration, None))
150-
RPS["plain"].append(rps)
151-
name, rps = asyncio.run(websockets_main(ssl_url, msg, duration, ssl_context))
152-
RPS["ssl"].append(rps)
153-
NAMES.append(name)
154-
155-
_, rps = asyncio.run(aiohttp_main(plain_url, msg, duration, None))
156-
RPS["plain"].append(rps)
157-
name, rps = asyncio.run(aiohttp_main(ssl_url, msg, duration, ssl_context))
158-
RPS["ssl"].append(rps)
159-
NAMES.append(name)
160-
161-
_, rps = asyncio.run(picows_main(plain_url, msg, duration, None))
162-
RPS["plain"].append(rps)
163-
name, rps = asyncio.run(picows_main(ssl_url, msg, duration, ssl_context))
164-
RPS["ssl"].append(rps)
165-
NAMES.append(name)
248+
run_for_websockets_library(plain_url, ssl_url, ssl_context, msg, duration)
249+
run_for_aiohttp_library(plain_url, ssl_url, ssl_context, msg, duration)
250+
run_picows_client(plain_url, ssl_url, ssl_context, msg, duration)
251+
252+
if picows_main_cython is not None:
253+
NAMES.append("picows\ncython client")
166254

167-
try:
168-
from examples.echo_client_cython import picows_main_cython
169255
if not args.picows_ssl_only:
170-
print("Run picows cython plain client")
171-
rps = asyncio.run(picows_main_cython(plain_url, msg, duration, None))
172-
RPS["plain"].append(rps)
256+
run_picows_cython_plain_client(plain_url, ssl_url, ssl_context, msg, duration)
173257

174258
if not args.picows_plain_only:
175-
print("Run picows cython ssl client")
176-
rps = asyncio.run(picows_main_cython(ssl_url, msg, duration, ssl_context))
177-
RPS["ssl"].append(rps)
178-
179-
NAMES.append("picows\ncython client")
180-
except ImportError:
181-
pass
259+
run_picows_cython_ssl_client(plain_url, ssl_url, ssl_context, msg, duration)
182260

183261
if not args.picows_plain_only and not args.picows_ssl_only and args.boost_client is not None:
184-
print("Run boost.beast plain client")
185-
pr = subprocess.run([args.boost_client, b"0",
186-
args.host.encode(),
187-
args.plain_port.encode(),
188-
args.msg_size, args.duration],
189-
shell=False, check=True, capture_output=True)
190-
_, rps = pr.stdout.split(b":", 2)
191-
RPS["plain"].append(int(rps.decode()))
192-
193-
print("Run boost.beast ssl client")
194-
pr = subprocess.run([args.boost_client, b"1",
195-
args.host.encode(),
196-
args.ssl_port.encode(),
197-
args.msg_size, args.duration],
198-
shell=False, check=True, capture_output=True)
199-
name, rps = pr.stdout.split(b":", 2)
200-
RPS["ssl"].append(int(rps.decode()))
201-
NAMES.append("c++ boost.beast")
262+
run_boost_beast_client(args)
202263

203264
if args.picows_plain_only or args.picows_ssl_only:
204265
exit()
205266

206-
for k, v in RPS.items():
207-
print(k.replace("\n", " "), v)
208-
209-
print("names:", " | ".join(n.replace("\n", " ") for n in NAMES))
267+
print_result_and_plot(loop_name, msg_size)
210268

211-
try:
212-
import matplotlib.pyplot as plt
213269

214-
fig, ax = plt.subplots(layout='constrained')
215-
216-
x = np.arange(len(NAMES))
217-
width = 0.25 # the width of the bars
218-
multiplier = 0
219-
220-
for cl_type, measurement in RPS.items():
221-
offset = width * multiplier
222-
rects = ax.bar(x + offset, measurement, width, label=cl_type)
223-
multiplier += 1
224-
225-
ax.set_ylabel('request/second')
226-
ax.set_title(f'Echo round-trip performance \n({loop_name}, msg_size={msg_size})')
227-
ax.set_xticks(x + width, NAMES)
228-
ax.legend(loc='upper left', ncols=3)
229-
230-
plt.show()
231-
except ImportError:
232-
pass
270+
if __name__ == '__main__':
271+
main()

examples/okx_roundtrip_time.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
import logging
33

44
import picows
5-
from picows import ws_connect, WSFrame, WSTransport, WSListener, WSMsgType, WSCloseCode
5+
from picows import ws_connect, WSTransport, WSListener
66

77
EXPECTED_OKX_ROUNDTRIP_TIME = 0.1
88

9+
910
class ClientListener(WSListener):
1011
async def check_okx_roundtrip_time(self, transport: picows.WSTransport):
1112
rtts = await transport.measure_roundtrip_time(5)

examples/readme_client.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
import uvloop
32
from picows import ws_connect, WSFrame, WSTransport, WSListener, WSMsgType, WSCloseCode
43

54

@@ -19,5 +18,4 @@ async def main(url):
1918

2019

2120
if __name__ == '__main__':
22-
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
2321
asyncio.run(main("ws://127.0.0.1:9001"))

examples/readme_server.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
import uvloop
32
from picows import ws_create_server, WSFrame, WSTransport, WSListener, \
43
WSMsgType, WSUpgradeRequest
54

@@ -30,5 +29,4 @@ def listener_factory(r: WSUpgradeRequest):
3029

3130

3231
if __name__ == '__main__':
33-
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
3432
asyncio.run(main())

examples/subprotocol_negotiation.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
ws_create_server, WSUpgradeResponse, WSUpgradeResponseWithListener, \
66
WSUpgradeRequest
77

8+
89
class OCPPServerClientListener(WSListener):
910
def on_ws_connected(self, transport: WSTransport):
1011
print("New client connected, negotiated protocol: ", transport.response.headers["Sec-WebSocket-Protocol"])
@@ -19,15 +20,26 @@ def on_ws_connected(self, transport: WSTransport):
1920
async def main():
2021
def server_client_factory(request: WSUpgradeRequest):
2122
if "ocpp2.1" in request.headers["Sec-WebSocket-Protocol"]:
22-
return WSUpgradeResponseWithListener(WSUpgradeResponse.create_101_response(extra_headers={"Sec-WebSocket-Protocol": "ocpp2.1"}), OCPPServerClientListener())
23+
return WSUpgradeResponseWithListener(
24+
WSUpgradeResponse.create_101_response(extra_headers={"Sec-WebSocket-Protocol": "ocpp2.1"}),
25+
OCPPServerClientListener())
2326
else:
24-
return WSUpgradeResponseWithListener(WSUpgradeResponse.create_error_response(HTTPStatus.BAD_REQUEST, b"requested websocket subprotocol is not supported"), None)
27+
return WSUpgradeResponseWithListener(
28+
WSUpgradeResponse.create_error_response(
29+
HTTPStatus.BAD_REQUEST,
30+
b"requested websocket subprotocol is not supported"
31+
),
32+
None)
2533

2634
server = await ws_create_server(server_client_factory, "127.0.0.1", 27001)
2735
asyncio.create_task(server.serve_forever())
2836

2937
# Client request support for either ocpp1.6 or ocpp2.1 protocol
30-
(transport, client) = await ws_connect(OCPPClientListener, "ws://127.0.0.1:27001/", extra_headers={"Sec-WebSocket-Protocol": "ocpp1.6,ocpp2.1"})
38+
(transport, client) = await ws_connect(
39+
OCPPClientListener,
40+
"ws://127.0.0.1:27001/",
41+
extra_headers={"Sec-WebSocket-Protocol": "ocpp1.6,ocpp2.1"}
42+
)
3143

3244
transport.disconnect()
3345
await transport.wait_disconnected()

0 commit comments

Comments
 (0)