From 441103a04d1d167dc870eaaf90e3fba974f67c93 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Tue, 10 May 2022 09:57:28 +0200 Subject: [PATCH] Refs #33173, Refs #30451 -- Fixed ResourceWarning from unclosed body files in ASGI handler on Python 3.11+. --- django/core/handlers/asgi.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/django/core/handlers/asgi.py b/django/core/handlers/asgi.py index 7b17c58153..11c8bc209b 100644 --- a/django/core/handlers/asgi.py +++ b/django/core/handlers/asgi.py @@ -164,12 +164,15 @@ class ASGIHandler(base.BaseHandler): except RequestAborted: return # Request is complete and can be served. - set_script_prefix(self.get_script_prefix(scope)) - await sync_to_async(signals.request_started.send, thread_sensitive=True)( - sender=self.__class__, scope=scope - ) - # Get the request and check for basic issues. - request, error_response = self.create_request(scope, body_file) + try: + set_script_prefix(self.get_script_prefix(scope)) + await sync_to_async(signals.request_started.send, thread_sensitive=True)( + sender=self.__class__, scope=scope + ) + # Get the request and check for basic issues. + request, error_response = self.create_request(scope, body_file) + finally: + body_file.close() if request is None: await self.send_response(error_response, send) return @@ -192,6 +195,7 @@ class ASGIHandler(base.BaseHandler): while True: message = await receive() if message["type"] == "http.disconnect": + body_file.close() # Early client disconnect. raise RequestAborted() # Add a body chunk from the message, if provided.