Skip to content

Commit

Permalink
Merge pull request #1 from TreyWW/feature/decorator_for_django_views
Browse files Browse the repository at this point in the history
Added new decorator
  • Loading branch information
TreyWW authored Mar 23, 2024
2 parents 031af82 + 29139ab commit 963e5fa
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
5 changes: 4 additions & 1 deletion django_umami/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ class UmamiPayload:
def dict(self):
data = {"website": self.website}
if self.data:
print("has data")
data |= self.data
return data

Expand Down Expand Up @@ -87,6 +86,10 @@ def send(self, payload: UmamiPayload):
return self.options.session.post(url=f"{self.options.host_url}/api/send", json=data, headers=headers)
return requests.post(url=f"{self.options.host_url}/api/send", json=data, headers=headers)

def track_event_name(self, event_name: str):
payload = UmamiPayload(website=self.options.website_id, data={"name": event_name})
return self.send(payload=payload)

def track(self, event: UmamiEventData | str, event_data=None):
website_id = self.options.website_id

Expand Down
31 changes: 29 additions & 2 deletions django_umami/decorators.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,42 @@
from functools import wraps
from typing import Optional

from django.http import HttpRequest

from django_umami.core import umami, UmamiEventData


def track(event_name: str, event_data: UmamiEventData = None):
def track(event: UmamiEventData | str, event_data: Optional[UmamiEventData] = None):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
umami.track(event_name, event_data)
umami.track(event, event_data)
return func(*args, **kwargs)

return wrapper

return decorator


def track_visit(event_data: Optional[UmamiEventData] = None):
def decorator(func):
@wraps(func)
def wrapper(request: HttpRequest, *args, **kwargs):
new_event_data: UmamiEventData = event_data or UmamiEventData()

data: UmamiEventData = UmamiEventData(
url=request.path,
referrer=request.META.get("HTTP_REFERER", ""),
title=request.META.get("HTTP_TITLE", ""),
)

new_event_data.update(
{k: v for k, v in data.items() if k not in new_event_data} # type: ignore[typeddict-item]
)

umami.track(new_event_data)
return func(request, *args, **kwargs)

return wrapper

return decorator

0 comments on commit 963e5fa

Please sign in to comment.