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

Add support for async middleware. #31

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
10 changes: 5 additions & 5 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
line-length = 88
ignore = [
lint.ignore = [
"D100", # Missing docstring in public module
"D101", # Missing docstring in public class
"D102", # Missing docstring in public method
Expand All @@ -22,7 +22,7 @@ ignore = [
"D417",
"D417", # Missing argument description in the docstring
]
select = [
lint.select = [
"A", # flake8 builtins
"C9", # mcabe
"D", # pydocstyle
Expand All @@ -34,13 +34,13 @@ select = [
"W", # pycodestype (warnings)
]

[isort]
[lint.isort]
combine-as-imports = true

[mccabe]
[lint.mccabe]
max-complexity = 8

[per-file-ignores]
[lint.per-file-ignores]
"*tests/*" = [
"D205", # 1 blank line required between summary line and description
"D400", # First line should end with a period
Expand Down
65 changes: 50 additions & 15 deletions user_visit/middleware.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import inspect
import logging
import typing

import django.db
from asgiref.sync import sync_to_async
from django.contrib.auth.models import AbstractBaseUser, AnonymousUser
from django.core.exceptions import MiddlewareNotUsed
from django.http import HttpRequest, HttpResponse
from django.utils import timezone
from django.utils.decorators import sync_and_async_middleware

from user_visit.models import UserVisit

Expand All @@ -24,23 +28,54 @@ def save_user_visit(user_visit: UserVisit) -> None:
)


class UserVisitMiddleware:
"""Middleware to record user visits."""
# Atomic transactions are not supported async yet
# https://docs.djangoproject.com/en/5.0/topics/async/
asave_user_visit = sync_to_async(save_user_visit)

def __init__(self, get_response: typing.Callable) -> None:
if RECORDING_DISABLED:
raise MiddlewareNotUsed("UserVisit recording has been disabled")
self.get_response = get_response

def __call__(self, request: HttpRequest) -> typing.Optional[HttpResponse]:
if request.user.is_anonymous:
return self.get_response(request)
@sync_to_async
def aget_user_from_request(
request: HttpRequest,
) -> AbstractBaseUser | AnonymousUser | None:
return request.user if bool(request.user) else None

if RECORDING_BYPASS(request):
return self.get_response(request)

uv = UserVisit.objects.build(request, timezone.now())
if not UserVisit.objects.filter(hash=uv.hash).exists():
save_user_visit(uv)
@sync_and_async_middleware
def UserVisitMiddleware( # noqa
get_response: typing.Callable,
) -> typing.Callable:
if RECORDING_DISABLED:
raise MiddlewareNotUsed("UserVisit recording has been disabled")

return self.get_response(request)
if inspect.iscoroutinefunction(get_response):

async def middleware(request: HttpRequest) -> typing.Optional[HttpResponse]:
user = await aget_user_from_request(request)
if not user or user.is_anonymous:
return await typing.cast(typing.Awaitable, get_response(request))

if RECORDING_BYPASS(request):
return await typing.cast(typing.Awaitable, get_response(request))

uv = UserVisit.objects.build(request, timezone.now())
if not await UserVisit.objects.filter(hash=uv.hash).aexists():
await asave_user_visit(uv)

return await typing.cast(typing.Awaitable, get_response(request))

else:

def middleware(request: HttpRequest) -> typing.Optional[HttpResponse]: # type: ignore
if request.user.is_anonymous:
return get_response(request)

if RECORDING_BYPASS(request):
return get_response(request)

uv = UserVisit.objects.build(request, timezone.now())
if not UserVisit.objects.filter(hash=uv.hash).exists():
save_user_visit(uv)

return get_response(request)

return middleware