Python源码示例:django.template()

示例1
def __init__(self, request, response):
    self.initialize(request, response)
    api_fixer.ReplaceDefaultArgument(response.set_cookie.im_func, 'secure',
                                     not constants.IS_DEV_APPSERVER)
    api_fixer.ReplaceDefaultArgument(response.set_cookie.im_func, 'httponly',
                                     True)
    if self.current_user:
      self._xsrf_token = xsrf.GenerateToken(_GetXsrfKey(),
                                            self.current_user.email())
      if self.app.config.get('using_angular', constants.DEFAULT_ANGULAR):
        # AngularJS requires a JS readable XSRF-TOKEN cookie and will pass this
        # back in AJAX requests.
        self.response.set_cookie('XSRF-TOKEN', self._xsrf_token, httponly=False)
    else:
      self._xsrf_token = None

    self.csp_nonce = _GetCspNonce()

    self._RawWrite = self.response.out.write
    self.response.out.write = self._ReplacementWrite

  # All content should be rendered through a template system to reduce the
  # risk/likelihood of XSS issues.  Access to the original function
  # self.response.out.write is available via self._RawWrite for exceptional
  # circumstances. 
示例2
def render_to_string(self, template, template_values=None):
    """Renders template_name with template_values and returns as a string."""
    if not template_values:
      template_values = {}

    template_values['_xsrf'] = self._xsrf_token
    template_values['_csp_nonce'] = self.csp_nonce
    template_strategy = self.app.config.get('template', constants.CLOSURE)

    if template_strategy == constants.DJANGO:
      t = django.template.loader.get_template(template)
      template_values = django.template.Context(template_values)
      return t.render(template_values)
    elif template_strategy == constants.JINJA2:
      return self.jinja2.render_template(template, **template_values)
    else:
      ijdata = { 'csp_nonce': self.csp_nonce }
      return template(template_values, ijdata) 
示例3
def Home(request):
    """Our Home page.
    This also doubles as a general API request handler with a few specific
    bits for the home page template."""

    # The recent tests table.
    recent_tests = memcache.get(key=RECENT_TESTS_MEMCACHE_KEY)
    if not recent_tests:
        ScheduleRecentTestsUpdate()

    show_evolution = False

    params = {
        'page_title': 'Home',
        'message': request.GET.get('message'),
        'recent_tests': recent_tests,
        'show_evolution': show_evolution,
    }
    return GetResults(request, template='home.html', params=params,
                                        do_sparse_filter=True) 
示例4
def GetStatsDataTemplatized(params, template='table'):
    """Returns the stats table run through a template.

    Args:
        params: Example:
                        params = {
                            'v': one of the keys in user_agent.BROWSER_NAV,
                            'current_user_agent': a user agent entity,
                            'user_agents': list_of user agents,
                            'tests': list of test names,
                            'stats': dict - stats[test_name][user_agent],
                            'total_runs': total_runs[test_name],
                            'request_path': request.path,
                            'params': result_parent.params, #optional
                        }

    """
    params['browser_nav'] = result_stats.BROWSER_NAV
    params['is_admin'] = users.is_current_user_admin()
    if not re.search('\?', params['request_path']):
        params['request_path'] = params['request_path'] + '?'
    t = loader.get_template('stats_%s.html' % template)
    template_rendered = t.render(Context(params))
    return template_rendered 
示例5
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
示例6
def parse(cls, parser, token):
        """
        Custom parsing for the ``{% ajax_comment_tags for ... %}`` tag.
        """
        # Process the template line.
        tag_name, args, kwargs = parse_token_kwargs(
            parser, token,
            allowed_kwargs=cls.allowed_kwargs,
            compile_args=False,  # Only overrule here, keep at render() phase.
            compile_kwargs=cls.compile_kwargs
        )

        # remove "for" keyword, so all other args can be resolved in render().
        if args[0] == 'for':
            args.pop(0)

        # And apply the compilation afterwards
        for i in range(len(args)):
            args[i] = parser.compile_filter(args[i])

        cls.validate_args(tag_name, *args, **kwargs)
        return cls(tag_name, *args, **kwargs) 
示例7
def get_template_loaders():
    """
    Compatibility method to fetch the template loaders.
    Source: https://github.com/django-debug-toolbar/django-debug-toolbar/blob/ece1c2775af108a92a0ef59636266b49e286e916/debug_toolbar/compat.py
    """
    try:
        from django.template.engine import Engine
    except ImportError:  # Django < 1.8
        Engine = None

    if Engine:
        try:
            engine = Engine.get_default()
        except ImproperlyConfigured:
            loaders = []
        else:
            loaders = engine.template_loaders
    else:  # Django < 1.8
        from django.template.loader import find_template_loader
        loaders = [
            find_template_loader(loader_name)
            for loader_name in settings.TEMPLATE_LOADERS]
    return loaders 
