33from dataclasses import dataclass
44from typing import Optional , Union
55
6- from tornado .httputil import HTTPConnection , HTTPHeaders , RequestStartLine , ResponseStartLine
6+ from tornado .httputil import (
7+ HTTPConnection ,
8+ HTTPHeaders ,
9+ RequestStartLine ,
10+ ResponseStartLine ,
11+ )
712from tornado .web import Application
813
914ReceiveCallable = Callable [[], Awaitable [dict ]]
1015SendCallable = Callable [[dict ], Awaitable [None ]]
1116
17+
1218@dataclass
1319class ASGIHTTPRequestContext :
1420 """To convey connection details to the HTTPServerRequest object"""
21+
1522 protocol : str
1623 address : Optional [tuple ] = None
1724 remote_ip : str = "0.0.0.0"
1825
26+
1927class ASGIHTTPConnection (HTTPConnection ):
2028 """Represents the connection for 1 request/response pair
2129
2230 This provides the API for sending the response.
2331 """
24- def __init__ (self , send_cb : SendCallable , context : ASGIHTTPRequestContext , task_holder : set ):
32+
33+ def __init__ (
34+ self , send_cb : SendCallable , context : ASGIHTTPRequestContext , task_holder : set
35+ ):
2536 self .send_cb = send_cb
2637 self .context = context
2738 self .task_holder = task_holder
@@ -44,12 +55,16 @@ async def _write_headers(
4455 headers : HTTPHeaders ,
4556 chunk : Optional [bytes ] = None ,
4657 ):
47- await self .send_cb ({
48- "type" : "http.response.start" ,
49- "status" : start_line .code ,
50- "headers" : [[k .lower ().encode ('latin1' ), v .encode ('latin1' )]
51- for k , v in headers .get_all ()]
52- })
58+ await self .send_cb (
59+ {
60+ "type" : "http.response.start" ,
61+ "status" : start_line .code ,
62+ "headers" : [
63+ [k .lower ().encode ("latin1" ), v .encode ("latin1" )]
64+ for k , v in headers .get_all ()
65+ ],
66+ }
67+ )
5368 if chunk is not None :
5469 await self ._write (chunk )
5570
@@ -62,20 +77,22 @@ def write_headers(
6277 return self ._bg_task (self ._write_headers (start_line , headers , chunk ))
6378
6479 async def _write (self , chunk : bytes ):
65- await self .send_cb ({
66- "type" : "http.response.body" ,
67- "body" : chunk ,
68- "more_body" : True
69- })
80+ await self .send_cb (
81+ {"type" : "http.response.body" , "body" : chunk , "more_body" : True }
82+ )
7083
7184 def write (self , chunk : bytes ) -> "Future[None]" :
7285 return self ._bg_task (self ._write (chunk ))
7386
7487 def finish (self ) -> None :
75- self ._bg_task (self .send_cb ({
76- "type" : "http.response.body" ,
77- "more_body" : False ,
78- }))
88+ self ._bg_task (
89+ self .send_cb (
90+ {
91+ "type" : "http.response.body" ,
92+ "more_body" : False ,
93+ }
94+ )
95+ )
7996
8097 def set_close_callback (self , callback : Optional [Callable [[], None ]]):
8198 self ._close_callback = callback
@@ -89,14 +106,15 @@ def _on_connection_close(self) -> None:
89106
90107class ASGIAdapter :
91108 """Wrap a tornado application object to use with an ASGI server"""
109+
92110 def __init__ (self , application : Application ):
93111 self .application = application
94112 self .task_holder = set ()
95113
96114 async def __call__ (self , scope , receive : ReceiveCallable , send : SendCallable ):
97- if scope [' type' ] == ' http' :
115+ if scope [" type" ] == " http" :
98116 return await self .http_scope (scope , receive , send )
99- raise KeyError (scope [' type' ])
117+ raise KeyError (scope [" type" ])
100118
101119 async def http_scope (self , scope , receive : ReceiveCallable , send : SendCallable ):
102120 """Handles one HTTP request"""
@@ -106,15 +124,15 @@ async def http_scope(self, scope, receive: ReceiveCallable, send: SendCallable):
106124 ctx .remote_ip = client_addr [0 ]
107125
108126 conn = ASGIHTTPConnection (send , ctx , self .task_holder )
109- req_target = scope [' path' ]
110- if qs := scope [' query_string' ]:
111- req_target += '?' + qs .decode (' latin1' )
127+ req_target = scope [" path" ]
128+ if qs := scope [" query_string" ]:
129+ req_target += "?" + qs .decode (" latin1" )
112130 req_start_line = RequestStartLine (
113- scope [' method' ], req_target , scope [' http_version' ]
131+ scope [" method" ], req_target , scope [" http_version" ]
114132 )
115133 req_headers = HTTPHeaders ()
116- for k , v in scope [' headers' ]:
117- req_headers .add (k .decode (' latin1' ), v .decode (' latin1' ))
134+ for k , v in scope [" headers" ]:
135+ req_headers .add (k .decode (" latin1" ), v .decode (" latin1" ))
118136 msg_delegate = self .application .start_request (None , conn )
119137 fut = msg_delegate .headers_received (req_start_line , req_headers )
120138 if fut is not None :
0 commit comments