Skip to content

Commit

Permalink
Add ASGI support (#127)
Browse files Browse the repository at this point in the history
This commit updates the middleware to handle applications using ASGI

Type: feature

Co-authored-by: Gadhi Rodriguez <[email protected]>
  • Loading branch information
pablogadhi and Gadhi Rodriguez authored Aug 27, 2024
1 parent 5692a3e commit 76d4438
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion pghistory/middleware.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.core.handlers.asgi import ASGIRequest as DjangoASGIRequest
from django.core.handlers.wsgi import WSGIRequest as DjangoWSGIRequest
from django.db import connection

import pghistory
from pghistory import config


class WSGIRequest(DjangoWSGIRequest):
class DjangoRequest:
"""
Although Django's auth middleware sets the user in middleware,
apps like django-rest-framework set the user in the view layer.
Expand All @@ -28,6 +29,14 @@ def __setattr__(self, attr, value):
return super().__setattr__(attr, value)


class WSGIRequest(DjangoRequest, DjangoWSGIRequest):
pass


class ASGIRequest(DjangoRequest, DjangoASGIRequest):
pass


def HistoryMiddleware(get_response):
"""
Annotates the user/url in the pghistory context.
Expand All @@ -43,6 +52,8 @@ def middleware(request):
with pghistory.context(user=user, url=request.path):
if isinstance(request, DjangoWSGIRequest): # pragma: no branch
request.__class__ = WSGIRequest
elif isinstance(request, DjangoASGIRequest): # pragma: no branch
request.__class__ = ASGIRequest

return get_response(request)
else:
Expand Down

0 comments on commit 76d4438

Please sign in to comment.