summaryrefslogtreecommitdiffstats
path: root/accounts/utils/__init__.py
blob: dfb02af11782af2788a59ece060f5a12830b5f2c (plain)
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
47
48
49
50
51
52
53
54
# -*- coding: utf-8 -*-
import importlib
from functools import wraps
from flask import render_template, request, Flask
from wtforms.validators import Regexp, ValidationError

from typing import Optional, Callable, Any


# using http://flask.pocoo.org/docs/patterns/viewdecorators/
def templated(
    template: Optional[str] = None,
) -> Callable[..., Callable[..., str]]:
    def templated_(f: Callable[..., str]) -> Callable[..., str]:
        @wraps(f)
        def templated__(*args: list[Any], **kwargs: dict[str, Any]) -> str:
            template_name = template
            if template_name is None:
                if request.endpoint:
                    template_name = (
                        request.endpoint.replace(".", "/") + ".html"
                    )
                else:
                    template_name = "error.html"
            ctx = f(*args, **kwargs)
            if ctx is None:
                ctx = {}
            elif not isinstance(ctx, dict):
                return ctx
            return render_template(template_name, **ctx)

        return templated__

    return templated_


class NotRegexp(Regexp):
    """
    Like wtforms.validators.Regexp, but rejects data that DOES match the regex.
    """

    def __call__(self, form, field):
        if self.regex.match(field.data or ""):
            if self.message is None:
                self.message: str = field.gettext("Invalid input.")

            raise ValidationError(self.message)


def get_backend(path: str, app: Flask):
    module = path.rsplit(".", 1).pop()
    class_name = "%sBackend" % module.title()
    backend_class = getattr(importlib.import_module(path), class_name)
    return backend_class(app)