While parsing json and viewing html source code it shows 10K lines - json

I am parsing json in Django Views with following code:
def xyz(request):
url =" https://tools.vcommission.com/api/coupons.php?apikey=952d164efe86ca9ec33a1fdac8e6d0b6d4c02c92f44062bf8b646ad04ebf8cdc "
response = urllib.request.urlopen(url)
data1 = json.loads(response.read())
context = {"data1": data1}
template = 'coupons/store/myntra.html'
return render(request, template, context)
Now I am using this code in my template file
{% for item in data1 %}
{% if item.offer_id == "1022" %}
{{ item.coupon_title }} <br>
{% endif %}
{% endfor %}
All code is working fine but when I view my template html source code it is more than 10K lines.
It's taking more time to load.
Please suggest some ways.

Related

django grpc json response to html template

need some help. Spent all day trying different permutations to no avail.
I am making a grpc call and formatting the response to a json. My goal is to pass the data onto my html template so I can format it how I want. The only thing I can get to work is to print the json on the page which is not what I want.
return JsonResponse(result, safe=False)
^ this prints json on page but I actually want to populate certain parts to a table.
I tried the following (not all at once obviously):
return HttpResponse(branch_list)
return HttpResponse(response, 'src/grpc.html', {'branch_list', branch_list})
return HttpResponse(response, 'src/grpc.html', {'branch_list',branch_list})
return render(request, 'src/grpc.html', {'branch_list': response})
return JsonResponse(result, safe=False)
return HttpResponse(json.dumps(branch_list), 'src/grpc.html', content_type="application/json")
This is my definition I am using in my views.py which works with the return statement
I pasted above:
...
def grpc(client_stub, payload_project_id=payload_project_id, grpc_stub_method=grpc_stub_method, metadata_okta_token_and_env=metadata_okta_token_and_env):
client_stub = BitcClient(server, port)
request = pb2.ListBranchesRequest(context=payload_project_id)
response = client_stub.get_grpc_stub(grpc_stub_method).ListBranches(request=request,
metadata=metadata_okta_token_and_env)
#print(response)
json_obj = MessageToJson(response)
result = json.loads(json_obj)
for data in result['branches']:
# print(data['branch'])
branch_list.append(data['branch'])
return <need help here>??????????
I would like to loop through branch_list in my html template and sprint the branch name and branch status in a table in grpc.html template:
{% if branch_list %}
<ul>
{% for branch in branch_list %}
<li>{{ branch.branch }}: {{ branch.status }}</li>
{% endfor %}
</ul>
{% else %}
<p>No branches were found.</p>
{% endif %}
my urls.py looks like this:
from django.urls import path
from . import views
urlpatterns = [
path('', views.grpc, name='grpc'),
]
help is greatly appreciated. thanks
So the correct return line needs to be: return render(request, 'src/grpc.html', result)

Dictionary in jinja and flask to retrieve JPG/PNG image from base64 format

I want to display image in HTML page from the base64n string using flask and jinja template.
image_64 = base64.encodestring(image_read).decode("ascii")
output = {"username":username, "email": email, "Base64 Image": image_64}
return render_template('display.html', result = output)
I want to display dictionary value as image if the key is "Base64 Image". else display only the values.
what I tried is:
{% for key, value in result.items() %}
<p> {{ key }} </p>
{% if result['Base64 Image'] != "" %}
<img src="data:image/jpg;base64,{{ value }}" alt="my_image" id="img"/> </img><br>
{% else %}
<p> {{ value }} </p><br>
{% endif %}
{% endfor %}
One thing you can try to save the image in a dir and load the image in your desired format.
to save image you can try:
#app.route('/api/scaning', methods=['GET'])
def scan_qr():
img = request.files['img']
## save image
img .save("temp_dir/"+img.filename)
## load Image
img = cv2.imread(f"temp_dir/{img.filename}")
return_value = MyModel.det_qr(img)
return return_value

Flask, jinja2 - Dynamically append templates one after another

I am building a chatbot. There are few child templates like login.html, messages.html, transaction.html, etc. I want to append these templates in base.html dynamically. I am extending base.html in all these templates. My problem is only one template is rendered at a time. Is there any solution for appending these templates one after another? I have used {%include%} but it's a static approach. I need dynamic.
printer.py looks like -
#app.route('/respond', methods=['GET','POST'])
def respond_def():
message = request.form['message_input']
if message == "l":
return render_template('printer/login.html')
elif message == "t":
return render_template('printer/transactionID.html')
base.html looks like -
//some code here
<li>
{% block template %}{% endblock %}
</li>
//some code here
message.html looks like -
{% extends "base.html" %}
{% block template %}
<div> Message template called </div>
{% endblock %}
I resolved it.
I made a list of templates in printer.py and then appended those templates in base.html whenever user asked for it.
printer.py
dictionary = []
// append name of template in this whenever needed.
return render_template('printer/base.html', dictionary=dictionary)
base.html
{% for d in dicts %}
{% set template = 'printer/' + d + '.html' %}
// can add conditions for different templates
{% include template %}
{% endfor %}

