Ejemplo n.º 1
0
def compile_template(template_string, using=None):
    """
    Load and return a template for the given string.
    """
    engines = _engine_list(using)
    for engine in engines:
        return engine.from_string(template_string)
Ejemplo n.º 2
0
def select_template(template_name_list,
                    using=None,
                    app_label=None,
                    model_name=None):
    """
    Loads and returns a template for one of the given names.

    Tries names in order and returns the first template found.

    Raises TemplateDoesNotExist if no such template exists.
    Hard override accepts app_label and model_name
    """
    if isinstance(template_name_list, six.string_types):
        raise TypeError(
            'select_template() takes an iterable of template names but got a '
            'string: %r. Use get_template() if you want to load a single '
            'template by name.' % template_name_list)

    chain = []
    engines = _engine_list(using)
    for template_name in template_name_list:
        for engine in engines:
            try:
                return engine.get_template(template_name,
                                           app_label=app_label,
                                           model_name=model_name)
            except TemplateDoesNotExist as e:
                chain.append(e)

    if template_name_list:
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    else:
        raise TemplateDoesNotExist("No template names provided")
    def test_call(self, template_on_disk, template_view, local_tz):
        """Assert that TemplateLastModified returns the last modified timestamp of the template"""

        path = Path(template_on_disk)
        last_modified = datetime.fromtimestamp(path.stat().st_mtime,
                                               tz=local_tz)
        assert last_modified == TemplateLastModified()(template_view())

        # Modify the file
        path.touch()

        # This line is required to force django.template.loaders.filesystem.Loader to
        # reload the template.
        _engine_list()[0].engine.template_loaders[0].reset()

        last_modified2 = datetime.fromtimestamp(path.stat().st_mtime,
                                                tz=local_tz)
        assert last_modified != last_modified2
        assert last_modified2 == TemplateLastModified()(template_view())
Ejemplo n.º 4
0
 def get_jinja_engine(self):
     engines = _engine_list()
     found_engine = None
     for engine in engines:
         if isinstance(engine, self.jinja_engine_classes):
             if found_engine is None:
                 found_engine = engine
             else:
                 raise ValueError('Multiple Jinja2 backends found.')
     if found_engine is None:
         raise ValueError('Cannot find django Jinja2 backend.')
     return found_engine
Ejemplo n.º 5
0
    def resolve_template(self, template_string):
        """
        Load and return a template for the given name.

        Raise TemplateDoesNotExist if no such template exists.
        """
        chain = []
        engines = _engine_list()
        for engine in engines:
            try:
                return engine.from_string(template_string)
            except Exception as e:
                chain.append(e)

        raise TemplateDoesNotExist(template_string, chain=chain)
Ejemplo n.º 6
0
 def JINJA2_GET_ENVIRONMENT():
     alias = 'Jinja2'
     try:
         from django.template.loader import _engine_list
         engines = _engine_list(alias)
         if engines:
             engine = engines[0]
             return engine.env
     except InvalidTemplateEngineError:
         raise InvalidTemplateEngineError(
             "Could not find config for '{}' "
             "in settings.TEMPLATES. "
             "COMPRESS_JINJA2_GET_ENVIRONMENT() may "
             "need to be defined in settings".format(alias))
     except ImportError:
         return None
Ejemplo n.º 7
0
def get_template(template_name, using=None, app_label=None, model_name=None):
    """
    Loads and returns a template for the given name.

    Raises TemplateDoesNotExist if no such template exists.
    Hard override accepts app_label and model_name
    """
    chain = []
    engines = _engine_list(using)
    for engine in engines:
        try:
            return engine.get_template(template_name,
                                       app_label=app_label,
                                       model_name=model_name)
        except TemplateDoesNotExist as e:
            chain.append(e)

    raise TemplateDoesNotExist(template_name, chain=chain)
Ejemplo n.º 8
0
def get_loaders():
    if VERSION[:2] < (1, 8):
        from django.template.loader import template_source_loaders
        if template_source_loaders is None:
            try:
                from django.template.loader import find_template as finder
            except ImportError:
                from django.template.loader import find_template_source as finder  # noqa
            try:
                source, name = finder('test')
            except TemplateDoesNotExist:
                pass
            from django.template.loader import template_source_loaders
        return template_source_loaders or []
    else:
        from django.template.loader import _engine_list
        loaders = []
        for engine in _engine_list():
            loaders.extend(engine.engine.template_loaders)
        return loaders
