示例#1
0
    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('//', '/')
示例#2
0
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
示例#3
0
    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
示例#4
0
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]
示例#5
0
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 ''
示例#6
0
    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, {})
示例#7
0
    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)
示例#8
0
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)
示例#9
0
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)
示例#10
0
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()
示例#11
0
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
示例#12
0
from django.template.loaders.filesystem import Loader

from .base import ConditionalJinja2LoaderMixin


class Loader(ConditionalJinja2LoaderMixin, Loader):
    pass


_loader = Loader()