Skip to content

Commit

Permalink
Add settings
Browse files Browse the repository at this point in the history
  • Loading branch information
mjnaderi committed Sep 13, 2022
1 parent b56ab27 commit 010a351
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 5 deletions.
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Count visits in your view like this:
```python
def view_blog_post(request, post_id):
post = get_object_or_404(MyBlogPost, pk=post_id)
post.update_visit_count()
post.count_visit()
...
```

Expand All @@ -59,6 +59,17 @@ def view_blog_post(request, post_id):
...
```

You can pass an optional keyword argument `session_duration` (integer, number of seconds)
to `count_visit` or `is_new_visit`.

## Settings

Default settings:

```python
VISIT_COUNT_DEFAULT_SESSION_DURATION = 5 * 60 # seconds
```

## Development

- Install development dependencies in your virtualenv with `pip install -e '.[dev]'`
Expand Down
5 changes: 5 additions & 0 deletions django_visit_count/app_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import os

from django.conf import settings

VISIT_COUNT_DEFAULT_SESSION_DURATION = getattr(settings, "VISIT_COUNT_DEFAULT_SESSION_DURATION", 5 * 60)
5 changes: 3 additions & 2 deletions django_visit_count/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
from django.db.models import F
from django.utils.translation import gettext_lazy as _

from .app_settings import VISIT_COUNT_DEFAULT_SESSION_DURATION
from .utils import is_new_visit


class VisitCountMixin:
visit_count = models.PositiveIntegerField(default=0, help_text=_("Visit count"))

def update_visit_count(self, request):
if is_new_visit(request, self):
def count_visit(self, request, session_duration=VISIT_COUNT_DEFAULT_SESSION_DURATION):
if is_new_visit(request, self, session_duration=session_duration):
self.visit_count = F("visit_count") + 1
self.save(update_fields=["visit_count"])
6 changes: 4 additions & 2 deletions django_visit_count/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from django.core.cache import cache
from ipware import get_client_ip

from .app_settings import VISIT_COUNT_DEFAULT_SESSION_DURATION

def is_new_visit(request, obj, *, timeout=5 * 60):

def is_new_visit(request, obj, *, session_duration=VISIT_COUNT_DEFAULT_SESSION_DURATION):
if request.user.is_authenticated:
user_key = f"user-{request.user.id}"
else:
Expand All @@ -16,5 +18,5 @@ def is_new_visit(request, obj, *, timeout=5 * 60):
if cache.get(cache_key):
return False

cache.set(cache_key, True, timeout)
cache.set(cache_key, True, timeout=session_duration)
return True

0 comments on commit 010a351

Please sign in to comment.