There is a file api.yml containing a config for ansible:
config/application.properties:
server.port: 6081
system.default.lang: rus
api.pdd.url: "http://{{ stage['PDD'] }}"
api.policy.alias: "integration"
api.order.url: "http://{{ stage['Order'] }}
api.foo.url: "http://{{ stage['FOO'] }}
There is a stage.yml containing the key and the stage values:
default_node:
Order: '172.16.100.40:8811'
PDD: '172.16.100.41:8090'
FOO: '10.100.0.11:3165
In fact, these files are larger and the 'stage' variables are also many.
My task is to parse api.yml and turn it into properties-config. The problem is that I can not pull up the values {{stage ['value']}} I'm trying to do it this way:
stream = yaml.load(open('api.yml'))
result={}
result.update(stream['config/application.properties'])
context= yaml.load(open('stage.yml'))
stage={}
stage.update(context['default_node'])
text = '{% for items in result | dictsort(true)%} {{ items[0] }} = {{
items[1] }} {%endfor%}'
template = Template(text)
properti = (template.render(result=result, stage=stage))
At the output I get this:
server.port = 6081
system.default.lang = rus
api.pdd.url = http://{{ stage['PDD'] }}
api.policy.alias = integration
api.order.url = http://{{ stage['Order'] }}
api.foo.url = http://{{ stage['FOO'] }}
And you need to get this:
server.port = 6081
system.default.lang = rus
api.pdd.url = 172.16.100.41:8090
api.policy.alias = "integration"
api.order.url = 172.16.100.40:8811
api.foo.url = 10.100.0.11:3165
Can I do it with jinja or ansible lib?
Sorry for my bad english
Following this approach, you would need to treat api.yml as a template itself and render it. Otherwise, jinja2 will treat it as a simple value of the property. Something like this would do:
import yaml
from jinja2 import Environment, Template
import json
stream = yaml.load(open('api.yml'))
result={}
result.update(stream['config/application.properties'])
context= yaml.load(open('stage.yml'))
stage={}
stage.update(context['default_node'])
text = """{% for items in result | dictsort(true)%} {{ items[0] }} = {{ items[1] }} {%endfor%}"""
#Then render the results dic as well
resultsTemplate = Template(json.dumps(result))
resultsRendered = json.loads( resultsTemplate.render(stage=stage) )
template = Template(text)
properti = (template.render(result=resultsRendered, stage=stage))
After this you will see the wanted values in the properti var:
' api.foo.url = http://10.100.0.11:3165 api.order.url = http://172.16.100.40:8811 api.pdd.url = http://172.16.100.41:8090 api.policy.alias = integration server.port = 6081 system.default.lang = rus'
It would be nice though if jinja2 was able to render recursively. Maybe spending some time working out with the globals and shared modes of the Environment this can be achieved.
Hope this helps.
Related
Why cant i acsess the dict that i am making here:
def kalkuler(request):
fotlister = Produkt.objects.filter(under_kategori__navn__iexact="lister")
kalkuler = ProduktKalkureing.objects.all()
beregning = {}
if request.method == "POST":
omkrets = request.POST['omkrets']
print(omkrets)
for i in kalkuler:
kalk = math.ceil((int(omkrets)/i.lengde)*1000)
add = ({'produkt_tittel': i.produkt.produkt_tittel,
'produkt_bilde': i.produkt.produkt_bilde,
'produkt_info': i.produkt.produkt_info,
'produkt_link': i.produkt.produkt_link,
'pris_heltall': i.produkt.pris_heltall,
'antall_kalk': kalk,
'total_kost': kalk * i.produkt.pris_heltall
})
beregning.update(add)
print(beregning)
context = {'kalkuler': kalkuler, 'beregning': beregning}
return render(request, 'frontend/kalkuler/fotlist_kalkuler.html', context)
With the standard django code?
{% for b in beregning %}
{{b.produkt_bilde}}
{% endfor %}
Also when i make the dictionary it only adds the last value. How do i make it so it adds every value.
For what you seem to achieve, you need a list instead of a dict
def kalkuler(request):
...
beregning = []
...
beregning.append(add)
...
I am unsure how should I used base64 to encode and decode my image, as well as where should I place the codes for encoding and decoding at. I am also unsure of how should I display it in Jinja Html.
I have already tried encoding my image but I am unsure whether I did the right way or not. I have also tried to decode it but it can seem to run my program.
main.py
#app.route('/camera', methods = ['GET', 'POST'])
def camera():
``list = []
``with shelve.open('PerStorageCamera.db') as d:
`enter code here`for key in d:
`enter code here`for i in d[key]:
`enter code here`list.append(i)
``form = FormSelect1(request.form)
``form1 = FormSelect2(request.form)
``location_data = form.location.data
``return render_template('camera.html', form=form, form1 = form1, location_data = location_data, list = list)
part of my codes for my class
``class Cameras:
``wdlands = []
``def __init__(self, location, camera):
``self.__location = location
``self.__camera = camera
``self.add()
``def get_location(self):
``return self.__location
``def get_camera(self):
``return self.__camera
``def add(self):
``if self.__location == 'wdlands':
``self.__class__.wdlands.append(self)
objects created to append into persistent storage
wdlands1 = Cameras('wdlands', 'Woodlands Causeway (Towards Johor)')
wdlands2 = Cameras('wdlands', 'Woodlands Checkpoint (Towards BKE)')
.html
``{% for i in list %}
``{% if location_data == "wdlands" %}
{% if i.get_location() == "wdlands" %}
<tr><th>Camera: </th><td>{{ i.get_camera() }}</td></tr>
``<form action= "http://localhost:5000/myjourney" method= "get">
{{ form.submit }}
``</form>
``<br>
``{% endif %}`
I am expecting to have different images for each of my objects that is appended into the persistent storage
I've already written a script that parses JSON data from a particular url and stores them into a list. After that I'm able to pass that as an argument to be displayed in my template.
My end goal is to display a table on the template from this JSON data (of which I have currently included only one parameter), for which I believe I need to pass that list into a Django Model.
def index(request):
is_cached = ('raw_json' in request.session)
print(is_cached)
if not is_cached:
# g = {'starttime': '2014-01-01', 'endtime': '2014-01-02', 'minmagnitude': '5'}
g=''
url1 = ul.urlencode(g)
# print(url1)
main_api = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&'
final_url = main_api + url1
# print(final_url)
raw_json = requests.get(final_url).json()
string_json = json.dumps(raw_json)
# print(raw_json)
with open('test.txt', 'w') as file:
file.write(string_json)
count = raw_json['metadata']['count']
print('Count: ' + str(count))
maglist = []
placelist = []
for cou in range(0, count):
mag = (raw_json['features'][cou]['properties']['mag'])
maglist.append(mag)
# magdict = dict(list(enumerate(maglist)))
place = (raw_json['features'][cou]['properties']['place'])
placelist.append(place)
# placedict = dict(list(enumerate(placelist)))
# print(placedict)
with open('test2.txt', 'w+') as t1:
for features in raw_json['features']:
coordinates = (features['geometry']['coordinates'])
id = (features['id'])
t1.write("id: %s \n" % (id))
t1.write("coordinates: %s \n" % (coordinates))
# print(singfeature)
for properties, value in features['properties'].items():
t1.write("%s : %s \n" % (properties, value))
# t1.write("\n")
# print (maglist)
args = {'magni': maglist}
print (args)
return render(request, 'earthquake/index.html', args)
The template receives this data with a simple for loop as follows:
{% block content %}
{% for item in magni %}
<p>{{ item }}</p>
{% endfor %}
{% endblock %}
To which the result shows up as follows:
As mentioned previously, I need to display a filterable/sortable table with this parameter (along with other parameters too), so that the end-user may view the data as needed.
I'm quite new to Django.
I am writing a custom test case for Django-Mptt template tag . Eveything is working fine but the json I am getting is not valid .
this is the template string I am sending :
self.template = re.sub(r'(?m)^[\s]+', '', '''
{% load yctags %}
[
{% recursetree_custom comments comment_order %}
{
"comment_id": "{{ node.id }}",
"comment_text": "{{ node.text }}",
"comment_parent_id": "{{ node.parent.id }}",
"children": [
{% if not node.is_leaf_node %}
{{ children }}
{% endif %}
]
}
{% endrecursetree %}
]''')
output :
[{"comment_id": "2","comment_text": "2nd comment","comment_parent_id": "","children": [{"comment_id": "7","comment_text": "2nd comment , 2nd child","comment_parent_id": "2","children": []}{"comment_id": "6","comment_text": "2nd comment , ist child","comment_parent_id": "2","children": []}]}{"comment_id": "1","comment_text": "Ist comment","comment_parent_id": "","children": [{"comment_id": "3","comment_text": "Ist comment , ist child","comment_parent_id": "1","children": [{"comment_id": "5","comment_text": "1-1-2","comment_parent_id": "3","children": []}{"comment_id": "4","comment_text": "1-1-1","comment_parent_id": "3","children": []}]}]}]
If u use any json validator for above o/p then u will know about my error in json output , there must be a comma b/w to comments to make it valid.
Please let me know the solution how I can make this json valid
the solution is join comments by comma ','
def _render_node(self, context, node):
# print "node-> ",node
bits = []
context.push()
#print "context->", context
for child in node.get_children():
bits.append(self._render_node(context, child))
context['node'] = node
context['children'] = mark_safe(','.join(bits)) **#join by ,**
rendered = self.template_nodes.render(context)
context.pop()
return rendered
def render(self, context):
queryset = self.queryset_var.resolve(context)
comment_order = self.order.resolve(context)
roots = cache_tree_children(queryset, comment_order)
# print "roots-> ", roots
bits = [self._render_node(context, node) for node in roots]
# print bits
return ','.join(bits) **#join by ,**
Is there any way to do this with jinja2?
template = Template("{{ var1 }}{{ var2 }}")
rendered1 = template.render(var1=5) # "5-{{ var2 }}"
rendered2 = Template(rendered1).render(var2=6) # "5-6"
basically, I want to be able to do multiple passes on a template. When the template engine finds a variable in the template that is not in the context, instead of replacing it with nothing, keep the template variable intact? If not jinja2, is there any other python template library that can do this?
You can use DebugUndefined, which keeps the failed lookups, as your Undefined Type for the undefined parameter of the Template environment:
>>> from jinja2 import Template, DebugUndefined
>>> template = Template("{{ var1 }}-{{ var2 }}", undefined=DebugUndefined)
>>> rendered1 = template.render(var1=5) # "5-{{ var2 }}"
>>> print(rendered1)
5-{{ var2 }}
>>> rendered2 = Template(rendered1).render(var2=6) # "5-6"
>>> print(rendered2)
5-6