示例8
def test_add_to_builtins(self):
            from compat import add_to_builtins

            # Explicit import of tags
            template = Template(
                '{% load test_app_tags %}'
                '{% my_tag %}'
            )
            self.assertIn('Return value of my_tag', template.render(Context({})))

            # No import
            with self.assertRaises(TemplateSyntaxError):
                template = Template(
                    '{% my_tag %}'
                )
                template.render(Context({}))

            # No import but add_to_builtins call
            add_to_builtins('compat.tests.test_app.templatetags.test_app_tags')
            template = Template(
                '{% my_tag %}'
            )
            self.assertIn('Return value of my_tag', template.render(Context({}))) 
示例9
def load_scenarios_from_path(self, relative_scenario_dir, include_identifier=False):
        """
        Returns an array of (title, xmlcontent) from files contained in a specified directory,
        formatted as expected for the return value of the workbench_scenarios() method.

        If `include_identifier` is True, returns an array of (identifier, title, xmlcontent).
        """
        base_dir = os.path.dirname(os.path.realpath(sys.modules[self.module_name].__file__))
        scenario_dir = os.path.join(base_dir, relative_scenario_dir)

        scenarios = []
        if os.path.isdir(scenario_dir):
            for template in sorted(os.listdir(scenario_dir)):
                if not template.endswith('.xml'):
                    continue
                identifier = template[:-4]
                title = identifier.replace('_', ' ').title()
                template_path = os.path.join(relative_scenario_dir, template)
                scenario = str(self.render_django_template(template_path, {"url_name": identifier}))
                if not include_identifier:
                    scenarios.append((title, scenario))
                else:
                    scenarios.append((identifier, title, scenario))

        return scenarios 
示例10
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
示例11
def read_template_source(filename):
    """Read the source of a Django template, returning the Unicode text."""
    # Import this late to be sure we don't trigger settings machinery too
    # early.
    from django.conf import settings

    if not settings.configured:
        settings.configure()

    with open(filename, "rb") as f:
        # The FILE_CHARSET setting will be removed in 3.1:
        # https://docs.djangoproject.com/en/3.0/ref/settings/#file-charset
        if django.VERSION >= (3, 1):
            charset = 'utf-8'
        else:
            charset = settings.FILE_CHARSET
        text = f.read().decode(charset)

    return text 
示例12
def get_line_map(self, filename):
        """The line map for `filename`.

        A line map is a list of character offsets, indicating where each line
        in the text begins.  For example, a line map like this::

            [13, 19, 30]

        means that line 2 starts at character 13, line 3 starts at 19, etc.
        Line 1 always starts at character 0.

        """
        if filename not in self.source_map:
            template_source = read_template_source(filename)
            if 0:   # change to see the template text
                for i in range(0, len(template_source), 10):
                    print("%3d: %r" % (i, template_source[i:i+10]))
            self.source_map[filename] = make_line_map(template_source)
        return self.source_map[filename] 
示例13
def test_get(self):
        # Verify that Resource.get fetches a Resource from the datastore.
        assert Resource.get('xyz', '1') is None
        self.put_resource('1', 'xyz', 10, 'pqr')
        assert Resource.get('xyz', '1').content == 'pqr'
        self.delete_resource('1', 'xyz')
        assert Resource.get('xyz', '1') is None

        # Verify that Resource.get fetches a Resource from an existing file.
        content = Resource.get('message.html.template', '1').content
        assert content != 'pqr'

        # Verify that the file can be overriden by a datastore entity.
        self.put_resource('1', 'message.html.template', 10, 'pqr')
        assert Resource.get('message.html.template', '1').content == 'pqr'
        self.delete_resource('1', 'message.html.template')
        assert Resource.get('message.html.template', '1').content == content 
示例14
def render(self, template, template_values=None):
    """Renders template with template_values and writes to the response."""
    template_strategy = self.app.config.get('template', constants.CLOSURE)
    self._RawWrite(self.render_to_string(template, template_values)) 
