def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c))
def test_recursive_multiple_loaders(self): engine = Engine( dirs=[os.path.join(RECURSIVE, 'fs')], loaders=[('django.template.loaders.locmem.Loader', { 'one.html': ('{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}' ), 'two.html': ('{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}' ), 'three.html': ('{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}' ), }), 'django.template.loaders.filesystem.Loader'], ) template = engine.get_template('one.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three locmem-three two locmem-two one locmem-one')
def install_project(self): self.info('开始安装DeerU') self.info('下载DeerU ...') s = '' if os.path.exists(self.name): # self.info('已存在相同目录 "%s" ,请选择: d(删除已存在目录); s(跳过下载) ' % self.name) s = input('已存在相同目录 "%s" ,请选择: d(删除已存在目录); s(跳过下载): ' % self.name) if s == 'd': shutil.rmtree(self.name) elif s == 's': pass else: raise CommandError('输入错误') if s != 's': result = subprocess.run( 'git clone -b %s %s %s' % (self.branch, self.DEERU_GIT_URL, self.name), shell=True) if result.returncode != 0: raise CommandError('\n下载DeerU失败') self.info('安装依赖...') result = subprocess.run('pip install -r requirements.txt', cwd=self.name, shell=True) if result.returncode != 0: raise CommandError('\n安装依赖失败') self.info('复制必要文件...') context = Context({'SECRET_KEY': get_random_secret_key()}, autoescape=False) for template_name, new_file in self.get_project_templates(): template = Engine().from_string( self.get_template_str(template_name)) content = template.render(context) new_file.write_text(content) self.success('\n安装完成 !!')
def test_include_cache(self): """ {% include %} keeps resolved templates constant (#27974). The CounterNode object in the {% counter %} template tag is created once if caching works properly. Each iteration increases the counter instead of restarting it. This works as a regression test only if the cached loader isn't used, so the @setup decorator isn't used. """ engine = Engine(loaders=[ ('django.template.loaders.locmem.Loader', { 'template': '{% for x in vars %}{% include "include" %}{% endfor %}', 'include': '{% include "next" %}', 'next': '{% load custom %}{% counter %}' }), ], libraries={'custom': 'template_tests.templatetags.custom'}) output = engine.render_to_string('template', {'vars': range(9)}) self.assertEqual(output, '012345678')
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, str): exception_repr = message context = { 'request_path': quote(request.path), 'exception': exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: if template_name != ERROR_404_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise # Render template (even though there are no substitutions) to allow # inspecting the context in tests. template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return HttpResponseNotFound(body, content_type=content_type)
def test_include_recursive(self): comments = [ { 'comment': 'A1', 'children': [ {'comment': 'B1', 'children': []}, {'comment': 'B2', 'children': []}, {'comment': 'B3', 'children': [ {'comment': 'C1', 'children': []} ]}, ] } ] engine = Engine(app_dirs=True) t = engine.get_template('recursive_include.html') self.assertEqual( "Recursion! A1 Recursion! B1 B2 B3 Recursion! C1", t.render(Context({'comments': comments})).replace(' ', '').replace('\n', ' ').strip(), )
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): # print("hello") """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: if template_name != ERROR_404_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise template = Engine().from_string( '<h1>Custom 404 page</h1>' '<p>The requested something {{ request_path }} was not found on the server.</p>' ) body = template.render(Context(context)) content_type = 'text/text' return http.HttpResponseNotFound(body, content_type=content_type)
def directory_index(path, fullpath): try: t = loader.select_template( ["static/directory_index.html", "static/directory_index"]) except TemplateDoesNotExist: t = Engine(libraries={ "i18n": "django.templatetags.i18n" }).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) c = Context() else: c = {} files = [] for f in fullpath.iterdir(): if not f.name.startswith("."): url = str(f.relative_to(fullpath)) if f.is_dir(): url += "/" files.append(url) c.update({"directory": path + "/", "file_list": files}) return HttpResponse(t.render(c))
def obtenerInformacion(listaFichero): #Cargamos el fichero Template textoTemplate = cargarFicheroTexto(path+"template.html") #Creamos el objeto template para nuestro texto template = Engine().from_string(textoTemplate) datosFinal=Context() array=[] for nombreFichero in listaFichero: datosTemplate=Context() textoEntrada=cargarFicheroTexto(path+nombreFichero) buscarPatrones(textoEntrada,datosTemplate) datosTemplate["nameFile"]=nombreFichero.replace("_","").replace(".txt","") array.append(datosTemplate) datosFinal['Ficheros'] = array renderizarPlantilla(template,datosFinal,path + "index.html")
def test_extends_include_missing_cachedloader(self): """ Test the cache loader separately since it overrides load_template. """ engine = Engine(debug=True, loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.app_directories.Loader', ]), ]) template = engine.get_template('test_extends_error.html') with self.assertRaises(TemplateDoesNotExist) as e: template.render(Context()) self.assertEqual(e.exception.args[0], 'missing.html') # Repeat to ensure it still works when loading from the cache template = engine.get_template('test_extends_error.html') with self.assertRaises(TemplateDoesNotExist) as e: template.render(Context()) self.assertEqual(e.exception.args[0], 'missing.html')
def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[ ( "django.template.loaders.locmem.Loader", { "child": '{{ var|default:"none" }}', }, ), ]) request = self.request_factory.get("/") ctx = RequestContext(request, {"var": "parent"}) self.assertEqual( engine.from_string('{% include "child" %}').render(ctx), "parent") self.assertEqual( engine.from_string('{% include "child" only %}').render(ctx), "none")
def test_block_override_in_extended_included_template(self): """ ExtendsNode.find_template() initializes history with self.origin (#28071). """ engine = Engine( loaders=[ ['django.template.loaders.locmem.Loader', { 'base.html': "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}", 'included.html': "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}", }], ['django.template.loaders.locmem.Loader', { 'base.html': "{% block base %}1{% endblock %}{% include 'included.html' %}", 'included.html': "{% block included %}A{% endblock %}", }], ], ) template = engine.get_template('base.html') self.assertEqual(template.render(Context({})), '12AB')
def get_engine(config): engine = Engine( dirs=[ os.path.join(local_root, 'templates/').replace('\\', '/'), os.path.join(settings.BASE_DIR, local_root, config.tenant + '/templates/').replace('\\', '/'), ], libraries={ # 'relative_path': 'merge.relative_path', 'mathfilters': 'merge.templatetags.mathfilters', }, ## add options for relative path names ## add options for maths ) # dirs = [ # os.path.join(local_root, 'templates/').replace('\\', '/'), # os.path.join(settings.BASE_DIR, local_root,config.tenant+'/templates/').replace('\\', '/'),] # print("template dirs:", dirs) return engine
def test_correct_exception_index(self): tests = [ ( "{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}", (38, 56), ), ( "{% load bad_tag %}{% for i in range %}{% for j in range %}" "{% badsimpletag %}{% endfor %}{% endfor %}", (58, 76), ), ( "{% load bad_tag %}{% for i in range %}{% badsimpletag %}" "{% for j in range %}Hello{% endfor %}{% endfor %}", (38, 56), ), ( "{% load bad_tag %}{% for i in range %}{% for j in five %}" "{% badsimpletag %}{% endfor %}{% endfor %}", (38, 57), ), ( "{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}", (18, 37), ), ] context = Context({ "range": range(5), "five": 5, }) engine = Engine( debug=True, libraries={"bad_tag": "template_tests.templatetags.bad_tag"}) for source, expected_error_source_index in tests: template = engine.from_string(source) try: template.render(context) except (RuntimeError, TypeError) as e: debug = e.template_debug self.assertEqual((debug["start"], debug["end"]), expected_error_source_index)
def test_unique_history_per_loader(self): """ Extending should continue even if two loaders return the same name for a template. """ engine = Engine(loaders=[ [ 'django.template.loaders.locmem.Loader', { 'base.html': '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}', } ], [ 'django.template.loaders.locmem.Loader', { 'base.html': '{% block content %}loader2{% endblock %}', } ], ]) template = engine.get_template('base.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'loader2 loader1')
def test_extends_include_missing_cachedloader(self): engine = Engine( debug=True, loaders=[ ( "django.template.loaders.cached.Loader", [ "django.template.loaders.app_directories.Loader", ], ), ], ) template = engine.get_template("test_extends_error.html") with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"): template.render(Context()) # Repeat to ensure it still works when loading from the cache template = engine.get_template("test_extends_error.html") with self.assertRaisesMessage(TemplateDoesNotExist, "missing.html"): template.render(Context())
def process_response(self, request, response): if not app_settings.EMULATE: return response try: val = smart_unicode(response.content) except Exception: return response toolbar = Engine(debug=True).from_string(self.TEMPLATE).render( Context({ 'request': request, 'app_settings': app_settings, })) idx = val.lower().rfind(self.TAG.lower()) if idx >= 0: response.content = val[:idx] + toolbar + val[idx + len(self.TAG):] return response
def generate_widget_js(lang): code = [] with language(lang): # Provide isolation code.append('(function (siteglobals) {\n') code.append('var module = {}, exports = {};\n') code.append('var lang = "%s";\n' % lang) catalog, plural = get_javascript_catalog(lang, 'djangojs', ['pretix']) catalog = dict( (k, v) for k, v in catalog.items() if k.startswith('widget\u0004')) template = Engine().from_string(js_catalog_template) context = Context({ 'catalog_str': indent(json.dumps(catalog, sort_keys=True, indent=2)) if catalog else None, 'formats_str': indent(json.dumps(get_formats(), sort_keys=True, indent=2)), 'plural': plural, }) code.append(template.render(context)) files = [ 'vuejs/vue.js' if settings.DEBUG else 'vuejs/vue.min.js', 'pretixpresale/js/widget/docready.js', 'pretixpresale/js/widget/floatformat.js', 'pretixpresale/js/widget/widget.js', ] for fname in files: f = finders.find(fname) with open(f, 'r') as fp: code.append(fp.read()) if settings.DEBUG: code.append('})(this);\n') else: # Do not expose debugging variables code.append('})({});\n') return ''.join(code)
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, str): exception_repr = message context = { 'request_path': quote(request.path), 'exception': exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use 'text/html'. except TemplateDoesNotExist as e: logger.exception(e) if template_name != ERROR_404_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise # Render template (even though there are no substitutions) to allow # inspecting the context in tests. template = Engine().from_string( ERROR_PAGE_TEMPLATE % { 'title': 'Not Found', 'details': 'The requested resource was not found on this server.', }, ) body = template.render(Context(context)) content_type = 'text/html' except Exception as e: logger.exception(e) body = "" content_type = 'text/html' return HttpResponseNotFound(body, content_type=content_type)
def create_site(name, directory=SITE_DIR, templates_dir=TEMPLATES_DIR, static_dir=RESOURCES_DIR): if not directory: sys.stderr.write( "Please provide a site name, e.g. %s <site_name>\n\n" % NAME) sys.exit(1) sys.stdout.write("\tCopying site templates to %s\n" % directory) # Generate manage.py from django.template import Engine, Context engine = Engine() f = open(os.path.join(os.path.dirname(templates_dir), 'manage.txt')) template = engine.from_string(f.read()) f.close() managepy_file_contents = template.render(Context({'site_name': name})) managepy_file = open(os.path.join(BASE_DIR, 'manage.py'), 'w+') managepy_file.write(managepy_file_contents) managepy_file.close() os.chmod(os.path.join(BASE_DIR, 'manage.py'), 0755) # copy template framework into site directory shutil.copytree("%s/" % templates_dir, directory, ignore=shutil.ignore_patterns('.svn')) site_resources = "%s/%s" % (static_dir, name) # make static dirs for static_dir in STATIC_DIRS: try: os.makedirs("%s/%s" % (site_resources, static_dir)) sys.stdout.write("\tCreated %s in %s\n" % (static_dir, site_resources)) except: pass
def page_not_found(request, template_name='404.html'): context = { 'request_path': request.path, 'error': { 'title': _('Page not found'), 'message': _("We tried but couldn't find this page, sorry."), }, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {% raw %}{{ request_path }}{% endraw %} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return HttpResponseNotFound(body, content_type=content_type)
def page_not_found(request, template_name='404.html'): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ context = {'request_path': request.path} try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>' ) body = template.render(Context(context)) content_type = 'text/html' return http.HttpResponseNotFound(body, content_type=content_type)
def send_templated_email(template_name, context, recipient_list, from_email=settings.DEFAULT_FROM_EMAIL, attachment_filename=None, attachment_data=None): """ Sends an email using a template stored in the database (based on the template name) Also supports attaching a file """ # Get template from database, render it using the provided context template_engine = Engine() email_template = EmailTemplate.objects.get(name=template_name) subject_template = template_engine.from_string(email_template.subject) body_template = template_engine.from_string(email_template.body) email_context = Context(context) email_subject = subject_template.render(email_context) email_body = body_template.render(email_context) email_body_full = render_to_string( 'emails/default.html', context={'rendered_email_body': email_body}) # Send the email text_message = strip_tags(email_body_full) email = EmailMultiAlternatives( to=recipient_list, from_email=from_email, subject=email_subject, body=text_message, ) email.attach_alternative(email_body_full, "text/html") # Attachment? if attachment_filename: if attachment_data: email.attach(attachment_filename, attachment_data) else: email.attach_file(attachment_filename) elif attachment_data: email.attach('attachment', attachment_data) email.send()
def directory_index(path, fullpath): try: t = loader.select_template( ["static/directory_index.html", "static/directory_index",] ) except TemplateDoesNotExist: t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string( DEFAULT_DIRECTORY_INDEX_TEMPLATE ) c = Context() else: c = {} files = [] for f in os.listdir(fullpath): if not f.startswith("."): if os.path.isdir(os.path.join(fullpath, f)): f += "/" files.append(f) c.update( {"directory": path + "/", "file_list": files,} ) return HttpResponse(t.render(c))
def page_not_found(request, exception, template_name='404.html'): exception_repr = '' try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, six.text_type): exception_repr = t_(message, request) settings.request_thread_safe = threading.local() settings.request_thread_safe.request = request try : request.ua.status_code = 404 request.ua.save() except Exception : pass if request.META.get('HTTP_AJAX') == 'true' : content_dict = { 'status': 'error', 'content': exception_repr or t_('找不到页面', request), } return http.HttpResponse(json.dumps(content_dict), content_type="application/json") context = { 'request_path': request.path, 'exception': exception_repr, 'request': request, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None except TemplateDoesNotExist: template = Engine().from_string('<h1>Not Found</h1><p>The requested URL' ' {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return http.HttpResponseNotFound(body, content_type=content_type)
def test_extend_cached(self): engine = Engine( dirs=[ os.path.join(RECURSIVE, "fs"), os.path.join(RECURSIVE, "fs2"), os.path.join(RECURSIVE, "fs3"), ], loaders=[ ( "django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", ], ), ], ) template = engine.get_template("recursive.html") output = template.render(Context({})) self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs/recursive") cache = engine.template_loaders[0].get_template_cache self.assertEqual(len(cache), 3) expected_path = os.path.join("fs", "recursive.html") self.assertTrue( cache["recursive.html"].origin.name.endswith(expected_path)) # Render another path that uses the same templates from the cache template = engine.get_template("other-recursive.html") output = template.render(Context({})) self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs/recursive") # Template objects should not be duplicated. self.assertEqual(len(cache), 4) expected_path = os.path.join("fs", "other-recursive.html") self.assertTrue( cache["other-recursive.html"].origin.name.endswith(expected_path))
def render(modules_set, apis_set, file_path): """ Render the text message to the urls.py file """ if not apis_set: return api_text = ' ' + apis_set[0] for api in apis_set[1:]: api_text = f'{api_text},\n {api}' api_text = f'[\n{api_text}\n]' module_text = modules_set[0] for module in modules_set[1:]: module_text = f'{module_text}\n{module}' context = Context( { 'import_module': module_text, 'routes_info': api_text, 'version': arkfbp.get_version(), 'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime( time.time())), }, autoescape=False) old_path = path.join(arkfbp.common.django.__path__[0], 'conf', 'route_template', 'urls_name.py-tpl') with open(old_path, 'r', encoding='utf-8') as template_file: content = template_file.read() template = Engine().from_string(content) content = template.render(context) with open(file_path, 'w+', encoding='utf-8') as new_file: new_file.write(content)
def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) c = Context() else: c = {} files = [] for f in fullpath.iterdir(): if not f.name.startswith('.'): url = str(f.relative_to(fullpath)) if f.is_dir(): url += '/' files.append(url) c.update({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c))
def page_not_found(request, exception, template_name="404.html"): context = { "request_path": request.path, "error": { "title": _("Page not found"), "message": _("We tried but couldn't find this page, sorry."), }, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None except TemplateDoesNotExist: template = Engine().from_string( "<h1>Not Found</h1>" "<p>The requested URL {% raw %}{{ request_path }}{% endraw %} was not found on this server.</p>" ) body = template.render(Context(context)) content_type = "text/html" return HttpResponseNotFound(body, content_type=content_type)
def test_template(self): # Templates can be created from unicode strings. engine = Engine() t1 = engine.from_string('ŠĐĆŽćžšđ {{ var }}') # Templates can also be created from bytestrings. These are assumed to # be encoded using UTF-8. s = b'\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}' t2 = engine.from_string(s) with self.assertRaises(TemplateEncodingError): engine.from_string(b'\x80\xc5\xc0') # Contexts can be constructed from unicode or UTF-8 bytestrings. Context({b"var": b"foo"}) Context({"var": b"foo"}) c3 = Context({b"var": "Đđ"}) Context({"var": b"\xc4\x90\xc4\x91"}) # Since both templates and all four contexts represent the same thing, # they all render the same (and are returned as unicode objects and # "safe" objects as well, for auto-escaping purposes). self.assertEqual(t1.render(c3), t2.render(c3)) self.assertIsInstance(t1.render(c3), six.text_type) self.assertIsInstance(t1.render(c3), SafeData)