7979from itertools import count
8080from wsgiref .handlers import format_date_time
8181
82- import trio
8382import h11
83+ import trio
8484
8585MAX_RECV = 2 ** 16
8686TIMEOUT = 10
@@ -99,10 +99,9 @@ def __init__(self, stream):
9999 self .stream = stream
100100 self .conn = h11 .Connection (h11 .SERVER )
101101 # Our Server: header
102- self .ident = " " .join ([
103- "h11-example-trio-server/{}" .format (h11 .__version__ ),
104- h11 .PRODUCT_ID ,
105- ]).encode ("ascii" )
102+ self .ident = " " .join (
103+ ["h11-example-trio-server/{}" .format (h11 .__version__ ), h11 .PRODUCT_ID ]
104+ ).encode ("ascii" )
106105 # A unique id for this connection, to include in debugging output
107106 # (useful for understanding what's going on if there are multiple
108107 # simultaneous clients).
@@ -120,8 +119,8 @@ async def _read_from_peer(self):
120119 if self .conn .they_are_waiting_for_100_continue :
121120 self .info ("Sending 100 Continue" )
122121 go_ahead = h11 .InformationalResponse (
123- status_code = 100 ,
124- headers = self . basic_headers () )
122+ status_code = 100 , headers = self . basic_headers ()
123+ )
125124 await self .send (go_ahead )
126125 try :
127126 data = await self .stream .receive_some (MAX_RECV )
@@ -185,6 +184,7 @@ def info(self, *args):
185184 # Little debugging method
186185 print ("{}:" .format (self ._obj_id ), * args )
187186
187+
188188################################################################
189189# Server main loop
190190################################################################
@@ -218,8 +218,7 @@ async def http_serve(stream):
218218 wrapper = TrioHTTPWrapper (stream )
219219 wrapper .info ("Got new connection" )
220220 while True :
221- assert wrapper .conn .states == {
222- h11 .CLIENT : h11 .IDLE , h11 .SERVER : h11 .IDLE }
221+ assert wrapper .conn .states == {h11 .CLIENT : h11 .IDLE , h11 .SERVER : h11 .IDLE }
223222
224223 try :
225224 with trio .fail_after (TIMEOUT ):
@@ -244,19 +243,19 @@ async def http_serve(stream):
244243 states = wrapper .conn .states
245244 wrapper .info ("unexpected state" , states , "-- bailing out" )
246245 await maybe_send_error_response (
247- wrapper ,
248- RuntimeError ( "unexpected state {}" . format ( states )) )
246+ wrapper , RuntimeError ( "unexpected state {}" . format ( states ))
247+ )
249248 await wrapper .shutdown_and_clean_up ()
250249 return
251250
251+
252252################################################################
253253# Actual response handlers
254254################################################################
255255
256256# Helper function
257257async def send_simple_response (wrapper , status_code , content_type , body ):
258- wrapper .info ("Sending" , status_code ,
259- "response with" , len (body ), "bytes" )
258+ wrapper .info ("Sending" , status_code , "response with" , len (body ), "bytes" )
260259 headers = wrapper .basic_headers ()
261260 headers .append (("Content-Type" , content_type ))
262261 headers .append (("Content-Length" , str (len (body ))))
@@ -265,12 +264,12 @@ async def send_simple_response(wrapper, status_code, content_type, body):
265264 await wrapper .send (h11 .Data (data = body ))
266265 await wrapper .send (h11 .EndOfMessage ())
267266
267+
268268async def maybe_send_error_response (wrapper , exc ):
269269 # If we can't send an error, oh well, nothing to be done
270270 wrapper .info ("trying to send error response..." )
271271 if wrapper .conn .our_state not in {h11 .IDLE , h11 .SEND_RESPONSE }:
272- wrapper .info ("...but I can't, because our state is" ,
273- wrapper .conn .our_state )
272+ wrapper .info ("...but I can't, because our state is" , wrapper .conn .our_state )
274273 return
275274 try :
276275 if isinstance (exc , h11 .RemoteProtocolError ):
@@ -280,13 +279,13 @@ async def maybe_send_error_response(wrapper, exc):
280279 else :
281280 status_code = 500
282281 body = str (exc ).encode ("utf-8" )
283- await send_simple_response (wrapper ,
284- status_code ,
285- "text/plain; charset=utf-8" ,
286- body )
282+ await send_simple_response (
283+ wrapper , status_code , "text/plain; charset=utf-8" , body
284+ )
287285 except Exception as exc :
288286 wrapper .info ("error while sending error response:" , exc )
289287
288+
290289async def send_echo_response (wrapper , request ):
291290 wrapper .info ("Preparing echo response" )
292291 if request .method not in {b"GET" , b"POST" }:
@@ -296,8 +295,10 @@ async def send_echo_response(wrapper, request):
296295 response_json = {
297296 "method" : request .method .decode ("ascii" ),
298297 "target" : request .target .decode ("ascii" ),
299- "headers" : [(name .decode ("ascii" ), value .decode ("ascii" ))
300- for (name , value ) in request .headers ],
298+ "headers" : [
299+ (name .decode ("ascii" ), value .decode ("ascii" ))
300+ for (name , value ) in request .headers
301+ ],
301302 "body" : "" ,
302303 }
303304 while True :
@@ -306,15 +307,14 @@ async def send_echo_response(wrapper, request):
306307 break
307308 assert type (event ) is h11 .Data
308309 response_json ["body" ] += event .data .decode ("ascii" )
309- response_body_unicode = json .dumps (response_json ,
310- sort_keys = True ,
311- indent = 4 ,
312- separators = ("," , ": " ))
310+ response_body_unicode = json .dumps (
311+ response_json , sort_keys = True , indent = 4 , separators = ("," , ": " )
312+ )
313313 response_body_bytes = response_body_unicode .encode ("utf-8" )
314- await send_simple_response (wrapper ,
315- 200 ,
316- "application/json; charset=utf-8" ,
317- response_body_bytes )
314+ await send_simple_response (
315+ wrapper , 200 , "application/json; charset=utf-8" , response_body_bytes
316+ )
317+
318318
319319async def serve (port ):
320320 print ("listening on http://localhost:{}" .format (port ))
@@ -323,6 +323,7 @@ async def serve(port):
323323 except KeyboardInterrupt :
324324 print ("KeyboardInterrupt - shutting down" )
325325
326+
326327################################################################
327328# Run the server
328329################################################################
0 commit comments