Skip to content
Merged
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
4 changes: 1 addition & 3 deletions .github/workflows/code_quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ jobs:
strategy:
matrix:
toxenv:
- isort
- black
# - flake8
- ruff
- docs
steps:
- uses: actions/checkout@v4
Expand Down
8 changes: 4 additions & 4 deletions CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ checks:
* Pull requests must be accompanied by tests. We use ``pytest`` and prefer using this
testing style over Django's ``django.test.TestCase``.
* Ideally, documentation updates are included in a pull request.
* Imports are sorted using ``isort``, while code is formatted using ``black``. There
are tox environments and CI checks in place to check/enforce this.
* Code formatting and linting is done with ``ruff``. There are tox environments and CI
checks in place to check/enforce this.
* Follow Django's code style where possible.
* Keep commits atomic - one commit should only concern one topic. Bugfixes typically
have one commit for the regression test and one commit with the fix.
Expand Down Expand Up @@ -100,8 +100,8 @@ or to build the full test matrix

.. code-block:: bash

black .
isort .
ruff format .
ruff check --fix .

Should be sufficient. Consider using a pre-commit hook to automate this.

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Manage cookie information and let visitors give or reject consent for them.
![License](https://img.shields.io/pypi/l/django-cookie-consent)
[![Build status][badge:GithubActions:CI]][GithubActions:CI]
[![Code Quality][badge:GithubActions:CQ]][GithubActions:CQ]
[![Code style: black][badge:black]][black]
[![Code style: ruff][badge:ruff]][ruff]
[![Test coverage][badge:codecov]][codecov]
[![Documentation][badge:docs]][docs]

Expand Down Expand Up @@ -36,8 +36,8 @@ from the `docs` directory in this repository.
[badge:GithubActions:CI]: https://github.com/django-commons/django-cookie-consent/workflows/Run%20CI/badge.svg
[GithubActions:CQ]: https://github.com/django-commons/django-cookie-consent/actions?query=workflow%3A%22Code+quality+checks%22
[badge:GithubActions:CQ]: https://github.com/django-commons/django-cookie-consent/workflows/Code%20quality%20checks/badge.svg
[black]: https://github.com/psf/black
[badge:black]: https://img.shields.io/badge/code%20style-black-000000.svg
[ruff]: https://github.com/astral-sh/ruff
[badge:ruff]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
[codecov]: https://codecov.io/gh/django-commons/django-cookie-consent
[badge:codecov]: https://codecov.io/gh/django-commons/django-cookie-consent/branch/master/graph/badge.svg
[docs]: https://django-cookie-consent.readthedocs.io/en/latest/?badge=latest
Expand Down
1 change: 0 additions & 1 deletion cookie_consent/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from django.contrib import admin

from .conf import settings
Expand Down
1 change: 0 additions & 1 deletion cookie_consent/cache.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from django.core.cache import caches

from .conf import settings
Expand Down
1 change: 0 additions & 1 deletion cookie_consent/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from django.conf import settings # NOQA

from appconf import AppConf
Expand Down
5 changes: 1 addition & 4 deletions cookie_consent/middleware.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
# -*- coding: utf-8 -*-
from typing import Optional

from .cache import all_cookie_groups
from .conf import settings
from .util import get_cookie_dict_from_request, is_cookie_consent_enabled


def _should_delete_cookie(group_version: Optional[str]) -> bool:
def _should_delete_cookie(group_version: str | None) -> bool:
# declined after it was accepted (and set) before
if group_version == settings.COOKIE_CONSENT_DECLINE:
return True
Expand Down
3 changes: 2 additions & 1 deletion cookie_consent/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ class Migration(migrations.Migration):
validators=[
django.core.validators.RegexValidator(
re.compile("^[-_a-zA-Z0-9]+$"),
"Enter a valid 'varname' consisting of letters, numbers, underscores or hyphens.",
"Enter a valid 'varname' consisting of letters, "
"numbers, underscores or hyphens.",
"invalid",
)
],
Expand Down
4 changes: 2 additions & 2 deletions cookie_consent/migrations/0003_alter_cookiegroup_varname.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


class Migration(migrations.Migration):

dependencies = [
("cookie_consent", "0002_auto__add_logitem"),
]
Expand All @@ -22,7 +21,8 @@ class Migration(migrations.Migration):
validators=[
django.core.validators.RegexValidator(
re.compile("^[-_a-zA-Z0-9]+$"),
"Enter a valid 'varname' consisting of letters, numbers, underscores or hyphens.",
"Enter a valid 'varname' consisting of letters, numbers, "
"underscores or hyphens.",
"invalid",
)
],
Expand Down
1 change: 0 additions & 1 deletion cookie_consent/migrations/0004_cookie_natural_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@


class Migration(migrations.Migration):

dependencies = [
("cookie_consent", "0003_alter_cookiegroup_varname"),
]
Expand Down
12 changes: 6 additions & 6 deletions cookie_consent/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import re
from typing import TypedDict

Expand Down Expand Up @@ -144,7 +143,7 @@ class Meta:
ordering = ["-created"]

def __str__(self):
return "%s %s%s" % (self.name, self.domain, self.path)
return f"{self.name} {self.domain}{self.path}"

@clear_cache_after
def save(self, *args, **kwargs):
Expand All @@ -161,7 +160,8 @@ def natural_key(self):

@property
def varname(self):
return "%s=%s:%s" % (self.cookiegroup.varname, self.name, self.domain)
group_varname = self.cookiegroup.varname
return f"{group_varname}={self.name}:{self.domain}"

def get_version(self):
return self.created.isoformat()
Expand All @@ -185,10 +185,10 @@ class LogItem(models.Model):
version = models.CharField(_("Version"), max_length=32)
created = models.DateTimeField(_("Created"), auto_now_add=True, blank=True)

def __str__(self):
return "%s %s" % (self.cookiegroup.name, self.version)

class Meta:
verbose_name = _("Log item")
verbose_name_plural = _("Log items")
ordering = ["-created"]

def __str__(self):
return f"{self.cookiegroup.name} {self.version}"
1 change: 0 additions & 1 deletion cookie_consent/templatetags/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
14 changes: 12 additions & 2 deletions cookie_consent/templatetags/cookie_consent_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def get_accept_cookie_groups_cookie_string(request, cookie_groups): # pragma: n
"Cookie string template tags for JS are deprecated and will be removed "
"in django-cookie-consent 1.0",
DeprecationWarning,
stacklevel=1,
)
cookie_dic = get_cookie_dict_from_request(request)
for cookie_group in cookie_groups:
Expand All @@ -113,6 +114,7 @@ def get_decline_cookie_groups_cookie_string(request, cookie_groups):
"Cookie string template tags for JS are deprecated and will be removed "
"in django-cookie-consent 1.0",
DeprecationWarning,
stacklevel=1,
)
cookie_dic = get_cookie_dict_from_request(request)
for cookie_group in cookie_groups:
Expand All @@ -133,12 +135,14 @@ def js_type_for_cookie_consent(request, varname, cookie=None):
alert("Social cookie accepted");
</script>
"""
# This approach doesn't work with page caches and/or strict Content-Security-Policies
# (unless you use nonces, which again doesn't work with aggressive page caching).
# This approach doesn't work with page caches and/or strict
# Content-Security-Policies (unless you use nonces, which again doesn't work with
# aggressive page caching).
warnings.warn(
"Template tags for use in/with JS are deprecated and will be removed "
"in django-cookie-consent 1.0",
DeprecationWarning,
stacklevel=1,
)
enabled = is_cookie_consent_enabled(request)
if not enabled:
Expand All @@ -162,6 +166,12 @@ def accepted_cookies(request):
{{ request|accepted_cookies }}

"""
warnings.warn(
"The 'accepted_cookies' template filter is deprecated and will be removed"
"in django-cookie-consent 1.0.",
DeprecationWarning,
stacklevel=1,
)
return [c.varname for c in get_accepted_cookies(request)]


