# -*- 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 # using http://flask.pocoo.org/docs/patterns/viewdecorators/ def templated(template: Optional[str] = None): def templated_(f): @wraps(f) def templated__(*args, **kwargs): 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)