Connexion/Flask/Jinja render template string as is - flask

I want to put an html in a string, NOT a file, like:
t = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>foo</title>
</head>
<body>
{{ script|safe }}
</body>
</html>
"""
script = ...
render_template_string(t, script=script)
However when I go to the actual webpage, I don't see an html page with a script, I see garbage:
"\n<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <title>foo</title>\n</head>\n\n<body>\n \n<script\n src=\"http://localhost:5006/bkapp/autoload.js?bokeh-autoload-element=ff639949-97c5-40b8-9cc2-28b78be802d1&bokeh-app-path=/bkapp&bokeh-absolute-url=http://localhost:5006/bkapp\"\n id=\"ff639949-97c5-40b8-9cc2-28b78be802d1\"\n data-bokeh-model-id=\"\"\n data-bokeh-doc-id=\"\"\n></script>\n</body>\n</html>"
How do I fix this?
EDIT: even a very simple
t = '{{ script|safe }}'
does not work, I get, in the browser:
"\n<script\n src=\"http://localhost:5006/bkapp/autoload.js?bokeh-autoload-element=07a43696-66af-4e54-a4e3-9a09ac242e38&bokeh-app-path=/bkapp&bokeh-absolute-url=http://localhost:5006/bkapp\"\n id=\"07a43696-66af-4e54-a4e3-9a09ac242e38\"\n data-bokeh-model-id=\"\"\n data-bokeh-doc-id=\"\"\n></script>"
EDIT 2: I have also tried
t = '{% autoescape false %}{{ script|safe }}{% endautoescape %}'
but that didn't work either.
I'm using Connexion if that matters.

Related

how to pass temporary decrypted data to django template

I have an application that can upload files in every format I want to be encrypted and saved to database I also created decrypt functionality but I dont know how to show this decrypted file to the user or django templates.
i have tried many ways like TemFile library but still I cant pass my decrypted data to the templates
here is my code for encryption
def encrypt (request):
if request.method == 'POST':
upload_file = request.FILES.get("like")
# key generation
key = Fernet.generate_key()
encode_key = urlsafe_base64_encode(force_bytes(key))
print(encode_key)
document = FileEncrypt.objects.create(document = upload_file,key=encode_key)
# using the generated key
fernet = Fernet(key)
# opening the original file to encrypt
with open(document.document.path, 'rb') as file:
original = file.read()
# encrypting the file
encrypted = fernet.encrypt(original)
with open(document.document.path, 'wb') as encrypted_file:
encrypted_file.write(encrypted)
document.save()
return redirect("decrypt_and_show", id=document.id)
else:
return render(request,"index.html",{
})
after redirecting to decrypt page it's not showing the file
here is my decrypt def
def decrypt(request,id):
document = FileEncrypt.objects.get(pk=id)
decode_key =force_text(urlsafe_base64_decode(document.key))
print(decode_key)
fernet = Fernet(decode_key)
# opening the encrypted file
with open(document.document.path, 'rb') as enc_file:
encrypted = enc_file.read()
# decrypting the file
decrypted = fernet.decrypt(encrypted)
tmpfile = tempfile.NamedTemporaryFile(delete=False,suffix='.JPEG')
tmpfile.seek(0)
tmpfile.write(decrypted)
return render(request,"index2.html",{
"d" : tmpfile.name
})
in my template is
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="{% static 'fileuploads/js/script.js' %}" defer></script>
</head>
<body>
<img src="{{d}}" />
</body>
</html>
in my index template is
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="{% static 'fileuploads/js/script.js' %}" defer></script>
</head>
<body>
<form action"" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="like" />
{% comment %} {{form}} {% endcomment %}
<button type="submit">Upload</button>
</form>
</body>
</html>
could you please help me with.

Embeding bokeh plot into a template (django)

I'm trying to embed a bokeh plot into a template (home.html), but nothing is displayed after executing the code.
here's the code.
views.py (all packages are imported)
def home(request):
s = [1,4,6,8]
h = [1,5,9,8]
p = figure(plot_width=600, plot_height=600)
p.vbar(x=s, width=0.5, bottom=0,
top=h, color="black")
script, div = components(p, CDN)
return render(request, 'home.html', {'div': div, 'script': script})
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Experiment with Bokeh</title>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">
</head>
<body>
<h1>hello</h1>
{{ div|safe }}
{{ script|safe }}
</body>
</html>
it displays nothing at the end, there's no error message, but and the page is completely blank
Help, Please!!
You are loading an ancient version of BokehJS from CDN:
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">
The 0.8.1 release is now several years old. By contrast, the vbar glyph method that you are using was only added quite recently. You need to make sure that the version of the BokehJS resources that you load in your template actually match the version of the Bokeh library that you are using.

django how to show images from my user directory

I am using linux and created a Django project.
I have folder in my home directory /home/simha/siteimages
i am trying to show a list of images from the above directory
In views.py
def gallery(request):
path="/home/simha/siteimages"
img_list =os.listdir(path)
return render(request,'blog/gallery.html', {'images': img_list})
gallery.html is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for image in images %}
<img src='/static/{{image}}' />
{% endfor %}
</body>
</html>
Its not working.
It says at img_list =os.listdir(path) error No such file or directory

Stuck with Test-Driven Development with Python (chapter 6) [duplicate]

I'm writing my first Django app by following along with this book:
http://chimera.labs.oreilly.com/books/1234000000754/ch05.html#_passing_python_variables_to_be_rendered_in_the_template
In the book there is a test that is verifying that the html is being returned as it is supposed to. Here is the test:
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('home.html')
print(expected_html)
print(response.content.decode())
self.assertEqual(response.content.decode(), expected_html)
My test is failing on the assertEqual test because I have added a csrf token in my HTML using the Django Template Language. Here is what my HTML page looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
{% csrf_token %}
</form>
<table id="id_list_table">
<tr><td>{{ new_item_list }}</td></tr>
</table>
</body>
</html>
My assert is failing due to the render_to_string method not including the token. Here is what my two print statements included in my test print out:
F<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
<input type='hidden' name='csrfmiddlewaretoken' value='VAiGvXZLHCjxWEWdjhgQRBwBSnMVoIWR' />
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
F.
He doesn't have this problem in the book (he's using 1.8), so I was wondering if the method behavior has changed, or how I would write this test to pass.
The request argument was added to render_to_string in Django 1.8. You could try changing the line in your test to:
expected_html = render_to_string('home.html', request=request)
It's only required to make this change in Django 1.9+, the test passes without the request in Django 1.8.
I found this solution which has worked for the latest Django version - 3.0.6
#add a function to the post request test function
def remove_csrf_tag(text):
"""Remove csrf tag from TEXT"""
return re.sub(r'<[^>]*csrfmiddlewaretoken[^>]*>', '', text)
...
# then change assertion
def test_home_page_can_save_a_POST_request(self):
...
self.assertEqual(
remove_csrf_tag(response.content),
remove_csrf_tag(expected_html)
)

How to decouple html/js code from laravel4 templates?

I want to separate html code from my laravel template (*.blade.php) file . I have following code in my dashboard.blade.php template :
<h1>Dashboard</h1>
<p>Welcome to your Dashboard. You rock!</p>
<div class="bubbletree-wrapper">
<div class="bubbletree"></div>
</div>
I want to separate this html code from here and want to move it to another file , with extension either *.html or *.tpl or any other except *.php .
Is it possible to do so ? Please help me on this .
Thanks.
I don't see anyone 100% decoupling HTML/CSS, but you can follow some Design Patterns, like Presenter, and use Laravel Blade so it be very little coupled.
Name a view home.blade.php and add your code to it and change your code to:
<h1>{{$pageTitle}}</h1>
<p>{{$welcomeMessage}}</p>
<div class="bubbletree-wrapper">
<div class="bubbletree"></div>
</div>
Create a route using:
<?php
Route::get('/', function() {
return View::make('home',
array(
'$pageTitle' => 'Dashboard',
'welcomeMessage' => 'Welcome to your Dashboard. You rock!'
)
);
});
See? It's almost 100% decoupled, but you cannot decouple 100% or you'll not be able to show your dynamic data in your final HTML.
Also, Blade helps you organize your code, so you can have a layout, let's call it layout.blade.php:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title> Your Application </title>
<link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.min.css">
</head>
<body class="">
#yield('contentSection')
</body>
</html>
You have one single line of Blade in it, just to add your page contents, now you can create your home view as:
#extends('layout')
#section('contentSection')
<h1>{{$pageTitle}}</h1>
<p>{{$welcomeMessage}}</p>
<div class="bubbletree-wrapper">
<div class="bubbletree"></div>
</div>
#stop
And blade will render this HTML for you:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title> Your Application </title>
<link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.min.css">
</head>
<body class="">
<h1>Dashboard</h1>
<p>Welcome to your Dashboard. You rock!</p>
<div class="bubbletree-wrapper">
<div class="bubbletree"></div>
</div>
</body>
</html>