Exemple #1
0
    def _render_query(query, parameters):
        """
        Render both jinja or %()s templates in query
        while keeping type of parameters
        """
        if isinstance(query, dict):
            return {key: _render_query(value, parameters) for key, value in deepcopy(query).items()}
        elif isinstance(query, list):
            return [_render_query(elt, parameters) for elt in deepcopy(query)]
        elif isinstance(query, str):
            if not _has_parameters(query):
                return query

            # Replace param templating with jinja templating:
            query = re.sub(RE_PARAM, r'{{ \g<1> }}', query)

            # Add quotes to string parameters to keep type if not complex
            clean_p = deepcopy(parameters)
            if re.match(RE_JINJA_ALONE, query):
                clean_p = _prepare_parameters(clean_p)

            env = NativeEnvironment()
            res = env.from_string(query).render(clean_p)
            # NativeEnvironment's render() isn't recursive, so we need to
            # apply recursively the literal_eval by hand for lists and dicts:
            if isinstance(res, (list, dict)):
                return _prepare_result(res)
            return res
        else:
            return query
Exemple #2
0
def cart_render_portal():
    product = request.args.get('product')
    e = NativeEnvironment()
    t = e.from_string(product)
    product = t.render() # product is product added to cart by the customer
    username = request.args.get('username')
    return render_template('cart.html', product=product, username=username, error = False)
Exemple #3
0
def purchase():
    product = request.args.get('product')
    e = NativeEnvironment()
    t = e.from_string(product)
    product = t.render()  # converting the string to native python type (dictionary)
    username = request.args.get('username')
    return render_template('purchase.html', product=product, error = False, username=username)
Exemple #4
0
class TemplateExpander(object):
    """Object to expand templates found as strings in structured data
    """

    def __init__(self, base_uri):
        self.ctx = {
            'env': os.environ,
            'load_spec': lambda uri, *args, **kwargs: load_spec(uri, base_uri, *args, **kwargs)
        }
        self.env = NativeEnvironment()
        self.env.filters['eval'] = eval

    def __call__(self, node, seen=None):
        if seen is None:
            seen = {}
        if id(node) in seen:
            return node
        elif isinstance(node, list):
            return [self(n, seen) for n in node]
        elif isinstance(node, dict):
            return {
                self(k, seen): self(v, seen)
                for k, v in node.items()
            }
        elif isinstance(node, str):
            if re_template_metacharacters.search(node):
                t = self.env.from_string(node)
                return t.render(self.ctx)
            else:
                return node
        return node
Exemple #5
0
class TemplateExpander(object):
    """Object to expand templates found as strings in structured data
    """
    def __init__(self, base_uri):
        self.ctx = {
            'env':
            os.environ,
            'load_spec':
            lambda uri, *args, **kwargs: load_spec(uri, base_uri, *args, **
                                                   kwargs)
        }
        self.env = NativeEnvironment()
        self.env.filters['eval'] = eval

    def __call__(self, node, seen=None):
        if seen is None:
            seen = {}
        if id(node) in seen:
            return node
        elif isinstance(node, list):
            return [self(n, seen) for n in node]
        elif isinstance(node, dict):
            return {self(k, seen): self(v, seen) for k, v in node.items()}
        elif isinstance(node, str):
            if re_template_metacharacters.search(node):
                t = self.env.from_string(node)
                return t.render(self.ctx)
            else:
                return node
        return node
Exemple #6
0
def jinja(template, _env=None, **data):
    """Recursively renders a python dict, list or str, evaluating strings
    along the way"""
    kwargs = deepcopy(config.variables)
    kwargs.update(data)

    if _env is None:
        _env = NativeEnvironment(loader=BaseLoader, undefined=DebugUndefined)

    return _env.from_string(str(template)).render(**kwargs, json=json)
Exemple #7
0
def purchase_tentative():
    username = request.args.get('username')
    product = request.args.get('product')
    qty = request.form.get('quantity')
    if qty == "":
        qty = 1
    if qty == '0':
        return render_template('purchase.html', username = username, product = product, error = True)
    e = NativeEnvironment()
    t = e.from_string(product)
    product = t.render()
    product["total_cost"] = int(product["cost"])*int(qty)
    product["quantity"] = qty
    return render_template('purchase_confirmation.html', product=product, username=username)
Exemple #8
0
def add_to_cart(): # getting the quantity of items required and calculating the total cost
    username = request.args.get('username')
    product = request.args.get('product')
    qty = request.form.get('quantity')
    if qty == "":
        qty = 1
    if qty == '0':
        return render_template('cart.html', product=product, username=username, error = True)
    e = NativeEnvironment()
    t = e.from_string(product)
    product = t.render()
    product["customer_name"] = username
    product["total_cost"] = int(product["cost"])*int(qty)
    product["quantity"] = qty
    add_this_product_to_cart(product)
    return redirect(url_for('recent_products_customer', is_message=True, message="cart", username=username))
Exemple #9
0
def purchase_confirmation():
    username = request.args.get('username')
    product = request.args.get('product')
    product_cnt = request.args.get('product_cnt')
    cart_cost = request.args.get('cart_cost')
    e = NativeEnvironment()
    t = e.from_string(product)
    product = t.render()
    product["customer_name"] = username
    product["no_of_items_in_cart"] = int(product_cnt)

    if product["no_of_items_in_cart"] > 1: # this condition is used since items checked out from cart are stored as single nested dictionary
        product["cart_cost"] = cart_cost

    product["mode"] = request.args.get('mode')
    if product["mode"] == 'cart':
        product["cart_cost"] = request.args.get('cart_cost')
    
    generatebill(product, username) # generate bill
    return redirect(url_for('recent_products_customer', is_message=True, message="buy", username=username))
Exemple #10
0
def temp(swagger):
    app = Flask(__name__)

    func_template = """
{{ endpoint }}
def func_{{ func_postfix }}():
    {{ func_body }}
"""

    env = NativeEnvironment()

    i: int = 0
    for method in swagger.methods:
        i = i + 1
        func_body = generate_function_body(method)
        endpoint = f'@app.route("{method.path}, methods=[\'{method.method_name.upper()}\']")'
        result = env.from_string(func_template).render(endpoint=endpoint,
                                                       func_postfix=i,
                                                       func_body=func_body)
        #print(result)
        exec(result)

    return app
Exemple #11
0
def render_template(template_str, data):
    env = NativeEnvironment()
    t = env.from_string(template_str)
    return t.render(data)