Source Code in iframe?

For my website, I have little code files to download, such as python (.py) files. I have the <a> tags for the downloads, but would like to display the source code before downloading it. On hover, I can display an iframe, but am having trouble getting the code to display.
FYI: I am using github pages for everything, and the files are in the site repo.
Jekyll code for the DL list.
<ul class="dl-display">
<!-- get the folder name that the index..html file is contained in -->
{% assign path_array = page.path | split: '/' %}
{% assign path_array_rev = path_array | reverse %}
{% assign page_dir = path_array_rev[1] | prepend: '/'%}
{% for item in site.static_files %}
{% if item.path contains page_dir %}
{% unless item.path contains 'index.html' %}
{% assign split_path = item.path | split: '/' %}
{% assign filename = split_path.last %}
{% assign rev_split_path = split_path | reverse %}
{% assign dirname = rev_split_path[1] %}
{% unless item.path contains '.txt' %}
<li><a href="{{site.baseurl}}{{item.path}}" download>{{filename}} <iframe id="sourcetooltip" src='{{item.path}}'></iframe></a></li>
{% endunless %}
{% if item.path contains 'description.txt' %}
<iframe src='{{item.path}}' scrolling='no' frameborder='0'></iframe>
{% endif %}
{% endunless %}
{% endif %}
{% endfor %}
</ul>
Sorry if the code is a bit messy, as I am still pretty new to web development.
The code that displays the iframe when filename is description works perfectly and displays the text.
In the unless block, the file begins to download. Is there any way to display the .py files like the txt files are displayed instead of downloading them?
Sorry if I'm not clear, its my first time with HTML, CSS, JS, and whatever else is used in web development.
Try using the iframe attribute srcdoc. It's value can be a whole page of HTML without investing time into a separate page.
SNIPPET
<iframe id='ifrm1' name='ifrm1' srcdoc="
<style>
section {
padding:5px;
background: rgba(0,0,0,.6);
}
code {
font:400 12px/.6 Consolas;
background: rgba(0,0,0,.8);
color: lime;
padding:5px;
}
</style>
<section>
<pre><code>
import urllib2
import urllib
import json
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
query = raw_input('What do you want to search for ? >> ')
query = urllib.urlencode( {'q' : query } )
response = urllib2.urlopen (url + query ).read()
data = json.loads ( response )
results = data [ 'responseData' ] [ 'results' ]
for result in results:
title = result['title']
url = result['url']
print ( title + '; ' + url )
</code></pre>
</section>" width='100%' frameborder='0'></iframe>

passing data json using django templates to the front (html)

I have a problem to send json data using django templates to the front (html).
This is the python code:
#api_view(['GET'])
#renderer_classes((JSONRenderer,))
def tasks_list_all(request):
i = inspect()
tasks_dic=i.registered_tasks()
for cle in tasks_dic.keys():
key=cle
tasks_old_v=tasks_dic.get(key)
tasks_new_v=[]
for tasks in tasks_old_v:
new_tasks=tasks.replace('infra_mngt.tasks.','')
tasks_new_v.append(new_tasks)
add_new=tasks_new_v[-1].replace('provisionning.celery.','')
tasks_new_v[-1]=add_new
tasks_new_v_new=json.dumps(tasks_new_v)
print "json.dumps(tasks_new_v)",tasks_new_v_new
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'), context={'list':tasks_new_v})
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v})
return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v_new})
this is the code of the front (tasks_all.html):
<h1>Dynamic list tasks</h1>
{% for list in tasks_new_v_new %}
{{ list }}
{% endfor %}
But after execution, I don't get any elements of the list that I need, just the display of this html code:
<h1>Dynamic list tasks</h1>
you're passing the wrong context to the template (or you're using the wrong variable in the template)
try something like (in the view):
return render(request, your_template, {"tasks": tasks_new_v_new})
in the template:
{% for task in tasks %}
{{ task }}
{% endfor %}
notice I'm passing a variable called tasks to the template and in the template I'm looping that variable.
Hope this helps