@@ -169,17 +169,16 @@ def send(
169169
170170 request_complete = False
171171 response_started = False
172- response_complete = False
172+ response_complete : anyio . Event
173173 raw_kwargs = {"body" : io .BytesIO ()} # type: typing.Dict[str, typing.Any]
174174 template = None
175175 context = None
176176
177177 async def receive () -> Message :
178- nonlocal request_complete , response_complete
178+ nonlocal request_complete
179179
180180 if request_complete :
181- while not response_complete :
182- await anyio .sleep (0.0001 )
181+ await response_complete .wait ()
183182 return {"type" : "http.disconnect" }
184183
185184 body = request .body
@@ -203,7 +202,7 @@ async def receive() -> Message:
203202 return {"type" : "http.request" , "body" : body_bytes }
204203
205204 async def send (message : Message ) -> None :
206- nonlocal raw_kwargs , response_started , response_complete , template , context
205+ nonlocal raw_kwargs , response_started , template , context
207206
208207 if message ["type" ] == "http.response.start" :
209208 assert (
@@ -225,21 +224,22 @@ async def send(message: Message) -> None:
225224 response_started
226225 ), 'Received "http.response.body" without "http.response.start".'
227226 assert (
228- not response_complete
227+ not response_complete . is_set ()
229228 ), 'Received "http.response.body" after response completed.'
230229 body = message .get ("body" , b"" )
231230 more_body = message .get ("more_body" , False )
232231 if request .method != "HEAD" :
233232 raw_kwargs ["body" ].write (body )
234233 if not more_body :
235234 raw_kwargs ["body" ].seek (0 )
236- response_complete = True
235+ response_complete . set ()
237236 elif message ["type" ] == "http.response.template" :
238237 template = message ["template" ]
239238 context = message ["context" ]
240239
241240 try :
242241 with anyio .start_blocking_portal (** self .async_backend ) as portal :
242+ response_complete = portal .call (anyio .Event )
243243 portal .call (self .app , scope , receive , send )
244244 except BaseException as exc :
245245 if self .raise_server_exceptions :
0 commit comments