How to open a txt file in a mako template? - python

My tree.txt file is stored in the directory tree. I want to open it in a mako template, and get its context.
Example (should work - but doesn't):
% for i in open("tree.txt", "r").read():
i
% endfor

% for i in open("/xxx/xxxx/xxxxx/xxxxxx/tree.txt", "r").read():
${i}
% endfor
It's already resolved.When you are opening a file by using a mako template, you must use a absolute path.

Related

Display contents of a text file in Django template

I am attempting to create a file in simple website and then read the contents of the same in a variable inside a Django view function and parse the variable to the template to be displayed on web page.
However, when I print the variable, it appears the same on cmd as is in the original text file, but the output on the web page has no formattings but appears like a single string.
I've been stuck on it for two days.
Also I'm relatively new to django and self learning it
file1 = open(r'status.txt','w',encoding='UTF-8')
file1.seek(0)
for i in range(0,len(data.split())):
file1.write(data.split()[i] + " ")
if i%5==0 and i!=0 and i!=5:
file1.write("\n")
file1.close()
file1 = open(r'status.txt',"r+",encoding='UTF-8')
d = file1.read()
print(d) #prints on cmd in the same formatting as in text file
return render(request,'status.html',{'dat':d}) **#the html displays it only as a single text
string**
<body>
{% block content %}
{{dat}}
{% endblock %}
</body>
Use the linebreaks filter in your template. It will render \n as <br/>.
use it like -:
{{ dat | linebreaks }}
from the docs:
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (<br>) and a new line followed by a
blank line becomes a paragraph break (</p>).
You can use linebreaksbr if you don't want <p> tag.
It's because in HTML newline is </br> in Python it is \n. You should convert it, before rendering
mytext = "<br />".join(mytext.split("\n"))
Depending of your needs and the file format you want to print, you may also want to check the <pre> HTML tag.

Why download button on Python website doesn't work

I have Flask website in which I want to add download button which downloads .csv file with scraped data.
In my html file I have this code:
<a href="cms_scrape.csv" ><button>Download!</button></a>
And only output I get is error: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
File is in its proper folder.
My folder structure:
└───Project
│ cms_scrape.csv
│
└───templates
index.html
You will need to specify some sort of route on the backend of your site.
For instance, somewhere in your flask site, you probably have a route #app.route('/') for your index. You will need a similar route for your file. That route will go out onto your file system and return the file itself.
#app.route('/csv_file')
def csv_file():
return flask.send_file('path/to/file/cms_scrape.csv',
attachment_filename='cms_scrape.csv',
as_attachment=True)
You will also need to modify your html to access a route and not the file name directly (unless you create your routes dynamically, of course):
<a href="/csv_file" ><button>Download!</button></a>
Not exactly sure about this but I think the tag has a download attribute you can use. Then you don't need the button.
Usage:
<a href="/path/to/file" download>
Source: https://www.w3schools.com/tags/att_a_download.asp
You can make links to files with the
{{ url_for('static', filename='filename.foo') }}
function inside your template. You have to store the file in a folder named 'static' which should be located in the directory where the main scipt is.
The link in your template should look like this:
<a href=" {{ url_for('static', filename='cms_scrape.csv') }} " download>Download!</a>

Jinja2 {% include file %} outside of search path doesn't work

This is an elementary issue which is probably related to Jinja2 PrefixLoader or ChoiceLoader.
On Python 3.6 we load with this command
jinja2.FileSystemLoader( searchpath= "\\template_folder\\")
On Windows 7, our file structure is as follows.
- folder_bbb
* subfile.txt
- template_folder
* template_file
- folder_aaa
* subfile.txt
From the template_file we are successful with this command
{% include "folder_aaa/subfile.txt" %}
Now we wish to move the file one level up, and write
{% include "../folder_bbb/subfile.txt" %}
but that doesn't work, complaining file not found.
What is the correct way to write? Thanks.
You may specify all paths in the the loader
jinja2.FileSystemLoader(["c:\\template_folder\\", "c:\\folder_bbb\\"])
and refer the including block without a specific path
{% include "subfile.txt" %}
The path will be searched in order so that as you say, moving the file one level up, the file will be found. (You need the template_folder path for the template itself.)

How do I extract the uploaded filename in a POST?

My form is this:
<form name="mail-me" action="/mail-me.py" method="POST" enctype="multipart/form-data">
<input id='file' type='file' name='file' />
I am doing this within python (I'm using the native google python dev_appserver webapp2.RequestHandler bindings):
fileH = self.request.POST["file"]
print(fileH.name)
print(fileH.type)
and i get:
file
application/octet-stream
The file I'm uploading is: wodim.conf so I should get wodim.conf instead of file. What am I doing wrong - how do i fix this, because I get:
Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.
request.FILES['filename'].name
From the request documentation.
You can iterate over the files:
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
Figured it out, did a: print(dir(fileH)) - that gave me a list of supported attributes and filename is what I should be using, not 'file'. So, print(fileH.filename) works. I'm getting the server error because google-app-server only allows a fixed list of extensions (no .exe is allowed for uploading). If you do: fname = fileH.file 'file' is returned and this will cause problems since it has no extension (hence the error message).

Caught ViewDoesNotExist while rendering

I have encountered an error:
Caught ViewDoesNotExist while rendering: Tried my_view_two in module yourmodule.views. Error was: 'module' object has no attribute 'my_view_two'
The error is triggered from template tag:
{% trans "Lost your password?" %}
Earlier I have my_view_two function and added that in urls.py too. But later I deleted the URL entry and function. But it is still giving an error.
I have had similar errors reporting on {% url password_reset_link %} before - is that the first {% url %} in your template by any chance?
It looks as if that view is being imported somewhere (perhaps elsewhere from the urls.py?). Have you imported that view into another views.py file for example?). A quick way to find files containing this is to use grep (on Linux/Mac) at a command line in your site root:
$ grep -r "my_view_two" .
This will search for that string in all files of your project (if I've understood you correctly, it shouldn't be there).

Categories