def handle(self, *args, **options): context = Context({ 'object_list': Registration.objects.all(), }) loader = Loader() template, _ = loader.load_template( 'willard/registration_list_table.html') filedata = template.render(context) bucket_name = 'assets.sunlightfoundation.com' connection = S3Connection(settings.MEDIASYNC.get('AWS_KEY'), settings.MEDIASYNC.get('AWS_SECRET')) headers = { "x-amz-acl": "public-read", "Content-Type": 'text/csv', } # calculate md5 digest of filedata checksum = hashlib.md5(filedata) hexdigest = checksum.hexdigest() b64digest = base64.b64encode(checksum.digest()) bucket = connection.get_bucket(bucket_name) key = Key(bucket) key.key = '/reporting/uploads/%s' % 'lobbyist_registrations.html' key.set_contents_from_string(filedata, headers=headers, md5=(hexdigest, b64digest)) print key.generate_url(60 * 60 * 24 * 8).split('?')[0].replace( 'https', 'http').replace('//', '/')
def write_override_diff(diff_filename='template_overrides.diff'): # Fetch latest version of each template override from database tos = TemplateOverride.objects.all().order_by('-version') newest_tos = {} for override in tos: if override.name not in newest_tos: newest_tos[override.name] = override print '%s (version %d)' % (override.name, override.version) # Fetch the template file in the working copy orig_templates = {} template_loader = Loader() for key in newest_tos: try: orig_templates[key] = template_loader.load_template_source(key) except: print 'Could not load original template %s' % key print 'Got %d overrides and %d original versions' % (len(newest_tos.keys()), len(orig_templates.keys())) # Compute diffs between original and overridden templates diff_filename = 'template_overrides.diff' file_out = open(diff_filename, 'w') for key in orig_templates: str1 = list([x.rstrip() for x in orig_templates[key][0].split('\n')]) str2 = list([x.rstrip() for x in newest_tos[key].content.split('\n')]) # print '\n'.join(str1) # print '\n'.join(str2) diff = difflib.unified_diff(str1, str2, key, key, lineterm='') for line in diff: file_out.write(line.encode('ascii', 'ignore') + '\n') file_out.close() print 'Wrote differences to %s' % diff_filename
def results(request): params = rewrite_params(request).copy() del params['_escaped_fragment_'] if not len(params): return HttpResponseNotFound() if not params.has_key('page'): params['page'] = 1 if not params.has_key('sorting'): params['sorting'] = '_score' query = {} for param in params: query[param] = urllib2.unquote(unicode(params[param])) search = SearchHandler().create(InjectRequest(query)) loader = Loader() items = pystache.render( loader.load_template_source('pages/search/items.html')[0], search['results'] ) facets = '' if search.has_key('facets') and search['facets'].has_key('company.facet'): facets = pystache.render( loader.load_template_source('pages/search/facets.html')[0], {'facets' : search['facets']['company.facet']} ) term = '' if (query.has_key('what') and len(query['what'])) and (query.has_key('where') and len(query['where'])): term = '%s / %s' % (query['what'].lower(), query['where'].lower()) elif query.has_key('what'): term = query['what'].lower() elif query.has_key('where'): term = query['where'].lower() total = 0 if len(search['results']): total = search['results']['total'] pagination = '' if len(search['results']) and len(search['results']['pagination']) > 1: pagination = pystache.render( loader.load_template_source('pages/search/pagination.html')[0], {'pagination' : search['results']['pagination'] } ) content = render_to_string('pages/search.html', { 'term': term, 'total': total, 'facets': facets, 'items': items, 'pagination': pagination }, context_instance=RequestContext(request)) return direct_to_template(request, 'base.html', { 'search': content, 'job_count': count_documents() })
def get_aliastemplate(): """Fetch template for displaying ifalias format as help to user""" templatepath = join(sysconfdir, "portadmin") templatename = "aliasformat.html" loader = Loader() rawdata, _ = loader.load_template_source(templatename, [templatepath]) tmpl = django.template.Template(rawdata) return tmpl
def raw_base_template(obj): """ Gets the base body template for an object. :param obj: A myblocks object with a valid base_template. :return: The base_template as a string. """ loader = Loader() return loader.load_template_source(obj.base_template)[0]
def upload_js(): """ return a jQuery Templates ref : http://api.jquery.com/category/plugins/templates/ """ path = os.path.join(settings.ROOT, 'templates/materials') loader = Loader() string, filename = loader.load_template_source('material_uploader_template.html', (path, )) return string
def handle(self, *args, **options): from django.conf import settings style = color_style() template_dirs = set(settings.TEMPLATE_DIRS) template_dirs |= set(options.get('includes', [])) template_dirs |= set( getattr( settings, 'VALIDATE_TEMPLATES_EXTRA_TEMPLATE_DIRS', [])) settings.TEMPLATE_DIRS = list(template_dirs) settings.TEMPLATE_DEBUG = True verbosity = int(options.get('verbosity', 1)) errors = 0 template_loader = Loader() # Replace built in template tags with our own validating versions if options.get('check_urls', False): add_to_builtins('django_extensions.utils.validatingtemplatetags') for template_dir in template_dirs: for root, dirs, filenames in os.walk(template_dir): for filename in filenames: if filename.endswith(".swp"): continue if filename.endswith("~"): continue filepath = os.path.join(root, filename) if verbosity > 1: print(filepath) validatingtemplatetags.before_new_template( options.get('force_new_urls', False)) try: template_loader.load_template(filename, [root]) except Exception as e: errors += 1 print( "%s: %s" % (filepath, style.ERROR( "%s %s" % (e.__class__.__name__, str(e))))) template_errors = validatingtemplatetags.get_template_errors() for origin, line, message in template_errors: errors += 1 print( "%s(%s): %s" % (origin, line, style.ERROR(message))) if errors and options.get('break', False): raise CommandError("Errors found") if errors: raise CommandError("%s errors found" % errors) print("%s errors found" % errors)
def raw_base_head(obj): """ Gets the base head template for an object if one exists. :param obj: A myblocks object. :return: If the object has a base_head attribute, a string containing the base_head template. Otherwise a blank string. """ if obj.base_head: loader = Loader() return loader.load_template_source(obj.base_head)[0] return ''
def library(cls, chart_id): if cls._library is None: loader = Loader(Engine()) for filename in loader.get_template_sources('chartkick.json'): if os.path.exists(filename): oprtions = Options() oprtions.load(filename) cls._library = oprtions break else: cls._library = Options() return cls._library.get(chart_id, {})
def library(cls, chart_id): if cls._library is None: loader = Loader() for filename in loader.get_template_sources('chartkick.json'): if os.path.exists(filename): oprtions = Options() oprtions.load(filename) cls._library = oprtions break else: cls._library = Options() return cls._library.get(chart_id, {})
def handle(self, *args, **options): from django.conf import settings style = color_style() template_dirs = set(settings.TEMPLATE_DIRS) template_dirs |= set(options.get('includes', [])) template_dirs |= set( getattr(settings, 'VALIDATE_TEMPLATES_EXTRA_TEMPLATE_DIRS', [])) settings.TEMPLATE_DIRS = list(template_dirs) settings.TEMPLATE_DEBUG = True verbosity = int(options.get('verbosity', 1)) errors = 0 template_loader = Loader() # Replace built in template tags with our own validating versions if options.get('check_urls', False): add_to_builtins('django_extensions.utils.validatingtemplatetags') for template_dir in template_dirs: for root, dirs, filenames in os.walk(template_dir): for filename in filenames: if filename.endswith(".swp"): continue if filename.endswith("~"): continue filepath = os.path.join(root, filename) if verbosity > 1: print(filepath) validatingtemplatetags.before_new_template( options.get('force_new_urls', False)) try: template_loader.load_template(filename, [root]) except Exception as e: errors += 1 print("%s: %s" % (filepath, style.ERROR("%s %s" % (e.__class__.__name__, str(e))))) template_errors = validatingtemplatetags.get_template_errors( ) for origin, line, message in template_errors: errors += 1 print("%s(%s): %s" % (origin, line, style.ERROR(message))) if errors and options.get('break', False): raise CommandError("Errors found") if errors: raise CommandError("%s errors found" % errors) print("%s errors found" % errors)
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 do_include_raw(parser, token): """ Performs a template include without parsing the context, just dumps the template in. Source: http://djangosnippets.org/snippets/1684/ """ bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError( "%r tag takes one argument: the name of the template " "to be included" % bits[0] ) template_name = bits[1] if template_name[0] in ('"', "'") and template_name[-1] == template_name[0]: template_name = template_name[1:-1] template_loader = Loader() source, path = template_loader.load_template_source(template_name) return template.TextNode(source)
def get_dependencies(self, path): """ Finds dependencies hierarchically based on the included files. """ template = path.replace(os.sep, "/") logger.debug("Loading template [%s] and preprocessing" % template) loader = Loader() contents, file_name = loader.load_template_source(template) if self.preprocessor: resource = self.site.content.resource_from_relative_path(template) if resource: contents = self.preprocessor(resource, contents) or contents parsed_template = Template(contents) extend_nodes = parsed_template.nodelist.get_nodes_by_type(ExtendsNode) tpls = [node.parent_name for node in extend_nodes] deps = [] for dep in tpls: deps.append(dep) if dep: deps.extend(self.get_dependencies(dep)) return list(set(deps))
def js_template(parser, token): """ Include js template """ bits = token.split_contents() if len(bits) != 3: raise TemplateSyntaxError, "%r tag takes two arguments: the name of the template to be included, the id of template" % bits[0] template_name = bits[1] if template_name[0] in ('"', "'") and template_name[-1] == template_name[0]: template_name = template_name[1:-1] template_id = bits[2] if template_id[0] in ('"', "'") and template_id[-1] == template_id[0]: template_id = template_id[1:-1] loader = Loader() source, path = loader.load_template_source(template_name) begin = "<script id=\"%sTpl\" type=\"text/template\">\n" % template_id end = "\n</script>" return template.TextNode(begin + source + end)
def write_override_diff(diff_filename='template_overrides.diff'): # Fetch latest version of each template override from database tos = TemplateOverride.objects.all().order_by('-version') newest_tos = {} for override in tos: if override.name not in newest_tos: newest_tos[override.name] = override print '%s (version %d)' % (override.name, override.version) # Fetch the template file in the working copy orig_templates = {} template_loader = Loader() for key in newest_tos: try: orig_templates[key] = template_loader.load_template_source(key) except: print 'Could not load original template %s' % key print 'Got %d overrides and %d original versions' % (len( newest_tos.keys()), len(orig_templates.keys())) # Compute diffs between original and overridden templates diff_filename = 'template_overrides.diff' file_out = open(diff_filename, 'w') for key in orig_templates: str1 = list([x.rstrip() for x in orig_templates[key][0].split('\n')]) str2 = list([x.rstrip() for x in newest_tos[key].content.split('\n')]) # print '\n'.join(str1) # print '\n'.join(str2) diff = difflib.unified_diff(str1, str2, key, key, lineterm='') for line in diff: file_out.write(line.encode('ascii', 'ignore') + '\n') file_out.close() print 'Wrote differences to %s' % diff_filename
def include_raw(parser, token): """ Performs a template include without parsing the context, just dumps the template in. """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[ 0] template_name = bits[1] if template_name[0] in ('"', "'") and template_name[-1] == template_name[0]: template_name = template_name[1:-1] source, path = Loader().load_template_source(template_name, None) return template.TextNode(source)
def load_template_source(self, template_name, template_dirs=None): if ":" not in template_name: raise TemplateDoesNotExist() app_name, template_name = template_name.split(":", 1) try: app = get_app(app_name) except ImproperlyConfigured: raise TemplateDoesNotExist() else: app_dir = path.dirname(app.__file__) app_templ_dir = path.join(app_dir, 'templates') if not path.isdir(app_templ_dir): raise TemplateDoesNotExist() return FileSystemLoader.load_template_source( self, template_name, template_dirs=[app_templ_dir])
def __init__(self, template, context=None): """ Set the initial value of the template to be parsed Allows for the template passed to be a string of a template name or a string that represents a template. """ self.template = template self.context = context #Contains the strings of all loaded classes self.loaded_classes = [] self.template_calls = [] self.tests = [] #Accept both template names and template strings try: self.template_string, self.filepath = Loader().load_template_source(template.name) except: self.template_string = template self.filepath = None
def load_template_source(self, template_name, template_dirs=None): if ":" not in template_name: raise TemplateDoesNotExist() app_name, template_name = template_name.split(":", 1) try: app = get_app(app_name) except ImproperlyConfigured: raise TemplateDoesNotExist() else: if path.basename(app.__file__).startswith('__init__'): # When "app.models" is a directory, app.__file__ will # be app/models/__init.py. app_dir = path.dirname(path.dirname(app.__file__)) else: app_dir = path.dirname(app.__file__) app_templ_dir = path.join(app_dir, 'templates') if not path.isdir(app_templ_dir): raise TemplateDoesNotExist() return FileSystemLoader.load_template_source( self, template_name, template_dirs=[app_templ_dir])
def render_include(context, path): __M_caller = context.caller_stack._push_frame() try: list = context.get('list', UNDEFINED) __M_writer = context.writer() from django.conf import settings from django.template.engine import Engine from django.template.loaders.filesystem import Loader from openedx.core.djangoapps.theming.helpers import get_current_theme dirs = settings.DEFAULT_TEMPLATE_ENGINE['DIRS'] theme = get_current_theme() if theme: dirs = list(dirs) dirs.insert(0, theme.path / 'templates') engine = Engine(dirs=dirs) source, template_path = Loader(engine).load_template_source(path) __M_writer(filters.decode.utf8(source)) return '' finally: context.caller_stack._pop_frame()
from django.template.loaders.filesystem import Loader from .base import ConditionalJinja2LoaderMixin class Loader(ConditionalJinja2LoaderMixin, Loader): pass _loader = Loader()
class TemplateParser(object): def __init__(self, template, context=None): """ Set the initial value of the template to be parsed Allows for the template passed to be a string of a template name or a string that represents a template. """ self.template = template self.context = context #Contains the strings of all loaded classes self.loaded_classes = [] self.template_calls = [] self.tests = [] #Accept both template names and template strings try: self.template_string, self.filepath = Loader().load_template_source(template.name) except: self.template_string = template self.filepath = None def parse(self): """ Parse the template tag calls out of the template. This is ugly because of having more than 1 tag on a line. Thus we have to loop over the file, splitting on the regex, then looping over the split, matching for our regex again. Improvements welcome! End result:: self.loaded_classes contains the load commands of classes loaded self.template_calls contains the template calls """ for line in self.template_string.split('\n'): split_line = tag_re.split(line) if len(split_line) > 1: for matched in split_line: mat = tag_re.search(matched) if mat: full_command = mat.group(0) cmd = mat.group(2).split()[0].strip() #get_comment_form etc if cmd == 'load': self.loaded_classes.append(full_command) else: if cmd not in DEFAULT_TAGS and cmd not in 'end'.join(DEFAULT_TAGS): self.template_calls.append(full_command) def create_tests(self): """ This yields a rendered template string to assert Equals against with the outputted template. """ for tag_string in self.template_calls: out_context = {} context_name = "" #Try and find anything in the string that's in the context context_name = '' bits = tag_string.split() for bit_num, bit in enumerate(bits): try: out_context[bit] = template.Variable(bit).resolve(self.context) except: pass if bit == 'as': context_name = bits[bit_num+1] if context_name: con_string = "{{ %s }}" % context_name else: con_string = "" template_string = "%s%s%s" % (''.join(self.loaded_classes), tag_string, con_string) try: template_obj = template.Template(template_string) rendered_string = template_obj.render(template.Context(out_context)) except Exception, e: print "EXCEPTION: %s" % e.message rendered_string = '' #self.tests.append(rendered_string) self.output_ttag(template_string, rendered_string, out_context)