Python jinja2 模块,Undefined() 实例源码

我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用jinja2.Undefined()

项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        self.context_processors = options.pop('context_processors', [])

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        if 'loader' not in options:
            options['loader'] = jinja2.FileSystemLoader(self.template_dirs)
        options.setdefault('autoescape', True)
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)
项目:rhel7stig-sphinx    作者:major    | 项目源码 | 文件源码
def description_tag_prettify(uglyname):
    """Make description tags prettier."""
    if uglyname is None or isinstance(uglyname, jinja2.Undefined):
        return uglyname

    prettynames = {
        'SecurityOverrideGuidance': 'Security Override Guidance',
        'MitigationControl': 'Mitigation Control',
        'IAControls': 'IA Controls',
        'FalseNegatives': 'False Negatives',
        'Mitigations': 'Mitigations',
        'ThirdPartyTools': 'Third Party Tools',
        'Responsibility': 'Responsibility',
        'PotentialImpacts': 'Potential Impacts',
        'FalsePositives': 'False Positives',
        'Documentable': 'Documentable'
    }

    if uglyname in prettynames:
        return prettynames[uglyname]
    else:
        return uglyname

# Get Jinja configured properly
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        self.context_processors = options.pop('context_processors', [])

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        if 'loader' not in options:
            options['loader'] = jinja2.FileSystemLoader(self.template_dirs)
        options.setdefault('autoescape', True)
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        self.context_processors = options.pop('context_processors', [])

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        if 'loader' not in options:
            options['loader'] = jinja2.FileSystemLoader(self.template_dirs)
        options.setdefault('autoescape', True)
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        options.setdefault('autoescape', True)
        options.setdefault('loader', jinja2.FileSystemLoader(self.template_dirs))
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)
项目:deb-python-coffin    作者:openstack    | 项目源码 | 文件源码
def django_filter_to_jinja2(filter_func):
    """
    Note: Due to the way this function is used by
    ``coffin.template.Library``, it needs to be able to handle native
    Jinja2 filters and pass them through unmodified. This necessity
    stems from the fact that it is not always possible to determine
    the type of a filter.

    TODO: Django's "func.is_safe" is not yet handled
    """
    def _convert_out(v):
        if isinstance(v, SafeData):
            return Markup(v)
        if isinstance(v, EscapeData):
            return Markup.escape(v)       # not 100% equivalent, see mod docs
        return v
    def _convert_in(v):
        if isinstance(v, Undefined):
            # Essentially the TEMPLATE_STRING_IF_INVALID default
            # setting. If a non-default is set, Django wouldn't apply
            # filters. This is something that we neither can nor want to
            # simulate in Jinja.
            return ''
        return v
    def conversion_wrapper(value, *args, **kwargs):
        result = filter_func(_convert_in(value), *args, **kwargs)
        return _convert_out(result)
    # Jinja2 supports a similar machanism to Django's
    # ``needs_autoescape`` filters: environment filters. We can
    # thus support Django filters that use it in Jinja2 with just
    # a little bit of argument rewriting.
    if hasattr(filter_func, 'needs_autoescape'):
        @environmentfilter
        def autoescape_wrapper(environment, *args, **kwargs):
            kwargs['autoescape'] = environment.autoescape
            return conversion_wrapper(*args, **kwargs)
        return autoescape_wrapper
    else:
        return conversion_wrapper
项目:airflow-declarative    作者:rambler-digital-solutions    | 项目源码 | 文件源码
def yaml_filter(obj):
    if isinstance(obj, str_types):
        return obj
    elif isinstance(obj, jinja2.Undefined):
        return ''
    else:
        try:
            return dump(obj)
        except Exception as exc:
            raise RuntimeError(
                'Unable to serialize {!r} to YAML because {}.'
                'Template render must produce valid YAML file, so please use'
                ' simple types in `with_items` block.'
                ''.format(obj, exc)
            )
项目:dbt    作者:fishtown-analytics    | 项目源码 | 文件源码
def create_macro_capture_env(node):

    class ParserMacroCapture(jinja2.Undefined):
        """
        This class sets up the parser to capture macros.
        """
        def __init__(self, hint=None, obj=None, name=None,
                     exc=None):
            super(jinja2.Undefined, self).__init__()

            self.node = node
            self.name = name
            self.package_name = node.get('package_name')

        def __getattr__(self, name):

            # jinja uses these for safety, so we have to override them.
            # see https://github.com/pallets/jinja/blob/master/jinja2/sandbox.py#L332-L339 # noqa
            if name in ['unsafe_callable', 'alters_data']:
                return False

            self.package_name = self.name
            self.name = name

            return self

        def __call__(self, *args, **kwargs):
            return True

    return ParserMacroCapture