Ejemplo n.º 9
0
def check_template(template_source, using=None):
    """
    Loads and returns a template for the given name.

    Raises TemplateDoesNotExist if no such template exists.
    """
    errs = {}
    engines = _engine_list(using)
    # We should find at least one engine that does not raise an error.
    for engine in engines:
        try:
            try:
                return engine.from_string(template_source)
            except jinja2.TemplateSyntaxError as exc:
                new = TemplateSyntaxError(exc.args)
                new.template_debug = get_exception_info(exc)
                six.reraise(TemplateSyntaxError, new, sys.exc_info()[2])
        except TemplateSyntaxError as err:
            errs.update({engine: err})
    if errs:
        raise TemplateSyntaxError(errs)
Ejemplo n.º 10
0
def get_loaders():
    loaders = []
    try:
        from django.template.loader import _engine_list
        engines = _engine_list()
        for engine in engines:
            try:
                loaders += engine.engine.template_loaders
            except AttributeError:
                pass
            try:
                loaders += engine.template_loaders
            except AttributeError:
                pass

    except ImportError:# django < 1.8
        from django.template.loader import find_template_loader
        for loader_name in django_settings.TEMPLATE_LOADERS:
            template_loader = find_template_loader(loader_name)
            if template_loader is not None:
                loaders.append(template_loader)
    return loaders
Ejemplo n.º 11
0
 def check_xss_vulnerabilities(self, xss_warnings_are_silenced,
                               suppression_path, rule_path):
     engine_obj = engine_loader._engine_list()[0]
     template_loader = template_dir_loader.Loader(engine_obj)
     template_directories = template_loader.get_dirs()
     user_template_directory = template_directories[0]
     template_paths = glob.glob(
         os.path.join(user_template_directory, "*.html"))
     xssdetector = XSSDetector(template_paths, suppression_path, rule_path)
     xssdetector.check()
     num_errors = xssdetector.get_num_errors()
     messages = xssdetector.get_error_messages()
     if num_errors > 0:
         if not xss_warnings_are_silenced:
             self.stdout.write(
                 str(num_errors) +
                 " potential XSS vulnerabilities were found:\n")
             self.stdout.write(messages)
         else:
             self.stdout.write(
                 "Potential XSS vulnerabilities were found (%s silenced).\n"
                 % str(num_errors))
     else:
         self.stdout.write("No XSS threats detected (0 silenced).")
Ejemplo n.º 12
0
import os
from django.contrib.sites.models import Site
from django.core.management.base import CommandError, BaseCommand
from django.template.utils import get_app_template_dirs
from django.template.loader import _engine_list
try:
    from django.utils.six import input as raw_input
except ImportError:
    pass

from dbtemplates.models import Template

ALWAYS_ASK, FILES_TO_DATABASE, DATABASE_TO_FILES = ('0', '1', '2')

DIRS = []
for engine in _engine_list():
    DIRS.extend(engine.dirs)
app_template_dirs = get_app_template_dirs('templates')


class Command(BaseCommand):
    help = "Syncs file system templates with the database bidirectionally."

    def add_arguments(self, parser):
        parser.add_argument("-e",
                            "--ext",
                            dest="ext",
                            action="store",
                            default="html",
                            help="extension of the files you want to "
                            "sync with the database [default: %default]")
Ejemplo n.º 13
0
def template_from_string(template_string, using=None):
    """
    Creates and returns a template for the given string.
    """
    engine = _engine_list(using)[0]
    return engine.from_string(template_string)
Ejemplo n.º 14
0
try:
    from threading import local
except ImportError:
    #pylint: disable=import-error,no-name-in-module
    from django.utils._threading_local import local

_thread_locals = local() #pylint: disable=invalid-name

LOGGER = logging.getLogger(__name__)


# signals hook for Django Templates. Jinja2 templates are done through
# a custom Environment.
#pylint:disable=protected-access
for engine in loader._engine_list():
    if isinstance(engine, DjangoTemplates):
        #pylint:disable=comparison-with-callable
        if Template._render != instrumented_test_render:
            Template.original_render = Template._render
            Template._render = instrumented_test_render
            break

def _add_editable_styles_context(context=None, less_variables=None):
    if context is None:
        context = {}
    if 'editable_styles' not in context:
        if less_variables is None:
            less_variables = {}
        styles_context = copy.deepcopy(settings.BOOTSTRAP_EDITABLE_VARIABLES)
        for _, section_attributes in styles_context:
Ejemplo n.º 15
0
def get_loaders():
    from django.template.loader import _engine_list
    loaders = []
    for engine in _engine_list():
        loaders.extend(engine.engine.template_loaders)
    return loaders
Ejemplo n.º 16
0
 def get_jinja_engine(self):
     engines = _engine_list()
     for engine in engines:
         if isinstance(engine, backend.Jinja2):
             return engine
     raise ValueError('Cannot find django_jinja.backend.Jinja2')