Skip to content
This repository was archived by the owner on Jul 26, 2024. It is now read-only.
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
33 changes: 28 additions & 5 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,42 @@ on:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:

jobs:
build:
test_from_py38:
# On python 3.8 and higher, all our Django versions are supported.
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [ '3.8', '3.9', '3.10', '3.11' ]

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install poetry
poetry install
- name: Test with tox
run: |
poetry run tox -e 'django{22,30,31,32,40,41,42}'

test_on_py37:
# On python 3.7, Django 4.2 is not supported.
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [ 3.7, 3.8, 3.9 ]
python-version: [ '3.7',]

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
Expand All @@ -30,4 +53,4 @@ jobs:
poetry install
- name: Test with tox
run: |
poetry run tox
poetry run tox -e 'django{22,30,31,32}'
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,28 @@ Allows you to clear Django cache via admin UI or manage.py command.
]
```

4. Apply migrations:

```
manage.py migrate [--database=<your_database>] [--settings=<your_settings>]
```

## Usage

### Via Django admin

1. Go to `/admin/clearcache/`, you should see a form with cache selector
Clearcache can be used by any user with permission ```clearcache.use_clearcache```,
and obviously be any superuser (superusers have all permissions).

1. Go to `/admin/clearcache/`. If you are authorized, you should see a form with cache selector.
2. Pick a cache. Usually there's one default cache, but can be more.
3. Click the button, you're done!

Any user with access to the Admin interface (i.e. any user with `is_staff` privilege)
will see a Clearcache section on the Admin homepage, if he is authorized, and can
access Clearcache from there.


### Via manage.py command

1. Run the following command to clear the default cache
Expand All @@ -60,5 +74,5 @@ Allows you to clear Django cache via admin UI or manage.py command.

## Follow me

1. Check my dev blog with Python and JavaScript tutorials at [https://timonweb.com](https://timonweb.com)
2. Follow me on twitter [@timonweb](https://twitter.com/timonweb)
1. Check my dev blog with Python and JavaScript tutorials at [https://timonweb.com](https://timonweb.com).
2. Follow me on Twitter [@timonweb](https://twitter.com/timonweb)
25 changes: 25 additions & 0 deletions clearcache/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 2.2.9 on 2023-08-19 21:27

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='CustomPermissions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
options={
'permissions': (('use_clearcache', "Can see clearcache UI in Admin, and use the 'clearcache_admin' view."),),
'managed': False,
'default_permissions': (),
},
),
]
Empty file.
14 changes: 14 additions & 0 deletions clearcache/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from django.db.models import Model


class CustomPermissions(Model):
"""
This model just defines custom permissions, without a corresponding table in the database.
"""
class Meta:
managed = False # No database table creation or deletion operations will be performed for this model.
default_permissions = () # disable "add", "change", "delete" and "view" default permissions for this model.
permissions = (
('use_clearcache',
"Can see clearcache UI in Admin, and use the 'clearcache_admin' view."),
)
29 changes: 16 additions & 13 deletions clearcache/templates/admin/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@

{% block sidebar %}
{{ block.super }}
<div class="app-clear-cache module">
<table>
<caption>
<a href="{% url 'clearcache_admin' %}" class="section" title="Clear cache">Clear cache</a>
</caption>
<tbody>
<tr class="model-user">
<th scope="row"><a href="{% url 'clearcache_admin' %}">Clear cache</a></th>
<td></td>
</tr>
</tbody>
</table>
</div>
{# do not add the clearcache div if the user is not allowed to use clearcache #}
{% if perms.clearcache.use_clearcache %}
<div class="app-clear-cache module">
<table>
<caption>
<a href="{% url 'clearcache_admin' %}" class="section" title="Clear cache">Clear cache</a>
</caption>
<tbody>
<tr class="model-user">
<th scope="row"><a href="{% url 'clearcache_admin' %}">Clear cache</a></th>
<td></td>
</tr>
</tbody>
</table>
</div>
{% endif %}
{% endblock %}
80 changes: 80 additions & 0 deletions clearcache/tests/test_regular_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""
Test clearcache with regular user
"""

import pytest
from django.contrib.auth.models import Permission
from django.core.cache import cache
from django.urls import reverse

CACHE_KEY = 'example_cache_key'
CACHE_VALUE = 'example_cache_value'
CACHE_EXPIRE_IN_SEC = 1


@pytest.fixture
def regular_user_no_permission(db, django_user_model, django_username_field):
user = django_user_model.objects.create_user(
**{django_username_field: "username_no_perm",
'password': "xxx"})
user.is_staff = True # To access Admin
user.save()
return user


@pytest.fixture
def regular_user_with_permission(db, django_user_model, django_username_field):
user = django_user_model.objects.create_user(**{django_username_field: "username_with_perm",
'password': "xxx"})
permission = Permission.objects.get(codename="use_clearcache")
user.user_permissions.add(permission)
user.is_staff = True
user.save()
return user



@pytest.mark.django_db
def test_clear_cache_in_admin_index(client,
regular_user_no_permission,
regular_user_with_permission):
client.force_login(regular_user_no_permission)
response = client.get('/admin/')
assert response.status_code == 200
assert "Clear cache" not in str(response.content)
client.force_login(regular_user_with_permission)
assert response.status_code == 200
response = client.get('/admin/')
assert "Clear cache" in str(response.content)


@pytest.mark.django_db
def test_clear_access_to_clearcache_form(client,
regular_user_no_permission,
regular_user_with_permission):
url = reverse('clearcache_admin')
client.force_login(regular_user_no_permission)
response = client.get(url)
assert response.status_code in [403, 302]
client.force_login(regular_user_with_permission)
response = client.get(url)
assert response.status_code == 200
assert "Clear cache now" in str(response.content), "Clear cache now button is visible"


@pytest.mark.django_db
def test_clears_cache_via_admin_ui(client,
regular_user_no_permission,
regular_user_with_permission):
cache.set(CACHE_KEY, CACHE_VALUE, 100)
assert cache.get(CACHE_KEY) == CACHE_VALUE, "Cache populated"
client.force_login(regular_user_no_permission)
client.post(reverse('clearcache_admin'), {
'cache_name': 'default'
})
assert cache.get(CACHE_KEY) == CACHE_VALUE, "Cache not cleared"
client.force_login(regular_user_with_permission)
client.post(reverse('clearcache_admin'), {
'cache_name': 'default'
})
assert cache.get(CACHE_KEY) is None, "Cache cleared"
6 changes: 4 additions & 2 deletions clearcache/tests.py → clearcache/tests/test_superuser.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
"""
Test clearcache with superuser
"""
import time

import pytest
Expand All @@ -7,11 +10,10 @@

CACHE_KEY = 'example_cache_key'
CACHE_VALUE = 'example_cache_value'
CACHE_EXPIRE_IN_SEC = 1


def test_cache_works():
CACHE_EXPIRE_IN_SEC = 1

assert cache.get(CACHE_KEY) is None, "The value isn't cached yet"

cache.set(CACHE_KEY, CACHE_VALUE, CACHE_EXPIRE_IN_SEC)
Expand Down
4 changes: 2 additions & 2 deletions clearcache/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ class ClearCacheAdminView(UserPassesTestMixin, FormView):
success_url = reverse_lazy('clearcache_admin')

def test_func(self):
# Only super user can clear caches via admin.
return self.request.user.is_superuser
# Only users with permission can clear caches (superusers have all permissions)
return self.request.user.has_perm("clearcache.use_clearcache")

def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, args, kwargs)
Expand Down
Empty file modified manage.py
100644 → 100755
Empty file.
Loading