示例15
def Render(request, template, params={}):
  """Wrapper function to render templates with global and category vars."""
  params['app_title'] = settings.APP_TITLE
  params['version_id'] = os.environ['CURRENT_VERSION_ID']
  params['build'] = settings.BUILD
  params['epoch'] = int(time.time())
  params['request_path'] = request.get_full_path()
  params['request_path_lastbit'] = re.sub('^.+\/([^\/]+$)', '\\1', request.path)
  params['current_ua_string'] = request.META['HTTP_USER_AGENT']
  params['current_ua'] = user_agent_parser.PrettyUserAgent(params['current_ua_string'])
  params['chromeframe_enabled'] = request.COOKIES.get(
      'browserscope-chromeframe-enabled', '0')
  params['app_categories'] = []
  params['is_admin'] = users.is_current_user_admin()

  current_user = users.get_current_user()
  if current_user:
    params['user_id'] = current_user.user_id()
  else:
    params['user_id'] = None
  params['user'] = current_user

  params['sign_in'] = users.create_login_url(request.get_full_path())
  params['sign_out'] = users.create_logout_url('/')

  return shortcuts.render_to_response(template, params) 
示例16
def configure(config_dict={}, django_admin=False):
    _create_app(inspect.stack())  # load application from parent module

    if 'BASE_DIR' in config_dict:
        config_dict.setdefault('TEMPLATE_DIRS', [os.path.join(config_dict['BASE_DIR'], 'templates')])

    if django_admin:
        _configure_admin(config_dict)

    django_config = {
        'INSTALLED_APPS': ['django_micro._app_config'] + config_dict.pop('INSTALLED_APPS', []),
        'ROOT_URLCONF': __name__,
        'TEMPLATES': [{
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': config_dict.pop('TEMPLATE_DIRS', []),
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': config_dict.pop('CONTEXT_PROCESSORS', []),
                'builtins': [__name__],
            },
        }],
    }

    django_config.update({key: val for key, val in config_dict.items() if key.isupper()})
    settings.configure(**django_config)
    django.setup() 
示例17
def add_arguments(self, parser):
        parser.add_argument('name', help='Name of the application or project.')
        parser.add_argument('directory', nargs='?', help='Optional destination directory')
        parser.add_argument('--template',
            help='The path or URL to load the template from.')
        parser.add_argument('--extension', '-e', dest='extensions',
            action='append', default=['py'],
            help='The file extension(s) to render (default: "py"). '
                 'Separate multiple extensions with commas, or use '
                 '-e multiple times.')
        parser.add_argument('--name', '-n', dest='files',
            action='append', default=[],
            help='The file name(s) to render. '
                 'Separate multiple extensions with commas, or use '
                 '-n multiple times.') 
示例18
def is_url(self, template):
        """
        Returns True if the name looks like a URL
        """
        if ':' not in template:
            return False
        scheme = template.split(':', 1)[0].lower()
        return scheme in self.url_schemes 
示例19
def clean(self):
        if not re.match(r"\<.+\/?\>", self.content):
            self.content = "<script>{}</script>".format(self.content)

        self.content = BeautifulSoup(self.content, "html.parser").prettify()

        try:
            template = Template(self.content)
            template.render(Context())
        except Exception as error:
            raise ValidationError({"content": error})

        return self 
示例20
def get_doc(self, request=None, context=None):
        content = self.content

        if request:
            template = Template(content)
            context = Context(Tag.create_context(request, context))
            content = template.render(context)

        return BeautifulSoup(content, "html.parser") 
示例21
def render(self, context):
        # Include proper template, avoid parsing it twice by operating like @register.inclusion_tag()
        if not getattr(self, 'nodelist', None):
            if appsettings.USE_THREADEDCOMMENTS:
                template = get_template("fluent_comments/templatetags/threaded_list.html")
            else:
                template = get_template("fluent_comments/templatetags/flat_list.html")
            self.nodelist = template

        # NOTE NOTE NOTE
        # HACK: Determine the parent object based on the comment list queryset.
        # the {% render_comment_list for article %} tag does not pass the object in a general form to the template.
        # Not assuming that 'object.pk' holds the correct value.
        #
        # This obviously doesn't work when the list is empty.
        # To address that, the client-side code also fixes that, by looking for the object ID in the nearby form.
        target_object_id = context.get('target_object_id', None)
        if not target_object_id:
            comment_list = context['comment_list']
            if isinstance(comment_list, list) and comment_list:
                target_object_id = comment_list[0].object_pk

        # Render the node
        context['USE_THREADEDCOMMENTS'] = appsettings.USE_THREADEDCOMMENTS
        context['target_object_id'] = target_object_id

        if django.VERSION >= (1, 8):
            context = context.flatten()
        return self.nodelist.render(context) 
