8
8
import ssl
9
9
import struct
10
10
import urllib .parse
11
+ from typing import List
11
12
12
13
from async_generator import asynccontextmanager
13
14
import trio
@@ -174,9 +175,10 @@ async def connect_websocket(nursery, host, port, resource, *, use_ssl,
174
175
if port in (80 , 443 ):
175
176
host_header = host
176
177
else :
177
- host_header = '{}:{}' .format (host , port )
178
- wsproto = WSConnection (ConnectionType .CLIENT )
179
- connection = WebSocketConnection (stream , wsproto , host = host_header ,
178
+ host_header = f'{ host } :{ port } '
179
+ connection = WebSocketConnection (stream ,
180
+ WSConnection (ConnectionType .CLIENT ),
181
+ host = host_header ,
180
182
path = resource ,
181
183
client_subprotocols = subprotocols , client_extra_headers = extra_headers ,
182
184
message_queue_size = message_queue_size ,
@@ -328,8 +330,9 @@ async def wrap_client_stream(nursery, stream, host, resource, *,
328
330
then the connection is closed with code 1009 (Message Too Big).
329
331
:rtype: WebSocketConnection
330
332
'''
331
- wsproto = WSConnection (ConnectionType .CLIENT )
332
- connection = WebSocketConnection (stream , wsproto , host = host , path = resource ,
333
+ connection = WebSocketConnection (stream ,
334
+ WSConnection (ConnectionType .CLIENT ),
335
+ host = host , path = resource ,
333
336
client_subprotocols = subprotocols , client_extra_headers = extra_headers ,
334
337
message_queue_size = message_queue_size ,
335
338
max_message_size = max_message_size )
@@ -356,8 +359,8 @@ async def wrap_server_stream(nursery, stream,
356
359
:type stream: trio.abc.Stream
357
360
:rtype: WebSocketRequest
358
361
'''
359
- wsproto = WSConnection ( ConnectionType . SERVER )
360
- connection = WebSocketConnection ( stream , wsproto ,
362
+ connection = WebSocketConnection ( stream ,
363
+ WSConnection ( ConnectionType . SERVER ) ,
361
364
message_queue_size = message_queue_size ,
362
365
max_message_size = max_message_size )
363
366
nursery .start_soon (connection ._reader_task )
@@ -446,7 +449,7 @@ def __init__(self, reason):
446
449
447
450
def __repr__ (self ):
448
451
''' Return representation. '''
449
- return '{}<{}>' . format ( self .__class__ .__name__ , self .reason )
452
+ return f' { self .__class__ .__name__ } < { self .reason } >'
450
453
451
454
452
455
class ConnectionRejected (HandshakeError ):
@@ -471,8 +474,7 @@ def __init__(self, status_code, headers, body):
471
474
472
475
def __repr__ (self ):
473
476
''' Return representation. '''
474
- return '{}<status_code={}>' .format (self .__class__ .__name__ ,
475
- self .status_code )
477
+ return f'{ self .__class__ .__name__ } <status_code={ self .status_code } >'
476
478
477
479
478
480
class CloseReason :
@@ -515,8 +517,8 @@ def reason(self):
515
517
516
518
def __repr__ (self ):
517
519
''' Show close code, name, and reason. '''
518
- return '{}<code={}, name={}, reason={}>' . format ( self .__class__ .__name__ ,
519
- self .code , self .name , self .reason )
520
+ return f' { self .__class__ .__name__ } ' \
521
+ f'<code= { self .code } , name= { self .name } , reason= { self .reason } >'
520
522
521
523
522
524
class Future :
@@ -619,7 +621,7 @@ async def accept(self, *, subprotocol=None, extra_headers=None):
619
621
:rtype: WebSocketConnection
620
622
'''
621
623
if extra_headers is None :
622
- extra_headers = list ()
624
+ extra_headers = []
623
625
await self ._connection ._accept (self ._event , subprotocol , extra_headers )
624
626
return self ._connection
625
627
@@ -651,14 +653,12 @@ def _get_stream_endpoint(stream, *, local):
651
653
represented as an endpoint.
652
654
:rtype: Endpoint or str
653
655
'''
656
+ socket , is_ssl = None , False
654
657
if isinstance (stream , trio .SocketStream ):
655
658
socket = stream .socket
656
- is_ssl = False
657
659
elif isinstance (stream , trio .SSLStream ):
658
660
socket = stream .transport_stream .socket
659
661
is_ssl = True
660
- else :
661
- socket = None
662
662
if socket :
663
663
addr , port , * _ = socket .getsockname () if local else socket .getpeername ()
664
664
endpoint = Endpoint (addr , port , is_ssl )
@@ -672,7 +672,7 @@ class WebSocketConnection(trio.abc.AsyncResource):
672
672
673
673
CONNECTION_ID = itertools .count ()
674
674
675
- def __init__ (self , stream , wsproto , * , host = None , path = None ,
675
+ def __init__ (self , stream , ws_connection , * , host = None , path = None ,
676
676
client_subprotocols = None , client_extra_headers = None ,
677
677
message_queue_size = MESSAGE_QUEUE_SIZE ,
678
678
max_message_size = MAX_MESSAGE_SIZE ):
@@ -688,7 +688,7 @@ def __init__(self, stream, wsproto, *, host=None, path=None,
688
688
for you.
689
689
690
690
:param SocketStream stream:
691
- :type wsproto: wsproto.WSConnection
691
+ :param ws_connection wsproto.WSConnection:
692
692
:param str host: The hostname to send in the HTTP request headers. Only
693
693
used for client connections.
694
694
:param str path: The URL path for this connection.
@@ -706,12 +706,12 @@ def __init__(self, stream, wsproto, *, host=None, path=None,
706
706
self ._id = next (self .__class__ .CONNECTION_ID )
707
707
self ._stream = stream
708
708
self ._stream_lock = trio .StrictFIFOLock ()
709
- self ._wsproto = wsproto
709
+ self ._wsproto = ws_connection
710
710
self ._message_size = 0
711
711
self ._message_parts = [] # type: List[bytes|str]
712
712
self ._max_message_size = max_message_size
713
713
self ._reader_running = True
714
- if wsproto .client :
714
+ if ws_connection .client :
715
715
self ._initial_request = Request (host = host , target = path ,
716
716
subprotocols = client_subprotocols ,
717
717
extra_headers = client_extra_headers or [])
@@ -895,8 +895,7 @@ async def ping(self, payload=None):
895
895
if self ._close_reason :
896
896
raise ConnectionClosed (self ._close_reason )
897
897
if payload in self ._pings :
898
- raise ValueError ('Payload value {} is already in flight.' .
899
- format (payload ))
898
+ raise ValueError (f'Payload value { payload } is already in flight.' )
900
899
if payload is None :
901
900
payload = struct .pack ('!I' , random .getrandbits (32 ))
902
901
event = trio .Event ()
@@ -938,7 +937,7 @@ async def send_message(self, message):
938
937
def __str__ (self ):
939
938
''' Connection ID and type. '''
940
939
type_ = 'client' if self .is_client else 'server'
941
- return '{ }-{}' . format ( type_ , self ._id )
940
+ return f' { type_ } -{ self ._id } '
942
941
943
942
async def _accept (self , request , subprotocol , extra_headers ):
944
943
'''
@@ -1110,8 +1109,7 @@ async def _handle_message_event(self, event):
1110
1109
self ._message_size += len (event .data )
1111
1110
self ._message_parts .append (event .data )
1112
1111
if self ._message_size > self ._max_message_size :
1113
- err = 'Exceeded maximum message size: {} bytes' .format (
1114
- self ._max_message_size )
1112
+ err = f'Exceeded maximum message size: { self ._max_message_size } bytes'
1115
1113
self ._message_size = 0
1116
1114
self ._message_parts = []
1117
1115
self ._close_reason = CloseReason (1009 , err )
@@ -1276,13 +1274,12 @@ def url(self):
1276
1274
else :
1277
1275
port_str = ':' + str (self .port )
1278
1276
if self .address .version == 4 :
1279
- return '{ }://{}{}' . format ( scheme , self .address , port_str )
1280
- return '{ }://[{}]{}' . format ( scheme , self . address , port_str )
1277
+ return f' { scheme } ://{ self .address } { port_str } '
1278
+ return f' { scheme } ://[{ self . address } ]{ port_str } '
1281
1279
1282
1280
def __repr__ (self ):
1283
1281
''' Return endpoint info as string. '''
1284
- return 'Endpoint(address="{}", port={}, is_ssl={})' .format (self .address ,
1285
- self .port , self .is_ssl )
1282
+ return f'Endpoint(address="{ self .address } ", port={ self .port } , is_ssl={ self .is_ssl } )'
1286
1283
1287
1284
1288
1285
class WebSocketServer :
@@ -1343,12 +1340,11 @@ def port(self):
1343
1340
if len (self ._listeners ) > 1 :
1344
1341
raise RuntimeError ('Cannot get port because this server has'
1345
1342
' more than 1 listeners.' )
1343
+ listener = self .listeners [0 ]
1346
1344
try :
1347
- listener = self .listeners [0 ]
1348
1345
return listener .port
1349
1346
except AttributeError :
1350
- raise RuntimeError ('This socket does not have a port: {!r}'
1351
- .format (listener )) from None
1347
+ raise RuntimeError (f'This socket does not have a port: { repr (listener )} ' ) from None
1352
1348
1353
1349
@property
1354
1350
def listeners (self ):
@@ -1360,16 +1356,14 @@ def listeners(self):
1360
1356
:returns: Listeners
1361
1357
:rtype list[Endpoint or str]:
1362
1358
'''
1363
- listeners = list ()
1359
+ listeners = []
1364
1360
for listener in self ._listeners :
1361
+ socket , is_ssl = None , False
1365
1362
if isinstance (listener , trio .SocketListener ):
1366
1363
socket = listener .socket
1367
- is_ssl = False
1368
1364
elif isinstance (listener , trio .SSLListener ):
1369
1365
socket = listener .transport_listener .socket
1370
1366
is_ssl = True
1371
- else :
1372
- socket = None
1373
1367
if socket :
1374
1368
sockname = socket .getsockname ()
1375
1369
listeners .append (Endpoint (sockname [0 ], sockname [1 ], is_ssl ))
@@ -1407,8 +1401,8 @@ async def _handle_connection(self, stream):
1407
1401
:type stream: trio.abc.Stream
1408
1402
'''
1409
1403
async with trio .open_nursery () as nursery :
1410
- wsproto = WSConnection ( ConnectionType . SERVER )
1411
- connection = WebSocketConnection ( stream , wsproto ,
1404
+ connection = WebSocketConnection ( stream ,
1405
+ WSConnection ( ConnectionType . SERVER ) ,
1412
1406
message_queue_size = self ._message_queue_size ,
1413
1407
max_message_size = self ._max_message_size )
1414
1408
nursery .start_soon (connection ._reader_task )
0 commit comments