项目:NetOpsWorkshop    作者:ipspace    | 项目源码 | 文件源码
def getOptions():
  try:
    options, args = getopt.getopt(sys.argv[1:], "y:j:n:sw", ["yaml=", "jinja=", "notrim", "strict", "warning"])
  except getopt.GetoptError as err:
    # print help information and exit:
    print str(err)  # will print something like "option -a not recognized"
    sys.exit(2)

  global yamlfile,jinjafile,trim,undefined
  trim = True
  opts = 0

  for opt,arg in options:
    opts = opts + 1
    if opt in ("-y","-yaml"):
      yamlfile = arg
    elif opt in ("-j","-jinja"):
      jinjafile = arg
    elif opt in ("-n","-notrim"):
      trim = False
    elif opt in ("-w","-warning"):
      undefined = make_logging_undefined (base = Undefined)
    elif opt in ("-s","-strict"):
      undefined = make_logging_undefined (base = StrictUndefined)

  return opts > 0
项目:dancedeets-monorepo    作者:mikelambert    | 项目源码 | 文件源码
def htmlsafe_json_dumps(obj, **kwargs):
    """Works exactly like :func:`dumps` but is safe for use in ``<script>``
    tags.  It accepts the same arguments and returns a JSON string.  Note that
    this is available in templates through the ``|tojson`` filter which will
    also mark the result as safe.  Due to how this function escapes certain
    characters this is safe even if used outside of ``<script>`` tags.
    The following characters are escaped in strings:
    -   ``<``
    -   ``>``
    -   ``&``
    -   ``'``
    This makes it safe to embed such strings in any place in HTML with the
    notable exception of double quoted attributes.  In that case single
    quote your attributes or HTML escape it in addition.
    .. versionchanged:: 0.10
       This function's return value is now always safe for HTML usage, even
       if outside of script tags or if used in XHTML.  This rule does not
       hold true when using this function in HTML attributes that are double
       quoted.  Always single quote attributes if you use the ``|tojson``
       filter.  Alternatively use ``|tojson|forceescape``.
    """
    if obj is None or isinstance(obj, jinja2.Undefined):
        return 'null'
    rv = json.dumps(obj, **kwargs) \
        .replace(u'<', u'\\u003c') \
        .replace(u'>', u'\\u003e') \
        .replace(u'&', u'\\u0026') \
        .replace(u"'", u'\\u0027')
    if not _slash_escape:
        rv = rv.replace('\\/', '/')
    return rv
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        options.setdefault('autoescape', True)
        options.setdefault('loader', jinja2.FileSystemLoader(self.template_dirs))
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def is_project(iterable):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: x.parent is None, iterable)
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def is_task_of(iterable, project):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: x.parent == project.persistentIdentifier, iterable)
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def project_with_completed_tasks(iterable):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: len(
        filter(lambda y: y.parent == x.persistentIdentifier and y.dateCompleted is not None, iterable)) > 0,
                  is_project(iterable))
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def project_with_incomplete_tasks(iterable):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: len(
        filter(lambda y: y.parent == x.persistentIdentifier and y.dateCompleted is None, iterable)) > 0,
                  is_project(iterable))
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def project_with_processing_tasks(iterable):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: len(
        filter(
            lambda y: y.parent == x.persistentIdentifier and y.dateCompleted is None and 'progress' in y.note.metadata,
            iterable)) > 0,
                  is_project(iterable))
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def is_incomplete(iterable):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: x.dateCompleted is None, iterable)
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def is_processing(iterable):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: 'progress' in x.note.metadata, is_incomplete(iterable))
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def not_started(iterable):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
    return filter(lambda x: 'progress' not in x.note.metadata, is_incomplete(iterable))
项目:py-omni-weekly    作者:JamesPan    | 项目源码 | 文件源码
def date(obj, fmt='%Y.%m.%d'):
    if obj is None or isinstance(obj, Undefined):
        return obj
    return datetime.datetime.strftime(obj, fmt)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        options.setdefault('autoescape', True)
        options.setdefault('loader', jinja2.FileSystemLoader(self.template_dirs))
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        options.setdefault('autoescape', True)
        options.setdefault('loader', jinja2.FileSystemLoader(self.template_dirs))
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
def fail_when_undefined(value):
    """Filter to force a failure when the value is undefined."""
    if isinstance(value, jinja2.Undefined):
        value()
    return value