Python jinja2.Undefined() Examples

The following are 30 code examples of jinja2.Undefined(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module jinja2 , or try the search function .
Example #1
Source File: jinja2.py    From bioforum with MIT License 6 votes vote down vote up
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super().__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) 
Example #2
Source File: fol2.py    From xos with Apache License 2.0 6 votes vote down vote up
def xproto_fol_to_python_test(policy, fol, model, tag=None):
    if isinstance(fol, jinja2.Undefined):
        raise Exception("Could not find policy:", policy)

    f2p = FOL2Python()
    fol_reduced = f2p.hoist_outer(fol)

    if fol_reduced in ["True", "False"] and fol != fol_reduced:
        raise TrivialPolicy(
            "Policy %(name)s trivially reduces to %(reduced)s."
            "If this is what you want, replace its contents with %(reduced)s"
            % {"name": policy, "reduced": fol_reduced}
        )

    a = f2p.gen_test_function(fol_reduced, policy, tag="security_check")

    return astunparse.unparse(a) 
Example #3
Source File: fol2.py    From xos with Apache License 2.0 6 votes vote down vote up
def xproto_fol_to_python_validator(policy, fol, model, message, tag=None):
    if isinstance(fol, jinja2.Undefined):
        raise Exception("Could not find policy:", policy)

    f2p = FOL2Python()
    fol_reduced = f2p.hoist_outer(fol)

    if fol_reduced in ["True", "False"] and fol != fol_reduced:
        raise TrivialPolicy(
            "Policy %(name)s trivially reduces to %(reduced)s."
            "If this is what you want, replace its contents with %(reduced)s"
            % {"name": policy, "reduced": fol_reduced}
        )

    a = f2p.gen_validation_function(fol_reduced, policy, message, tag="validator")

    return astunparse.unparse(a) 
Example #4
Source File: jinja2.py    From python with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: jinja.py    From st2 with Apache License 2.0 6 votes vote down vote up
def get_jinja_environment(allow_undefined=False, trim_blocks=True, lstrip_blocks=True):
    '''
    jinja2.Environment object that is setup with right behaviors and custom filters.

    :param strict_undefined: If should allow undefined variables in templates
    :type strict_undefined: ``bool``

    '''
    # Late import to avoid very expensive in-direct import (~1 second) when this function
    # is not called / used
    import jinja2

    undefined = jinja2.Undefined if allow_undefined else jinja2.StrictUndefined
    env = jinja2.Environment(  # nosec
        undefined=undefined,
        trim_blocks=trim_blocks,
        lstrip_blocks=lstrip_blocks
    )
    env.filters.update(get_filters())
    env.tests['in'] = lambda item, list: item in list
    return env 
Example #6
Source File: fol2.py    From xos with Apache License 2.0 6 votes vote down vote up
def xproto_fol_to_python_test(policy, fol, model, tag=None):
    if isinstance(fol, jinja2.Undefined):
        raise Exception("Could not find policy:", policy)

    f2p = FOL2Python()
    fol_reduced = f2p.hoist_outer(fol)

    if fol_reduced in ["True", "False"] and fol != fol_reduced:
        raise TrivialPolicy(
            "Policy %(name)s trivially reduces to %(reduced)s."
            "If this is what you want, replace its contents with %(reduced)s"
            % {"name": policy, "reduced": fol_reduced}
        )

    a = f2p.gen_test_function(fol_reduced, policy, tag="security_check")

    return astunparse.unparse(a) 
Example #7
Source File: fol2.py    From xos with Apache License 2.0 6 votes vote down vote up
def xproto_fol_to_python_validator(policy, fol, model, message, tag=None):
    if isinstance(fol, jinja2.Undefined):
        raise Exception("Could not find policy:", policy)

    f2p = FOL2Python()
    fol_reduced = f2p.hoist_outer(fol)

    if fol_reduced in ["True", "False"] and fol != fol_reduced:
        raise TrivialPolicy(
            "Policy %(name)s trivially reduces to %(reduced)s."
            "If this is what you want, replace its contents with %(reduced)s"
            % {"name": policy, "reduced": fol_reduced}
        )

    a = f2p.gen_validation_function(fol_reduced, policy, message, tag="validator")

    return astunparse.unparse(a) 
Example #8
Source File: jinja2.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super().__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) 
Example #9
Source File: jinja2.py    From python2017 with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: filters.py    From kolla with Apache License 2.0 6 votes vote down vote up
def customizable(context, val_list, call_type):
    # NOTE(mgoddard): Don't try to customise undefined values. There are cases
    # where this might happen, for example using a generic template overrides
    # file for building multiple image install types and/or distros, where
    # variables are not defined in every case.
    if isinstance(val_list, Undefined):
        return val_list
    name = context['image_name'].replace("-", "_") + "_" + call_type + "_"
    if name + "override" in context:
        return context[name + "override"]
    if name + "append" in context:
        val_list.extend(context[name + "append"])
    if name + "remove" in context:
        for removal in context[name + "remove"]:
            if removal in val_list:
                val_list.remove(removal)
    return val_list 
