Interpret name with nested string - jinja2

I'm trying to read my conda-forge recipe:
from jinja2 import Environment, BaseLoader
text = """
{% set name = "foo" %}
requires:
- {{ name }}
- {{ compiler('c') }}
"""
rtemplate = Environment(loader=BaseLoader).from_string(text)
data = rtemplate.render(**{"compiler('c')": "foo"})
print(data)
but the (illegal?) field {{ compiler('c') }} throws:
Traceback (most recent call last):
File "/Users/tdegeus/data/prog/src/conda_envfile/t.py", line 14, in <module>
data = rtemplate.render(**{"compiler('cxx')": "foo"})
File "/Users/tdegeus/miniforge3/envs/test/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
self.environment.handle_exception()
File "/Users/tdegeus/miniforge3/envs/test/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "<template>", line 6, in top-level template code
File "/Users/tdegeus/miniforge3/envs/test/lib/python3.10/site-packages/jinja2/utils.py", line 83, in from_obj
if hasattr(obj, "jinja_pass_arg"):
jinja2.exceptions.UndefinedError: 'compiler' is undefined
Can I solve this with jinja2, or do I need to do pre-processing?

Related

How do I create an attribute dynamically while using yattag?

This is the part of 'data' in the code below:
{'element': 'background', 'x': 0, 'y': 0, 'width': 800, 'height': 898, 'properties': {'background-color': '#ffffff'}}
The code:
for i in data:
print(i)
if i['element'] in comp:
ta = i['element']
if i['properties']:
prop_keys = list(i['properties'].keys())
background = "green"
for j in range(len(prop_keys)):
attri = prop_keys[j]
print(type(attri))
val = i['properties'][prop_keys[j]]
print(type(val))
doc, tag, text = Doc().tagtext()
exec('with tag(ta, %s = %s)'%(attri,val))
break
The error that I am getting:
Traceback (most recent call last):
File "/home/harsh/.virtualenvs/py3/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3418, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-78-69185a93c0dd>", line 19, in <module>
exec('with tag(ta, %s = %s)'%(attri,val))
File "<string>", line 1
with tag(ta, background-color = #ffffff)
^
SyntaxError: unexpected EOF while parsing
I basically want to use value of 'attri' as the name of attribute in the yattag to make it dynamic.
I tried using 'exec' function to put in the values to convert the json data into html using yattag but the yattag library doesn't allow to use expression in place of variable name to make it dynamic.

TypeError: Object of type Decimal is not JSON serializable | Django

I am getting quite unusual error. I got pretty confused because of this. When I iterate over the cart items and try to view them it throws a TypeError Object of type Decimal is not JSON serializable. But if i remove the block from my templates then refresh the page and again add the same block to my templates and refresh the page it works. I have added some screenshots. Please have a look and help me out with this
cart.py
class Cart(object):
def __init__(self, request):
"""
Initialize the cart
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# save an empty cart in the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, quantity=1, override_quantity=False):
"""
Add a product to the cart or update its quantity
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {
'quantity': 0,
'price': str(product.price)
}
if override_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def __iter__(self):
"""
Iterate over the items in the cart
and get the products from the database
"""
product_ids = self.cart.keys()
# get the product objects and add the o the cart
products = Product.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def get_total_price(self):
"""
Calculate the total cost of the items in the cart
"""
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
orders.py
def order_create(request):
cart = Cart(request)
order = None
address_form = AddressCheckoutForm()
billing_address_id = request.session.get('billing_address_id', None)
shipping_address_id = request.session.get('shipping_address_id', None)
order, created = Order.objects.get_or_create(user=request.user, ordered=False)
if shipping_address_id:
shipping_address = Address.objects.get(id=shipping_address_id)
order.shipping_address = shipping_address
del request.session['shipping_address_id']
if billing_address_id:
billing_address = Address.objects.get(id=billing_address_id)
order.billing_address = billing_address
del request.session['billing_address_id']
if billing_address_id or shipping_address_id:
order.save()
if request.method == 'POST':
for item in cart:
OrderItem.objects.create(
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity']
)
order.ordered = True
order.save()
cart.clear()
return render(request, 'orders/order/created.html', {'order': order})
return render(request, 'orders/order/create.html', {'cart': cart, 'address_form': address_form, 'object': order})
create.html
<h1>Checkout</h1>
{% if not object.shipping_address %}
<h3>Shipping</h3>
{% url "addresses:checkout_address_create" as checkout_address_create %}
{% include 'address/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %}
{% elif not object.billing_address %}
<h3>Billing</h3>
{% url "addresses:checkout_address_create" as checkout_address_create %}
{% include 'address/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='billing' %}
{% else %}
{% for item in cart %}
{{ item.quantity }} X {{ item.product.name }}
{{ item.total_price }}
{% endfor %}
<p>Total Price: {{ cart.get_total_price }}</p>
<form action="" method="POST">
{% csrf_token %}
<p><input type="submit" value="Place Order"></p>
</form>
{% endif %}
Traceback
Internal Server Error: /order/create/
Traceback (most recent call last):
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__
response = self.process_response(request, response)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/middleware.py", line 58, in process_response
request.session.save()
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 83, in save
obj = self.create_model_instance(data)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 70, in create_model_instance
session_data=self.encode(data),
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 105, in encode
serialized = self.serializer().dumps(session_dict)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/core/signing.py", line 87, in dumps
return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
return cls(
File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.8/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable
[29/Jul/2020 14:20:17] "GET /order/create/ HTTP/1.1" 500 102125
The error
code block that is raising the error
removing the block
after removing the block and refreshing the page
adding the block again
after adding the block and refreshing the page
As you can see before removing the code block the error is there, after removing it and refreshing the page and adding the code block back to the templates and refreshing the page again seems to work fine. Can you please help me out with this?
The problem here at this line
for product in products:
cart[str(product.id)]['product'] = product
product's instance has a decimal field, the price field, which is not JSON serializable.
So to solve this error, you can add explicitly the product's fields, you want to use in the template, into the session data to loop over.
For instance:
cart[str(product.id)]['product_name'] = product.name
cart[str(product.id)]['product_price'] = float(product.price)
and for the price field, instead of converting it into Decimal, you can use float:
for item in cart.values():
item['price'] = float(item['price'])

Sqlalchemy class _MatchType(sqltypes.Float, sqltypes.MatchType): AttributeError

sometimes execute query and got this error:
ct = db.session.query(CIType).filter(
CIType.type_name == key).first() or \
db.session.query(CIType).filter(CIType.type_id == key).first()
full error info
2016-08-11 14:27:26,177 ERROR /usr/lib/python2.6/site-packages/flask/app.py 1306 - Exception on /api/v0.1/projects/search-indexer-rafael/product [GET]
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/data/webapps/cmdb-api/core/special.py", line 175, in get_project_product
product = ProjectManager().get_for_product(project_name)
File "/data/webapps/cmdb-api/lib/special/project.py", line 18, in __init__
self.ci_type = CITypeCache.get("project")
File "/data/webapps/cmdb-api/models/cmdb.py", line 458, in get
ct = db.session.query(CIType).filter(
File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/scoping.py", line 149, in do
def do(self, *args, **kwargs):
File "/usr/lib64/python2.6/site-packages/sqlalchemy/util/_collections.py", line 903, in __call__
item = dict.get(self, key)
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 201, in __init__
bind=db.engine,
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 754, in engine
return self.get_engine(self.get_app())
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 771, in get_engine
return connector.get_engine()
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 451, in get_engine
self._engine = rv = sqlalchemy.create_engine(info, **options)
File "/usr/lib64/python2.6/site-packages/sqlalchemy/engine/__init__.py", line 344, in create_engine
of 0 indicates no limit; to disable pooling, set ``poolclass`` to
File "/usr/lib64/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 50, in create
File "/usr/lib64/python2.6/site-packages/sqlalchemy/engine/url.py", line 116, in get_dialect
return self.get_dialect().driver
File "/usr/lib64/python2.6/site-packages/sqlalchemy/util/langhelpers.py", line 170, in load
fn.__func__.__doc__ = doc
File "/usr/lib64/python2.6/site-packages/sqlalchemy/dialects/__init__.py", line 33, in _auto_fn
try:
File "/usr/lib64/python2.6/site-packages/sqlalchemy/dialects/mysql/__init__.py", line 8, in <module>
from . import base, mysqldb, oursql, \
File "/usr/lib64/python2.6/site-packages/sqlalchemy/dialects/mysql/base.py", line 681, in <module>
class _MatchType(sqltypes.Float, sqltypes.MatchType):
AttributeError: 'module' object has no attribute 'MatchType'
code
#special.route("/api/v0.1/projects/<string:project_name>/product",
methods=["GET"])
def get_project_product(project_name):
product = ProjectManager().get_for_product(project_name)
return jsonify(product=product)
...
goto
class ProjectManager(object):
def __init__(self):
self.ci_type = CITypeCache.get("project")
...
then
class CITypeCache(object):
#classmethod
def get(cls, key):
if key is None:
return
ct = cache.get("CIType::ID::%s" % key) or \
cache.get("CIType::Name::%s" % key)
if ct is None:
ct = db.session.query(CIType).filter(
CIType.type_name == key).first() or \
db.session.query(CIType).filter(CIType.type_id == key).first()
if ct is not None:
CITypeCache.set(ct)
return ct
The sqlalchemy's version is SQLAlchemy-1.0.8-py2.6.egg-info
and after many same error, I can't catch this error any more. What's the reason of this error?
I assume CIType.type_name and CIType.type_id have different data types (perhaps string and numeric types). It may lead to situation when:
db.session.query(CIType).filter(CIType.type_name == key).first()
is valid expression but:
db.session.query(CIType).filter(CIType.type_id == key).first()
produces error because of type mismatch. You need to convert key to the type_id column type in this expression.
The second expression is calculated when first expression returns no results. As written in Python documentation:
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
For example:
>>> a = 1 or 2 + '2'
>>> print a
1
>>> a = 0 or 2 + '2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Python Return a list in Bottle

I have a list from an mysql query that I'm trying to return in my bottle website. Is this possible? Here's what I have:
def create_new_location():
kitchen_locations = select_location()
return template('''
% for kitchen_location in {{kitchen_locations}}:
{{kitchen_location}} Kitchen
<br/>
% end''',kitchen_locations=kitchen_locations)
This is the error that I get.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "index.py", line 32, in create_new_location
</form>''',kitchen_locations=kitchen_locations)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3609, in template
return TEMPLATES[tplid].render(kwargs)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3399, in render
self.execute(stdout, env)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3386, in execute
eval(self.co, env)
File "<string>", line 6, in <module>
TypeError: unhashable type: 'set'
Got It (took me a while...)
% for kitchen_location in {{kitchen_locations}}:
Should be
% for kitchen_location in kitchen_locations:
When using the % at the beginning you don't need the {{}}.
This error:
TypeError: unhashable type: 'set'
is trying to use a set literal {{kitchen_locations}} ==>
kitchen_locations in a set in another set. since set is not hash-able you got the error

Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)

Hello I live in Poland so I have to deal with letters like łóźć etc. When I try to add, in admin pannel, text like "Zespół Szkół" I get error like this:
Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode
characters in position 4-5: ordinal not in range(128)
I seen on Stackoverflow page many of similar problem but I don't have any idea how to solve my.
My Databse is MySQL
Unicode collection for my db: utf8_unicode_ci
My models.py
# -*- coding: utf-8 -*-
from django.db import models
import codecs
...
class experience(models.Model):
dateStart = models.DateField()
dateEnd = models.DateField()
company = models.CharField(max_length=50)
position = models.CharField(max_length=50)
description = models.TextField(max_length=255)
def __unicode__(self):
return self.company.decode('utf8')
...
Traceback
Request Method: GET
Request URL: http://vm:8000/admin/mycv/experience/
Django Version: 1.3.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'cv.mycv']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template error:
In template /usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/admin/change_list.html, error at line 97
Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)
87 : {% endif %}
88 : {% endblock %}
89 :
90 : <form id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>{% csrf_token %}
91 : {% if cl.formset %}
92 : <div>{{ cl.formset.management_form }}</div>
93 : {% endif %}
94 :
95 : {% block result_list %}
96 : {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %}
97 : {% result_list cl %}
98 : {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %}
99 : {% endblock %}
100 : {% block pagination %}{% pagination cl %}{% endblock %}
101 : </form>
102 : </div>
103 : </div>
104 : {% endblock %}
105 :
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
197. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in changelist_view
1179. ], context, context_instance=context_instance)
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
188. return t.render(context_instance)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
123. return self._render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in _render
117. return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
127. return compiled_parent._render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in _render
117. return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
127. return compiled_parent._render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in _render
117. return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
64. result = block.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
64. result = block.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
921. dict = func(*args)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in result_list
232. 'results': list(results(cl))}
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in results
217. yield ResultList(None, items_for_result(cl, res, None))
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in __init__
209. super(ResultList, self).__init__(*items)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in items_for_result
137. f, attr, value = lookup_field(field_name, result, cl.model_admin)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/util.py" in lookup_field
218. value = attr()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py" in __str__
377. return force_unicode(self).encode('utf-8')
File "/usr/local/lib/python2.6/dist-packages/django/utils/encoding.py" in force_unicode
71. s = unicode(s)
File "/home/lechu/apps/cv/../cv/mycv/models.py" in __unicode__
31. return self.company.decode('utf8')
File "/usr/lib/python2.6/encodings/utf_8.py" in decode
16. return codecs.utf_8_decode(input, errors, True)
Exception Type: TemplateSyntaxError at /admin/mycv/experience/
Exception Value: Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)
104 : {% endblock %}
105 :
Traceback:
File
Your __unicode__ method is unfortunately nonsense.
decode is for converting bytestrings to unicode, but self.company is already unicode. So calling decode('utf-8') on it means that Python has to implicitly encode it to a bytestring first, which it does by the default ascii encoding - which will fail as soon as you have any accented characters.
I don't know what you were trying to do with that method, but __unicode__ methods should always return unicode. Just return self.company is the correct thing to do here.