示例22
def fluent_comments_list(parser, token):
    """
    A tag to select the proper template for the current comments app.
    """
    return FluentCommentsList() 
示例23
def render_to_string(template_name, context=None,
                     context_instance=_context_instance_undefined,
                     dirs=_dirs_undefined,
                     dictionary=_dictionary_undefined,
                     request=None, using=None):
    if (context_instance is _context_instance_undefined and dirs is _dirs_undefined and
            dictionary is _dictionary_undefined):
        if django.VERSION >= (1, 8):
            # Call new render_to_string with new arguments
            return render_to_string_django(template_name, context, request, using)
        else:
            # Call legacy render_to_string with new arguments
            from django.template import RequestContext
            context_instance = RequestContext(request) if request else None
            return render_to_string_django(template_name, context, context_instance)
    else:
        if django.VERSION >= (1, 10):
            # Call new render_to_string with legacy arguments
            raise NotImplementedError('Django compat does not support calling post-1.8 render_to_string with pre-1.8 '
                                      'keyword arguments')
        else:
            # Call legacy render_to_string with legacy arguments
            if dictionary is _dictionary_undefined:
                dictionary = {}
            if context_instance is _context_instance_undefined:
                context_instance = None
            return render_to_string_django(template_name, dictionary, context_instance)


### Undocumented ### 
示例24
def test_url_template_tag(self):
        template = Template(
            '{% load url from compat %}'
            '<a href="{% url "logout" %}">Log out</a>'
        )
        html = template.render(Context({}))
        self.assertEqual(
            html,
            '<a href="/accounts/logout/">Log out</a>'
        ) 
示例25
def test_get_template_loaders(self):
        template_loaders = get_template_loaders()
        self.assertEqual(len(template_loaders), 2)
        self.assertIsInstance(template_loaders[0], django.template.loaders.filesystem.Loader)
        self.assertIsInstance(template_loaders[1], django.template.loaders.app_directories.Loader) 
示例26
def test_verbatim_tag02(self):
        template = Template(self.import_tag +
            '{% verbatim %}{% endif %}{% endverbatim %}'
        )
        html = template.render(Context({}))
        self.assertEqual(html,
             '{% endif %}'
        ) 
示例27
def test_verbatim_tag03(self):
        template = Template(self.import_tag +
            '{% verbatim %}It\'s the {% verbatim %} tag{% endverbatim %}'
        )
        html = template.render(Context({}))
        self.assertEqual(html,
             'It\'s the {% verbatim %} tag'
        ) 
示例28
def test_verbatim_tag05(self):
        template = Template(self.import_tag +
            '{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}'
        )
        html = template.render(Context({}))
        self.assertEqual(html, '') 
示例29
def test_verbatim_tag06(self):
            template = Template(self.import_tag +
                '{% verbatim special %}'
                                  'Don\'t {% endverbatim %} just yet{% endverbatim special %}'
            )
            html = template.render(Context({}))
            self.assertEqual(html,
                 'Don\'t {% endverbatim %} just yet'
            ) 
示例30
def test_for_obj_no_metadata(self):
        """ Checks that defaults are used when no metadata object (previously) exists.
            The relevant path is also removed so that the object's link to the database is used.
        """
        self.deregister_alternatives()

        # Remove all metadata
        Metadata = Coverage._meta.get_model('modelinstance')

        # Create a page with metadata (with a path that get_metadata won't find)
        page = Page.objects.create(title=u"Page Title", type=u"nometadata", content=u"no meta data")
        content_type = ContentType.objects.get_for_model(Page)
        Metadata.objects.filter(_content_type=content_type, _object_id=page.pk).update(title="Page Title",
                                                                                       _path="/different/")

        expected_output = '<title>Page Title</title>'

        # Check the output of the template is correct when the metadata exists
        self.context = {'obj': page}
        self.compilesTo("{% get_metadata for obj %}", expected_output)
        self.compilesTo("{% get_metadata for obj as var %}{{ var }}", expected_output)
        self.compilesTo("{% get_metadata for obj as var %}{{ var.populate_from7 }}",
                        '<populate_from7>model instance content: no meta data</populate_from7>')

        # Check the output is correct when there is no metadata
        Metadata.objects.filter(_content_type=content_type, _object_id=page.pk).delete()
        self.compilesTo("{% get_metadata for obj %}", "<title>example.com</title>")
        self.compilesTo("{% get_metadata for obj as var %}{{ var }}", "<title>example.com</title>")
        self.compilesTo("{% get_metadata for obj as var %}{{ var.populate_from7 }}",
                        '<populate_from7>model instance content: no meta data</populate_from7>')