Example #11
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def timestamp(val):
    """Try convert non-timestamp values to a timestamp

       >>> timestamp({"year": 2018, "month": 8, "day": 1, "timezoneID": "CET"})
       1533078000000

       >>> timestamp(jinja2.Undefined())
       'null'

       >>> timestamp("now") > 1530000000000
       True

       >>> timestamp("now") > 2000000000000 # 2033
       False
    """
    if isinstance(val, dict):
        y = val.get("year", 1970)
        m = val.get("month", 1)
        d = val.get("day", 1)
        h = val.get("hour", 0)
        n = val.get("minute", 0)
        s = val.get("second", 0)
        u = val.get("milliSecond", 0)
        z = pytz.timezone(val.get("timezoneID", "UTC"))
        dt = datetime.datetime(y, m, d, h, n, s, u, z)
        return int(calendar.timegm(dt.utctimetuple()) * 1000)
    if isinstance(val, jinja2.Undefined):
        return "null"
    if isinstance(val, datetime.datetime):
        return int(calendar.timegm(val.utctimetuple()) * 1000)
    if val == "now":
        return int(calendar.timegm(datetime.datetime.now().utctimetuple()) * 1000)
    return val 
Example #12
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def ldap_filter(val):
    """Jinja2 filter function 'ldap' produces LDAP-encoded string of the value"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"
    escaped = []
    for char in str(val):
        if char < '0' or char > 'z' or char in "\\*()":
            char = "\\%02x" % ord(char)
        escaped.append(char)
    return ''.join(escaped) 
Example #13
Source File: jinja2_filters.py    From resilient-python-api with MIT License 5 votes vote down vote up
def _filter_base64(val):
    """
    Return val as base64 encoded string
    """
    if isinstance(val, Undefined):
        return ""
    s = json.dumps(val).encode("utf-8")
    return b64encode(s).decode("utf-8") 
Example #14
Source File: transformer.py    From airflow-declarative with Apache License 2.0 5 votes vote down vote up
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)
            ) 
Example #15
Source File: jinja2.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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) 
Example #16
Source File: page.py    From dactyl with MIT License 5 votes vote down vote up
def get_pp_env(self, loader):
        if (self.config["preprocessor_allow_undefined"] or
                self.config.bypass_errors):
            preferred_undefined = jinja2.Undefined
        else:
            preferred_undefined = jinja2.StrictUndefined

        pp_env = jinja2.Environment(undefined=preferred_undefined,
                extensions=['jinja2.ext.i18n'], loader=loader)

        # Add custom "defined_and_" tests
        def defined_and_equalto(a,b):
            return pp_env.tests["defined"](a) and pp_env.tests["equalto"](a, b)
        pp_env.tests["defined_and_equalto"] = defined_and_equalto
        def undefined_or_ne(a,b):
            return pp_env.tests["undefined"](a) or pp_env.tests["ne"](a, b)
        pp_env.tests["undefined_or_ne"] = undefined_or_ne

        # Pull exported values (& functions) from page filters into the pp_env
        for filter_name in self.filters(save=False):
            if filter_name not in self.config.filters.keys():
                logger.debug("Skipping unloaded filter '%s'" % filter_name)
                continue
            if "export" in dir(self.config.filters[filter_name]):
                for key,val in self.config.filters[filter_name].export.items():
                    logger.debug("... pulling in filter_%s's exported key '%s'"
                            % (filter_name, key))
                    pp_env.globals[key] = val

        return pp_env 
Example #17
Source File: render_graphiql.py    From graphene-tornado with MIT License 5 votes vote down vote up
def tojson_filter(obj, **kwargs):
    if isinstance(obj, Undefined):
        return str(obj)
    return Markup(htmlsafe_dumps(obj, **kwargs)) 
Example #18
Source File: publish.py    From guildai with Apache License 2.0 5 votes vote down vote up
def empty(val):
        if val in (None, "") or isinstance(val, jinja2.Undefined):
            return ""
        return val 
Example #19
Source File: publish.py    From guildai with Apache License 2.0 5 votes vote down vote up
def flag_val(val):
        if isinstance(val, jinja2.Undefined):
            return ""
        return run_util.format_attr(val) 
Example #20
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def pretty_filter(val, indent=2):
    """Jinja2 filter function 'pretty' produces pretty-printed string of the value"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"

    def nice_repr(object, context, maxlevels, level):
        if sys.version_info.major < 3:
            typ = type(object)
            if typ is unicode:
                object = object.encode("utf-8")
        return pprint._safe_repr(object, context, maxlevels, level)

    printer = pprint.PrettyPrinter(indent=indent)
    printer.format = nice_repr
    return printer.pformat(val) 