Expand Down
1 change: 0 additions & 1 deletion cookie_consent/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from django.urls import path, re_path
from django.views.decorators.csrf import csrf_exempt

Expand Down
10 changes: 4 additions & 6 deletions cookie_consent/util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
import datetime
import logging
from typing import Dict, Union

from .cache import all_cookie_groups, get_cookie, get_cookie_group
from .conf import settings
Expand All @@ -13,7 +11,7 @@
KEY_VALUE_SEP = "="


def parse_cookie_str(cookie: str) -> Dict[str, str]:
def parse_cookie_str(cookie: str) -> dict[str, str]:
if not cookie:
return {}

Expand Down Expand Up @@ -171,7 +169,7 @@ def are_all_cookies_accepted(request):
)


def _get_cookie_groups_by_state(request, state: Union[bool, None]):
def _get_cookie_groups_by_state(request, state: bool | None):
return [
cookie_group
for cookie_group in get_cookie_groups()
Expand Down Expand Up @@ -219,7 +217,7 @@ def get_cookie_string(cookie_dic):
expires = datetime.datetime.now() + datetime.timedelta(
seconds=settings.COOKIE_CONSENT_MAX_AGE
)
cookie_str = "%s=%s; expires=%s; path=/" % (
cookie_str = "{}={}; expires={}; path=/".format(
settings.COOKIE_CONSENT_NAME,
dict_to_cookie_str(cookie_dic),
expires.strftime("%a, %d %b %Y %H:%M:%S GMT"),
Expand All @@ -239,5 +237,5 @@ def get_accepted_cookies(request):
continue
for cookie in cookie_group.cookie_set.all():
if version >= cookie.get_version():
accepted_cookies.append(cookie)
accepted_cookies.append(cookie) # noqa: PERF401
return accepted_cookies
1 change: 0 additions & 1 deletion cookie_consent/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from django.contrib.auth.views import RedirectURLMixin
from django.core.exceptions import SuspiciousOperation
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponse
Expand Down
3 changes: 1 addition & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import os
import sys
from pathlib import Path
Expand All @@ -14,7 +13,7 @@

django.setup()

from cookie_consent import __version__ # isort:skip
from cookie_consent import __version__ # noqa: E402

# -- General configuration -----------------------------------------------------

Expand Down
6 changes: 3 additions & 3 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Django cookie consent

Manage cookie information and let visitors give or reject consent for them.

|build-status| |code-quality| |black| |coverage| |docs|
|build-status| |code-quality| |ruff| |coverage| |docs|

|python-versions| |django-versions| |pypi-version|

Expand Down Expand Up @@ -63,8 +63,8 @@ Indices and tables
:alt: Code quality checks
:target: https://github.com/django-commons/django-cookie-consent/actions?query=workflow%3A%22Code+quality+checks%22

.. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
.. |ruff| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
:target: https://github.com/astral-sh/ruff

.. |coverage| image:: https://codecov.io/gh/django-commons/django-cookie-consent/branch/master/graph/badge.svg
:target: https://codecov.io/gh/django-commons/django-cookie-consent
Expand Down
43 changes: 29 additions & 14 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,12 @@ Changelog = "https://github.com/django-commons/django-cookie-consent/blob/master
[project.optional-dependencies]
tests = [
"pytest",
"pytest-cov",
"pytest-django",
"pytest-playwright",
"hypothesis",
"tox",
"isort",
"black",
"flake8",
]
coverage = [
"pytest-cov",
"ruff",
]
docs = [
"sphinx",
Expand All @@ -71,14 +67,6 @@ version = {attr = "cookie_consent.__version__"}
include = ["cookie_consent*"]
namespaces = true

[tool.isort]
profile = "black"
combine_as_imports = true
skip = ["env", ".tox", ".history", ".eggs"]
known_django = "django"
known_first_party="cookie_consent"
sections=["FUTURE", "STDLIB", "DJANGO", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"]

[tool.pytest.ini_options]
testpaths = ["tests"]
DJANGO_SETTINGS_MODULE = "testapp.settings"
Expand All @@ -105,3 +93,30 @@ exclude_also = [
"\\.\\.\\.",
"\\bpass$",
]

[tool.ruff.lint]
extend-select = [
"UP", # pyupgrade
"DJ", # django
"LOG", # logging
"G",
"I", # isort
"E", # pycodestyle
"F", # pyflakes
"PERF",# perflint
"B", # flake8-bugbear
]

[tool.ruff.lint.isort]
combine-as-imports = true
section-order = [
"future",
"standard-library",
"django",
"third-party",
"first-party",
"local-folder",
]

[tool.ruff.lint.isort.sections]
"django" = ["django"]
4 changes: 0 additions & 4 deletions setup.cfg

This file was deleted.

1 change: 0 additions & 1 deletion testapp/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from django.views.generic import TemplateView

from cookie_consent.util import get_cookie_value_from_request
Expand Down
1 change: 0 additions & 1 deletion tests/test_cache.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
from django.test import TestCase, override_settings

from cookie_consent.cache import delete_cache, get_cookie, get_cookie_group
Expand Down
Loading