File: django.py

package info (click to toggle)
python-html-sanitizer 1.9.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 152 kB
  • sloc: python: 803; sh: 24; makefile: 2
file content (46 lines) | stat: -rw-r--r-- 1,337 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from __future__ import absolute_import, unicode_literals

from django.conf import settings
from django.core import checks
from django.core.exceptions import ImproperlyConfigured

from .sanitizer import Sanitizer

try:
    from functools import lru_cache
except ImportError:  # pragma: no cover
    # Django versions older than 3.0
    from django.utils.lru_cache import lru_cache


def _get_sanitizer(name="default"):
    sanitizers = getattr(settings, "HTML_SANITIZERS", {})
    if name in sanitizers:
        return Sanitizer(sanitizers[name])
    elif name == "default":
        return Sanitizer()
    raise ImproperlyConfigured(
        "Unknown sanitizer %r, did you define HTML_SANITIZERS[%r] in your"
        " Django settings module?" % (name, name)
    )


get_sanitizer = lru_cache(maxsize=None)(_get_sanitizer)


@checks.register()
def check_configuration(app_configs, **kwargs):
    errors = []
    sanitizers = ["default"] + list(getattr(settings, "HTML_SANITIZERS", {}))
    for name in sorted(set(sanitizers)):
        try:
            _get_sanitizer(name)
        except TypeError as exc:
            errors.append(
                checks.Error(
                    "Invalid sanitizer configuration '%s': %s" % (name, exc),
                    id="html_sanitizer.E001",
                )
            )

    return errors