Example #21
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def sh_filter(val):
    """Jinja2 filter function 'sh' escapes for use in a Unix shell commandline"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"
    escaped = []
    for char in str(val):
        if char in "$#\"":
            char = "\\" + char
        elif ord(char) < 32 or ord(char) > 126:
            char = "\\%03o" % ord(char)
        escaped.append(char)
    return ''.join(escaped) 
Example #22
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def ps_filter(val):
    """Jinja2 filter function 'ps' escapes for use in a PowerShell commandline"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"
    escaped = []
    for char in str(val):
        if char in "`$#'\"":
            char = "`" + char
        elif char == '\0':
            char = "`0"
        elif char == '\a':
            char = "`a"
        elif char == '\b':
            char = "`b"
        elif char == '\f':
            char = "`f"
        elif char == '\n':
            char = "`n"
        elif char == '\r':
            char = "`r"
        elif char == '\t':
            char = "`t"
        elif char == '\v':
            char = "`v"
        escaped.append(char)
    return ''.join(escaped) 
Example #23
Source File: yasha.py    From yasha with MIT License 5 votes vote down vote up
def load_jinja(
        path, tests, filters, classes, mode,
        trim_blocks, lstrip_blocks, keep_trailing_newline):
    from jinja2.defaults import BLOCK_START_STRING, BLOCK_END_STRING, \
        VARIABLE_START_STRING, VARIABLE_END_STRING, \
        COMMENT_START_STRING, COMMENT_END_STRING, \
        LINE_STATEMENT_PREFIX, LINE_COMMENT_PREFIX, \
        NEWLINE_SEQUENCE

    undefined = {
        'pedantic': jinja.StrictUndefined,
        'debug': jinja.DebugUndefined,
        None: jinja.Undefined,
    }

    env = jinja.Environment(
        block_start_string=BLOCK_START_STRING,
        block_end_string=BLOCK_END_STRING,
        variable_start_string=VARIABLE_START_STRING,
        variable_end_string=VARIABLE_END_STRING,
        comment_start_string=COMMENT_START_STRING,
        comment_end_string=COMMENT_END_STRING,
        line_statement_prefix=LINE_STATEMENT_PREFIX,
        line_comment_prefix=LINE_COMMENT_PREFIX,
        trim_blocks=trim_blocks,
        lstrip_blocks=lstrip_blocks,
        newline_sequence=NEWLINE_SEQUENCE,
        keep_trailing_newline=keep_trailing_newline,
        extensions=classes,
        undefined=undefined[mode],
        loader=jinja.FileSystemLoader(path)
    )
    env.tests.update(tests)
    env.filters.update(filters)
    return env 
Example #24
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def idna_filter(val):
    """Jinja2 filter function 'idna' encodes the value per RFC 3490"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"
    return val.encode("idna").decode("utf-8") 
Example #25
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def url_filter(val):
    """Jinja2 filter function 'url' produces URL-encoded string of the value"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"
    return urllib.quote(str(val)) 
Example #26
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def html_filter(val):
    """Jinja2 filter function 'html' produces HTML-encoded string of the value"""
    if isinstance(val, jinja2.Undefined):
        return "[undefined]"
    return html_escape(val) 
Example #27
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def json_filter(val, indent=0):
    """Jinja2 filter function 'json' produces JSONified string of the value"""
    if val is None or isinstance(val, jinja2.Undefined):
        return "null"
    return json.dumps(val, indent=indent, sort_keys=True) 
Example #28
Source File: template_functions.py    From resilient-python-api with MIT License 5 votes vote down vote up
def js_filter(val):
    """Jinja2 filter function 'js' produces JSONified string of the value, without surrounding quotes"""
    if val is None or isinstance(val, jinja2.Undefined):
        return "null"
    js = json_filter(val)
    return js[1:-1] 
Example #29
Source File: utils.py    From intake with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _j_passthrough(x, funcname):
    if isinstance(x, Undefined):
        x = x._undefined_name
    return "{{%s(%s)}}" % (funcname, x) 
Example #30
Source File: utils.py    From intake with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _j_getshell(x):
    if isinstance(x, Undefined):
        x = x._undefined_name
    try:
        return subprocess.check_output(x).decode()
    except (IOError, OSError):
        return ""