def test_loaders_security(self): ad_loader = app_directories.Loader(Engine.get_default()) fs_loader = filesystem.Loader(Engine.get_default()) def test_template_sources(path, template_dirs, expected_sources): if isinstance(expected_sources, list): # Fix expected sources so they are abspathed expected_sources = [ os.path.abspath(s) for s in expected_sources ] # Test the two loaders (app_directores and filesystem). func1 = lambda p, t: list(ad_loader.get_template_sources(p, t)) func2 = lambda p, t: list(fs_loader.get_template_sources(p, t)) for func in (func1, func2): if isinstance(expected_sources, list): self.assertEqual(func(path, template_dirs), expected_sources) else: self.assertRaises(expected_sources, func, path, template_dirs) template_dirs = ['/dir1', '/dir2'] test_template_sources('index.html', template_dirs, ['/dir1/index.html', '/dir2/index.html']) test_template_sources('/etc/passwd', template_dirs, []) test_template_sources('etc/passwd', template_dirs, ['/dir1/etc/passwd', '/dir2/etc/passwd']) test_template_sources('../etc/passwd', template_dirs, []) test_template_sources('../../../etc/passwd', template_dirs, []) test_template_sources('/dir1/index.html', template_dirs, ['/dir1/index.html']) test_template_sources('../dir2/index.html', template_dirs, ['/dir2/index.html']) test_template_sources('/dir1blah', template_dirs, []) test_template_sources('../dir1blah', template_dirs, []) # UTF-8 bytestrings are permitted. test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', template_dirs, ['/dir1/Ångström', '/dir2/Ångström']) # Unicode strings are permitted. test_template_sources('Ångström', template_dirs, ['/dir1/Ångström', '/dir2/Ångström']) test_template_sources('Ångström', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström']) test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström']) # Invalid UTF-8 encoding in bytestrings is not. Should raise a # semi-useful error message. test_template_sources(b'\xc3\xc3', template_dirs, UnicodeDecodeError) # Case insensitive tests (for win32). Not run unless we're on # a case insensitive operating system. if os.path.normcase('/TEST') == os.path.normpath('/test'): template_dirs = ['/dir1', '/DIR2'] test_template_sources('index.html', template_dirs, ['/dir1/index.html', '/DIR2/index.html']) test_template_sources('/DIR1/index.HTML', template_dirs, ['/DIR1/index.HTML'])
def test_loaders_security(self): ad_loader = app_directories.Loader(Engine.get_default()) fs_loader = filesystem.Loader(Engine.get_default()) def test_template_sources(path, template_dirs, expected_sources): if isinstance(expected_sources, list): # Fix expected sources so they are abspathed expected_sources = [os.path.abspath(s) for s in expected_sources] # Test the two loaders (app_directores and filesystem). func1 = lambda p, t: list(ad_loader.get_template_sources(p, t)) func2 = lambda p, t: list(fs_loader.get_template_sources(p, t)) for func in (func1, func2): if isinstance(expected_sources, list): self.assertEqual(func(path, template_dirs), expected_sources) else: self.assertRaises(expected_sources, func, path, template_dirs) template_dirs = ['/dir1', '/dir2'] test_template_sources('index.html', template_dirs, ['/dir1/index.html', '/dir2/index.html']) test_template_sources('/etc/passwd', template_dirs, []) test_template_sources('etc/passwd', template_dirs, ['/dir1/etc/passwd', '/dir2/etc/passwd']) test_template_sources('../etc/passwd', template_dirs, []) test_template_sources('../../../etc/passwd', template_dirs, []) test_template_sources('/dir1/index.html', template_dirs, ['/dir1/index.html']) test_template_sources('../dir2/index.html', template_dirs, ['/dir2/index.html']) test_template_sources('/dir1blah', template_dirs, []) test_template_sources('../dir1blah', template_dirs, []) # UTF-8 bytestrings are permitted. test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', template_dirs, ['/dir1/Ångström', '/dir2/Ångström']) # Unicode strings are permitted. test_template_sources('Ångström', template_dirs, ['/dir1/Ångström', '/dir2/Ångström']) test_template_sources('Ångström', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström']) test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström']) # Invalid UTF-8 encoding in bytestrings is not. Should raise a # semi-useful error message. test_template_sources(b'\xc3\xc3', template_dirs, UnicodeDecodeError) # Case insensitive tests (for win32). Not run unless we're on # a case insensitive operating system. if os.path.normcase('/TEST') == os.path.normpath('/test'): template_dirs = ['/dir1', '/DIR2'] test_template_sources('index.html', template_dirs, ['/dir1/index.html', '/DIR2/index.html']) test_template_sources('/DIR1/index.HTML', template_dirs, ['/DIR1/index.HTML'])
def patch_builtins(library): if django.VERSION < (1, 9): return patch('django.template.base.builtins', [library]) else: from django.template.engine import Engine engine = Engine.get_default() return patch.object(engine, 'template_builtins', [library])
def setUp(self): self.loader = eggs.Loader(Engine.get_default()) # Defined here b/c at module scope we may not have pkg_resources class MockProvider(pkg_resources.NullProvider): def __init__(self, module): pkg_resources.NullProvider.__init__(self, module) self.module = module def _has(self, path): return path in self.module._resources def _isdir(self, path): return False def get_resource_stream(self, manager, resource_name): return self.module._resources[resource_name] def _get(self, path): return self.module._resources[path].read() def _fn(self, base, resource_name): return os.path.normcase(resource_name) pkg_resources._provider_factories[MockLoader] = MockProvider self.empty_egg = create_egg("egg_empty", {}) self.egg_1 = create_egg("egg_1", { os.path.normcase('templates/y.html'): StringIO("y"), os.path.normcase('templates/x.txt'): StringIO("x"), })
def _base_detail( request, instance, template_name='detail.html', item_name="char_1", template_string='', ): context = {} context['instance'] = instance context['instance_class'] = instance.__class__() context['item_name'] = item_name if hasattr(request, 'toolbar'): request.toolbar.set_object(instance) if template_string: context = RequestContext(request=request, dict_=context) if DJANGO_1_7: template = Template(template_string) return HttpResponse(template.render(context)) else: from django.template.engine import Engine engine = Engine.get_default() template = engine.from_string(template_string) return HttpResponse(template.render(context)) else: return render(request, template_name, context)
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = os.path.join(directory, template) if os.path.exists(template_file): with open(template_file) as f: template_contents = f.read() else: template_contents = '' templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': template_contents, 'order': index, }) kwargs.update({ 'name': template, 'templates': templates, }) return super().get_context_data(**kwargs)
def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) if title: title = utils.parse_rst(title, 'filter', _('filter:') + filter_name) if body: body = utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name) tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) kwargs.update({'filters': filters}) return super().get_context_data(**kwargs)
def get_context_data(self, **kwargs): tags = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [("", lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for tag_name, tag_func in library.tags.items(): title, body, metadata = utils.parse_docstring( tag_func.__doc__) title = title and utils.parse_rst(title, "tag", _("tag:") + tag_name) body = body and utils.parse_rst(body, "tag", _("tag:") + tag_name) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], "tag", _("tag:") + tag_name) tag_library = module_name.split(".")[-1] tags.append({ "name": tag_name, "title": title, "body": body, "meta": metadata, "library": tag_library, }) return super().get_context_data(**{**kwargs, "tags": tags})
def _handler(self, request, *args, **kwargs): # Rethinking of this logic in 5 years, aka, working around RequestContext that doesn't seem to actually work context = {} for processor in Engine.get_default().context_processors: context.update(import_string(processor)(self.request)) if context['page'] and context['exact_match']: if context['page'].redirect_url: if context['page'].redirect_permanent: return HttpResponsePermanentRedirect(context['page'].redirect_url) else: return HttpResponseRedirect(context['page'].redirect_url) if context['page'].view: if context['page'].view.find('.as_view(') != -1: pass else: cls = get_callable(context['page'].view) return cls(request) if context['page'].template: self.template_name = context['page'].template elif context['page'].inherit_template: for i in context['pageA']: if i.template: self.template_name = i.template content = loader.render_to_string(self.template_name, context) return HttpResponse(content) raise Http404
def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring( filter_func.__doc__) title = title and utils.parse_rst( title, 'filter', _('filter:') + filter_name) body = body and utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], 'filter', _('filter:') + filter_name) tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return super().get_context_data(**{**kwargs, 'filters': filters})
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(directory) / template if template_file.exists(): with template_file.open() as f: template_contents = f.read() else: template_contents = '' templates.append({ 'file': template_file, 'exists': template_file.exists(), 'contents': template_contents, 'order': index, }) return super().get_context_data(**{ **kwargs, 'name': template, 'Templates': templates, })
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = os.path.join(directory, template) if os.path.exists(template_file): with open(template_file) as f: template_contents = f.read() else: template_contents = '' templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': template_contents, 'order': index, }) kwargs.update({ 'name': template, 'templates': templates, }) return super(TemplateDetailView, self).get_context_data(**kwargs)
def get_context_data(self, **kwargs): tags = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for tag_name, tag_func in library.tags.items(): title, body, metadata = utils.parse_docstring( tag_func.__doc__) if title: title = utils.parse_rst(title, 'tag', _('tag:') + tag_name) if body: body = utils.parse_rst(body, 'tag', _('tag:') + tag_name) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], 'tag', _('tag:') + tag_name) tag_library = module_name.split('.')[-1] tags.append({ 'name': tag_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) kwargs.update({'tags': tags}) return super(TemplateTagIndexView, self).get_context_data(**kwargs)
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that admin and contenttypes apps are installed, as well as the auth context processor. """ if not apps.is_installed('django.contrib.admin'): raise ImproperlyConfigured( "Put 'django.contrib.admin' in your INSTALLED_APPS " "setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS " "setting in order to use the admin application.") try: default_template_engine = Engine.get_default() except ImproperlyConfigured: # Skip the check if the user has a non-trivial TEMPLATES setting pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors): raise ImproperlyConfigured( "Enable 'django.contrib.auth.context_processors.auth' " "in your TEMPLATES setting in order to use the admin " "application.")
def setUp(self): self.loader = eggs.Loader(Engine.get_default()) # Defined here b/c at module scope we may not have pkg_resources class MockProvider(pkg_resources.NullProvider): def __init__(self, module): pkg_resources.NullProvider.__init__(self, module) self.module = module def _has(self, path): return path in self.module._resources def _isdir(self, path): return False def get_resource_stream(self, manager, resource_name): return self.module._resources[resource_name] def _get(self, path): return self.module._resources[path].read() def _fn(self, base, resource_name): return os.path.normcase(resource_name) pkg_resources._provider_factories[MockLoader] = MockProvider self.empty_egg = create_egg("egg_empty", {}) self.egg_1 = create_egg( "egg_1", { os.path.normcase('templates/y.html'): StringIO("y"), os.path.normcase('templates/x.txt'): StringIO("x"), })
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that admin and contenttypes apps are installed, as well as the auth context processor. """ if not apps.is_installed('django.contrib.admin'): raise ImproperlyConfigured( "Put 'django.contrib.admin' in your INSTALLED_APPS " "setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS " "setting in order to use the admin application.") try: default_template_engine = Engine.get_default() except ImproperlyConfigured: # Skip the check if the user has a non-trivial TEMPLATES setting pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors): raise ImproperlyConfigured( "Enable 'django.contrib.auth.context_processors.auth' " "in your TEMPLATES setting in order to use the admin " "application.")
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that admin and contenttypes apps are installed, as well as the auth context processor. """ if not apps.is_installed('django.contrib.admin'): raise ImproperlyConfigured( "Put 'django.contrib.admin' in your INSTALLED_APPS " "setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS " "setting in order to use the admin application.") try: default_template_engine = Engine.get_default() except Exception: # Skip this non-critical check: # 1. if the user has a non-trivial TEMPLATES setting and Django # can't find a default template engine # 2. if anything goes wrong while loading template engines, in # order to avoid raising an exception from a confusing location # Catching ImproperlyConfigured suffices for 1. but 2. requires # catching all exceptions. pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors): raise ImproperlyConfigured( "Enable 'django.contrib.auth.context_processors.auth' " "in your TEMPLATES setting in order to use the admin " "application.")
def get_template_source(name, dirs=None): """Retrieves the template's source contents. :param name: Template's filename, as passed to the template loader. :param dirs: list of directories to optionally override the defaults. :return: tuple including file contents and file path. """ loaders = [] for loader in Engine.get_default().template_loaders: # The cached loader includes the actual loaders underneath if hasattr(loader, "loaders"): loaders.extend(loader.loaders) else: loaders.append(loader) for loader in loaders: for template_dir in loader.get_dirs(): try: filename = safe_join(template_dir, name) except SuspiciousFileOperation: # The joined path was located outside of this template_dir # (it might be inside another one, so this isn't fatal). continue try: with open(filename, encoding=loader.engine.file_charset) as fp: return fp.read() except FileNotFoundError: continue raise TemplateDoesNotExist(name)
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] for dir in Engine.get_default().dirs: template_file = os.path.join(dir, template) templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': lambda: open(template_file).read() if os.path.exists(template_file) else '', 'order': list(Engine.get_default().dirs).index(dir), }) kwargs.update({ 'name': template, 'templates': templates, }) return super(TemplateDetailView, self).get_context_data(**kwargs)
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that admin and contenttypes apps are installed, as well as the auth context processor. """ if not apps.is_installed('django.contrib.admin'): raise ImproperlyConfigured( "Put 'django.contrib.admin' in your INSTALLED_APPS " "setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS " "setting in order to use the admin application.") try: default_template_engine = Engine.get_default() except Exception: # Skip this non-critical check: # 1. if the user has a non-trivial TEMPLATES setting and Django # can't find a default template engine # 2. if anything goes wrong while loading template engines, in # order to avoid raising an exception from a confusing location # Catching ImproperlyConfigured suffices for 1. but 2. requires # catching all exceptions. pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors): raise ImproperlyConfigured( "Enable 'django.contrib.auth.context_processors.auth' " "in your TEMPLATES setting in order to use the admin " "application.")
def get_context_data(self, **kwargs): template = self.kwargs["template"] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) if template_file.exists(): template_contents = template_file.read_text() else: template_contents = "" templates.append({ "file": template_file, "exists": template_file.exists(), "contents": template_contents, "order": index, }) return super().get_context_data(**{ **kwargs, "name": template, "templates": templates, })
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that LogEntry, ContentType and the auth context processor are installed. 检查运行xadmin需要的包是否已经正确安装 默认情况下会检查 *ContentType* 模块是否已经正确安装 """ from django.contrib.contenttypes.models import ContentType if not ContentType._meta.installed: raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in " "your INSTALLED_APPS setting in order to use the admin application." ) default_template_engine = Engine.get_default() if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or 'django.core.context_processors.auth' in default_template_engine.context_processors): raise ImproperlyConfigured( "Put 'django.contrib.auth.context_processors.auth' " "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application." )
def template_source(request): """ Return the source of a template, syntax-highlighted by Pygments if it's available. """ template_origin_name = request.GET.get('template_origin', None) if template_origin_name is None: return HttpResponseBadRequest('"template_origin" key is required') try: template_origin_name = signing.loads(template_origin_name) except Exception: return HttpResponseBadRequest('"template_origin" is invalid') template_name = request.GET.get('template', template_origin_name) final_loaders = [] loaders = Engine.get_default().template_loaders for loader in loaders: if loader is not None: # When the loader has loaders associated with it, # append those loaders to the list. This occurs with # django.template.loaders.cached.Loader if hasattr(loader, 'loaders'): final_loaders += loader.loaders else: final_loaders.append(loader) for loader in final_loaders: if Origin: # django>=1.9 origin = Origin(template_origin_name) try: source = loader.get_contents(origin) break except TemplateDoesNotExist: pass else: # django<1.9 try: source, _ = loader.load_template_source(template_name) break except TemplateDoesNotExist: pass else: source = "Template Does Not Exist: %s" % (template_origin_name,) try: from pygments import highlight from pygments.lexers import HtmlDjangoLexer from pygments.formatters import HtmlFormatter source = highlight(source, HtmlDjangoLexer(), HtmlFormatter()) source = mark_safe(source) source.pygmentized = True except ImportError: pass # Using SimpleTemplateResponse avoids running global context processors. return SimpleTemplateResponse('debug_toolbar/panels/template_source.html', { 'source': source, 'template_name': template_name })
def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES secure aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [("", lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) if title: title = utils.parse_rst(title, "filter", _("filter:") + filter_name) if body: body = utils.parse_rst(body, "filter", _("filter:") + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], "filter", _("filter:") + filter_name) tag_library = module_name.split(".")[-1] filters.append( {"name": filter_name, "title": title, "body": body, "meta": metadata, "library": tag_library} ) kwargs.update({"filters": filters}) return super(TemplateFilterIndexView, self).get_context_data(**kwargs)
def _handler(self, request, *args, **kwargs): # Rethinking of this logic in 5 years, aka, working around RequestContext that doesn't seem to actually work context = {} for processor in Engine.get_default().context_processors: context.update(import_string(processor)(self.request)) if context['page'] and context['exact_match']: if context['page'].redirect_url: if context['page'].redirect_permanent: return HttpResponsePermanentRedirect( context['page'].redirect_url) else: return HttpResponseRedirect(context['page'].redirect_url) if context['page'].view: if context['page'].view.find('.as_view(') != -1: pass else: cls = get_callable(context['page'].view) return cls(request) if context['page'].template: self.template_name = context['page'].template elif context['page'].inherit_template: for i in context['pageA']: if i.template: self.template_name = i.template content = loader.render_to_string(self.template_name, context) return HttpResponse(content) raise Http404
def get_template_loader(cls): if not cls.template_loader: from django.template.loaders.filesystem import Loader from django.template.engine import Engine default_template_engine = Engine.get_default() cls.template_loader = Loader(default_template_engine) return cls.template_loader
def render_to_response(self, context, **response_kwargs): if self.template_string: context = RequestContext(request=self.request, dict_=context) engine = Engine.get_default() template = engine.from_string(self.template_string) return HttpResponse(template.render(context)) else: return super().render_to_response(context, **response_kwargs)
def render_to_response(self, context, **response_kwargs): if self.template_string: context = RequestContext(request=self.request, dict_=context) engine = Engine.get_default() template = engine.from_string(self.template_string) return HttpResponse(template.render(context)) else: return super(ClassDetail, self).render_to_response(context, **response_kwargs)
def sample_template(): template_string = """ {% load djpt_limits %} {% djptlimit 'TimeLimit' total=3 %} {{ slow_rendering }} {% enddjptlimit %} """ return Engine.get_default().from_string(template_string)
def get_bricks_context(self): request = self.request context = make_context({}, request) for processor in Engine.get_default().template_context_processors: context.update(processor(request)) return context
def template_source(request): """ Return the source of a template, syntax-highlighted by Pygments if it's available. """ template_origin_name = request.GET.get('template_origin', None) if template_origin_name is None: return HttpResponseBadRequest('"template_origin" key is required') template_name = request.GET.get('template', template_origin_name) final_loaders = [] loaders = Engine.get_default().template_loaders for loader in loaders: if loader is not None: # When the loader has loaders associated with it, # append those loaders to the list. This occurs with # django.template.loaders.cached.Loader if hasattr(loader, 'loaders'): final_loaders += loader.loaders else: final_loaders.append(loader) for loader in final_loaders: if Origin: # django>=1.9 origin = Origin(template_origin_name) try: source = loader.get_contents(origin) break except TemplateDoesNotExist: pass else: # django<1.9 try: source, _ = loader.load_template_source(template_name) break except TemplateDoesNotExist: pass else: source = "Template Does Not Exist: %s" % (template_origin_name, ) try: from pygments import highlight from pygments.lexers import HtmlDjangoLexer from pygments.formatters import HtmlFormatter source = highlight(source, HtmlDjangoLexer(), HtmlFormatter()) source = mark_safe(source) source.pygmentized = True except ImportError: pass # Using SimpleTemplateResponse avoids running global context processors. return SimpleTemplateResponse('debug_toolbar/panels/template_source.html', { 'source': source, 'template_name': template_name })
def template_source(request): """ Return the source of a template, syntax-highlighted by Pygments if it's available. """ template_origin_name = request.GET.get("template_origin") if template_origin_name is None: return HttpResponseBadRequest('"template_origin" key is required') try: template_origin_name = signing.loads(template_origin_name) except Exception: return HttpResponseBadRequest('"template_origin" is invalid') template_name = request.GET.get("template", template_origin_name) final_loaders = [] loaders = Engine.get_default().template_loaders for loader in loaders: if loader is not None: # When the loader has loaders associated with it, # append those loaders to the list. This occurs with # django.template.loaders.cached.Loader if hasattr(loader, "loaders"): final_loaders += loader.loaders else: final_loaders.append(loader) for loader in final_loaders: origin = Origin(template_origin_name) try: source = loader.get_contents(origin) break except TemplateDoesNotExist: pass else: source = "Template Does Not Exist: {}".format(template_origin_name) try: from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import HtmlDjangoLexer source = highlight(source, HtmlDjangoLexer(), HtmlFormatter()) source = mark_safe(source) source.pygmentized = True except ImportError: pass content = render_to_string( "debug_toolbar/panels/template_source.html", { "source": source, "template_name": template_name }, ) return JsonResponse({"content": content})
def __init__(self, forms_dir='forms', engine=None): if engine is None: engine = Engine.get_default() self._engine = engine self._forms_dirs = get_app_template_dirs(forms_dir) self._forms_loader = Loader(self) self.use_form_tags = False self.context_processors = self._engine.context_processors + ['template_forms.posted_answers']
def __init__(self, loaders): self.template_cache = {} self._loaders = loaders self._cached_loaders = [] try: from django.template.loader import find_template_loader as _find_template_loader except: _find_template_loader = Engine.get_default().find_template_loader self._find_template_loader = _find_template_loader
def __init__(self, engine, loaders): self.template_cache = {} self._loaders = loaders self._cached_loaders = [] try: from django.template.loader import find_template_loader as _find_template_loader except: _find_template_loader = Engine.get_default().find_template_loader self._find_template_loader = _find_template_loader
def build_context(request, **kwargs): context = make_context({}, request) for processor in Engine.get_default().template_context_processors: context.update(processor(request)) context.update( kwargs) # Updated _after_ processors in order to avoid shadowing return context.flatten()
def __init__(self): if has_engine: super(Loader, self).__init__(Engine.get_default()) else: super(Loader, self).__init__() include_pattern = getattr(settings, 'JINGO_INCLUDE_PATTERN', None) if include_pattern: self.include_re = re.compile(include_pattern) else: self.include_re = None
def __init__(self, *args, **kwargs): engine = kwargs.get('engine', None) if engine is None: kwargs['engine'] = engine = Engine.get_default() # Parse this template with special tags engine.use_form_tags = True Template.__init__(self, *args, **kwargs) engine.use_form_tags = False self._enumerate_form_nodes()
def get_template_loaders(self): """Some loaders have nested loaders that are what we actually use.""" if Engine is None: loader = Loader() return getattr(loader, 'loaders', [loader]) engine = Engine.get_default() loaders = [] for loader in engine.template_loaders: loaders += getattr(loader, 'loaders', [loader]) return loaders
def __init__(self, *args, **kwargs): engine = kwargs.get('engine', None) if engine is None: kwargs['engine'] = engine = Engine.get_default() # Parse this template with special tags engine.use_form_tags = True Template.__init__(self, *args, **kwargs) engine.use_form_tags = False self._enumerate_form_nodes()
def get_template_loaders(self): """Some loaders have nested loaders that are what we actually use.""" if Engine is None: loader = Loader() return getattr(loader, 'loaders', [loader]) engine = Engine.get_default() loaders = [] for loader in engine.template_loaders: loaders += getattr(loader, 'loaders', [loader]) return loaders
def raise_or_not_variable_does_not_exist_compat_version(context): """This function raise exception if template is in debug mode. If not, it return ''. Multiples ways (depending to the Django version) to retrieve the value of template debug. :param context: context for the field. :return: Either '' or raise Exception """ if django.VERSION < (1, 8): if settings.TEMPLATE_DEBUG: Exception('') else: return '' if django.VERSION >= (1, 8) and django.VERSION < (1, 10): from django.template.engine import Engine template_debug_value = getattr(settings, 'TEMPLATE_DEBUG', None) if template_debug_value: raise Exception('') if not template_debug_value: return '' if template_debug_value is None: try: engine = context.template.engine except AttributeError: engine = Engine.get_default() if engine.debug: raise Exception() return '' if django.VERSION >= (1, 10): from django.template.engine import Engine try: engine = context.template.engine except AttributeError: engine = Engine.get_default() if engine.debug: raise Exception() return '' raise Exception()
def raise_or_not_variable_does_not_exist_compat_version(context): """This function raise exception if template is in debug mode. If not, it return ''. Multiples ways (depending to the Django version) to retrieve the value of template debug. :param context: context for the field. :return: Either '' or raise Exception """ if django.VERSION < (1, 8): if settings.TEMPLATE_DEBUG: raise else: return '' if django.VERSION >= (1, 8) and django.VERSION < (1, 10): from django.template.engine import Engine template_debug_value = getattr(settings, 'TEMPLATE_DEBUG', None) if template_debug_value: raise if not template_debug_value: return '' if template_debug_value is None: try: engine = context.template.engine except AttributeError: engine = Engine.get_default() if engine.debug: raise return '' if django.VERSION >= (1, 10): from django.template.engine import Engine try: engine = context.template.engine except AttributeError: engine = Engine.get_default() if engine.debug: raise return '' raise
def __init__(self, forms_dir='forms', engine=None): if engine is None: engine = Engine.get_default() self._engine = engine self._forms_dirs = get_app_template_dirs(forms_dir) self._forms_loader = Loader(self) self.use_form_tags = False self.context_processors = self._engine.context_processors + [ 'template_forms.posted_answers' ]
def get_template_context_processors(): """Compatibility method to fetch the template context processors.""" if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: context_processors = [] else: context_processors = engine.template_context_processors else: # Django < 1.8 context_processors = get_standard_processors() return context_processors
def get_template_dirs(): """Compatibility method to fetch the template directories.""" if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: template_dirs = [] else: template_dirs = engine.dirs else: # Django < 1.8 template_dirs = settings.TEMPLATE_DIRS return template_dirs
def get_template_context_processors(): """Compatibility method to fetch the template context processors.""" if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: context_processors = [] else: context_processors = engine.template_context_processors else: # Django < 1.8 context_processors = get_standard_processors() return context_processors
def get_template_loaders(): """Compatibility method to fetch the template loaders.""" if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: loaders = [] else: loaders = engine.template_loaders else: # Django < 1.8 loaders = [find_template_loader(loader_name) for loader_name in settings.TEMPLATE_LOADERS] return loaders
def get_template_dirs(): """Compatibility method to fetch the template directories.""" if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: template_dirs = [] else: template_dirs = engine.dirs else: # Django < 1.8 template_dirs = settings.TEMPLATE_DIRS return template_dirs
def get_template_loaders(): """Compatibility method to fetch the template loaders.""" if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: loaders = [] else: loaders = engine.template_loaders else: # Django < 1.8 loaders = [find_template_loader(loader_name) for loader_name in settings.TEMPLATE_LOADERS] return loaders
def __init__(self, app_path, template_subdir='templates'): '''Creates a renderer to the given path (relateive to the project root where settings.STATIC_ROOT points to)''' project_path = os.path.normpath(settings.BASE_DIR) self.app_path = app_path template_dir = get_app_template_dir(app_path, template_subdir) # raises ImproperlyConfigured if error self.template_search_dirs = [ template_dir ] if get_setting('TEMPLATES_DIRS', False): self.template_search_dirs.extend(get_setting('TEMPLATES_DIRS')) self.template_search_dirs.append(settings.BASE_DIR) self.cache_root = os.path.abspath(os.path.join(project_path, app_path, get_setting('TEMPLATES_CACHE_DIR'), template_subdir)) self.tlookup = TemplateLookup(directories=self.template_search_dirs, imports=get_setting('DEFAULT_TEMPLATE_IMPORTS'), module_directory=self.cache_root, collection_size=2000, filesystem_checks=settings.DEBUG, input_encoding=get_setting('DEFAULT_TEMPLATE_ENCODING', 'utf-8')) # Use the default django engine (to get the list of context processors) self.engine = Engine.get_default()
def get_context_processors(): """Get context processors in a way that works for Django 1.7 and 1.8+""" try: # 1.7 from django.template.context import get_standard_processors return get_standard_processors() except ImportError: # 1.8+ try: from django.template.engine import Engine engine = Engine.get_default() except ImproperlyConfigured: return [] return engine.template_context_processors
def test_missing_template_is_cached(self): "#19949 -- Check that the missing template is cached." template_loader = Engine.get_default().template_loaders[0] # Empty cache, which may be filled from previous tests. template_loader.reset() # Check that 'missing.html' isn't already in cache before 'missing.html' is loaded self.assertRaises(KeyError, lambda: template_loader.template_cache["missing.html"]) # Try to load it, it should fail self.assertRaises(TemplateDoesNotExist, template_loader.load_template, "missing.html") # Verify that the fact that the missing template, which hasn't been found, has actually # been cached: self.assertEqual(template_loader.template_cache.get("missing.html"), TemplateDoesNotExist, "Cached template loader doesn't cache file lookup misses. It should.")
def _base_detail(request, instance, template_name='detail.html', item_name="char_1", template_string='',): context = {} context['instance'] = instance context['instance_class'] = instance.__class__() context['item_name'] = item_name if hasattr(request, 'toolbar'): request.toolbar.set_object(instance) if template_string: context = RequestContext(request=request, dict_=context) engine = Engine.get_default() template = engine.from_string(template_string) return HttpResponse(template.render(context)) else: return render(request, template_name, context)
def inner(self): loader = Engine.get_default().template_loaders[0] func(self) func(self) loader.reset() with override_settings(TEMPLATE_STRING_IF_INVALID='INVALID'): func(self) func(self) loader.reset() with override_settings(TEMPLATE_DEBUG=True): func(self) func(self) loader.reset()
def update_template_debug(debug=True): """ Helper method for updating the template debug option based on the django version. Use the results of this function as the context. :return: SettingsOverride object """ # Create our overridden template settings with debug turned off. templates_override = settings.TEMPLATES templates_override[0]['OPTIONS'].update({'debug': debug}) # Engine gets created based on template settings initial value so # changing the settings after the fact won't update, so do it # manually. Necessary when testing validate_context # with render method and want debug off. Engine.get_default().debug = debug return SettingsOverride(TEMPLATES=templates_override)
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that admin and contenttypes apps are installed, as well as the auth context processor. """ if not apps.is_installed('django.contrib.admin'): raise ImproperlyConfigured("Put 'django.contrib.admin' in " "your INSTALLED_APPS setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in " "your INSTALLED_APPS setting in order to use the admin application.") if 'django.contrib.auth.context_processors.auth' not in Engine.get_default().context_processors: raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' " "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
def _render_content(content, **kwargs): # Track current render level and abort if we nest too deep. Avoids # crashing in recursive page contents (eg. a page list that contains # itself or similar). request = kwargs.get("request") if request is not None: level = getattr(request, "feincms_render_level", 0) if level > 10: logging.getLogger("feincms").error( "Refusing to render %r, render level is already %s" % (content, level) ) return setattr(request, "feincms_render_level", level + 1) r = content.render(**kwargs) if isinstance(r, (list, tuple)): # Modeled after feincms3's TemplatePluginRenderer context = kwargs["context"] plugin_template, plugin_context = r if not hasattr(plugin_template, "render"): # Quacks like a template? try: engine = context.template.engine except AttributeError: # This fails hard in Django 1.7 (ImportError). So what. This # just means that this particular feature isn't available # there. from django.template.engine import Engine engine = Engine.get_default() if isinstance(plugin_template, (list, tuple)): plugin_template = engine.select_template(plugin_template) else: plugin_template = engine.get_template(plugin_template) with context.push(plugin_context): return plugin_template.render(context) if request is not None: level = getattr(request, "feincms_render_level", 1) setattr(request, "feincms_render_level", max(level - 1, 0)) return r
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that LogEntry, ContentType and the auth context processor are installed. """ from django.contrib.contenttypes.models import ContentType if not ContentType._meta.installed: raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in " "your INSTALLED_APPS setting in order to use the admin application.") default_template_engine = Engine.get_default() if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or 'django.core.context_processors.auth' in default_template_engine.context_processors): raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' " "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")