Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ASGI compatibility on Python 3.12 #162

Merged
merged 1 commit into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Changelog
=========

* Fix ASGI compatibility on Python 3.12.

1.7.0 (2023-10-11)
------------------

Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"asgiref>=3.6",
"Django>=3.2",
"minify-html",
]
Expand Down
15 changes: 7 additions & 8 deletions src/django_minify_html/middleware.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from __future__ import annotations

import asyncio
from typing import Awaitable
from typing import Callable

import minify_html
from asgiref.sync import iscoroutinefunction
from asgiref.sync import markcoroutinefunction
from django.http import HttpRequest
from django.http import HttpResponse
from django.http.response import HttpResponseBase
Expand All @@ -22,19 +23,17 @@ def __init__(
),
) -> None:
self.get_response = get_response
if asyncio.iscoroutinefunction(self.get_response):
self.async_mode = iscoroutinefunction(self.get_response)

if self.async_mode:
# Mark the class as async-capable, but do the actual switch
# inside __call__ to avoid swapping out dunder methods
self._is_coroutine = (
asyncio.coroutines._is_coroutine # type: ignore [attr-defined]
)
else:
self._is_coroutine = None
markcoroutinefunction(self)

def __call__(
self, request: HttpRequest
) -> HttpResponseBase | Awaitable[HttpResponseBase]:
if self._is_coroutine:
if self.async_mode:
return self.__acall__(request)
response = self.get_response(request)
assert isinstance(response, HttpResponseBase)
Expand Down