missing "pass" in view - python

{{extend 'layout.html'}}
{{import xml.etree.ElementTree as ET}}
<h1>
This is a Stations detail page
</h1>
{{filename = xmlfile}}
{{fh = open(filename, "r")}}
{{while True:}}
{{line = fh.readline()}}
{{print(line, end="")}}
{{fh.close()}}
{{=BEAUTIFY(response._vars)}}
The above code is showing "missing "pass" in view" error in web2py. Not sure why this error is showing up

Unlike in real Python, the indentation in a web2py view is only aesthetic. You need to clearly specify where the while block ends by adding pass at its end. Also note that you don't need to constantly close and open the brackets like this, you can escape all the code in only one {{ ... }}.
{{
filename = xmlfile
fh = open(xmlfile, "r")
while True:
line = fh.readline()
print(line, end="")
pass
fh.close()
}}
More informations about web2py views here.

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.

How to pass value from python to html form using flask/jinja

So I first create an array of all folders in a specific directory, I then pass that to my html file.
def test_yt_vid():
mylist = os.listdir(WD+r"static/"+YOUTUBE_FOLDER)
full_path = (WD+YOUTUBE_FOLDER)
return dict(mylist=mylist, full_path=full_path)
Next I look through that array to find what file has been selected.
<select name=list id="videolist" method="GET" action="/">
{% for mylist in mylist %}
<option value= "{{mylist}}" SELECTED>{{mylist}}</option>"
{% endfor %}
</select>
Next I use JS to get the specific value into a variable
$('#videolist').change(function () {
//console.log($("#videolist").val());
var fileInput = $("#videolist").val())};
So The problem is here, I'm not sure how I would go about passing that value into the following jinja code
<video id="videotesting1" class="video" width="300" height="240" autoplay loop controls="true">
<source src="{{url_for('static',filename='videoTest/' + 'testVid.mp4')}}" type="video/mp4">
</video >
I'm trying to replace 'testVid.mp4' with the variable fileInput from the JS, I tried using $("#videotesting1").attr("src","{{url_for('static',filename='videoTest/'" + fileInput +")}}");'
But no luck so far.
This is different to "How do you change video src using jQuery?" because I am trying to pass a jinja variable to HTML using js.
You have some wrong closed quotes. Take a look at filename, where you set 'videoTest/' plus some variable value (e.g x), which results in 'videoTest/'x. Do you notice it? The single quote closed after videoTest should appear after the variable fileInput. The correct way would be:
$("#videotesting1").attr("src","{{url_for('static',filename='videoTest/" + fileInput + "')}}");
When you modify the src, has by inspect element the src changed, but the desired video isn't being played? If so, try:
$("#videotesting1").load()
Take a look at what load does # JQuery docs.
Figure out the problem, the file name has to go outside the jinja code because it doesnt get rendered by jinja for some reason when the event happens.
$("#videotesting1").attr("src","{{url_for('static',filename='videoTest/')}}" + fileInput);

Multiline posting in HTML

I'm totally new at web development and I am currently trying to create a little website. The goal of this site, is to show random quotes of some of my teachers. The main pages are actually working just fine (I can get random quotes of my whole database, and random quotes from every teacher). But, I wanted to show all the quotes on the same page, and it happens they just appear all on the same line... And it's quite embarrassing...
In my python code, I used "\n" between each quote, so each new one started on a new line. But, on my HTML code, when I pass this string, it seems to have no effect I all the quotes just follow themselves on one line....
I'm using a Flask application, and a python class:
for i in range(2, max):
inte = inte + citation.ClasseCitations('Classe/citations.json','Classe/profs.json', prof, i).corps + ' \n '
return render_template("integrale.html", citation=inte, auteur=prof)
In my HTML file, I use citation like this:
<p>{{ citation }}</p>
Try this :
for i in range(2, max):
inte = inte + citation.ClasseCitations('Classe/citations.json','Classe/profs.json', prof, i).corps + ' <br/> '
return render_template("integrale.html", citation=inte, auteur=prof)
I'm not able to comment, but try it with
<br/>
instead of
\n
this could work.
I'd try using a list object within your flask-app.
Then in your html:
{% for quote in quotes %}
{{quote}} <br>
{% endfor %}
More on jinja2's for-loops
http://jinja.pocoo.org/docs/2.9/templates/#for-loop

Django - Read and write from a plain text

I'm trying to read and then write from a plain text in Django.
Basically I want to open a file, get an specific word and then change it for whatever else.
Here's what I have:
def address_L1():
file = open("interfaces.txt","r")
content = file.read()
file.close()
address = re.findall('address\s(.*?)\s',open('interfaces.txt','r').read())
if address:
print address[0]
else:
print 'no Address found!'
return address[0]
Here I'm opening a file and search for the word next to address, which is 192.168.5.5 and works perfect.
def get_interfaces(request):
address = str(address_L1())
if 'address' in request.POST:
write_template(request)#This is for my writing function
return render(request, 'interfaces.html', {'address':address})
Here I'm passing to template what's in address I mean, 192.168.5.5 will be shown in template.
<form method="post" action="">{% csrf_token %}
<label for="your_name">Address: </label>
<input id="your_name" type="text" name="address" value="{{ address }}">
<br>
<input type="submit" class="btn btn-success btn-xs" value="Guardar Cambios">
</form>
Here is my html were I'm displaying my variable, There's an input Address that will show my 192.168.5.5 or whatever is in address variable.
Everything works ok until now.
Now I'm trying to write to my plain text.
def write_template(request):
if request.method == 'POST':
get_address = address_L1()
change_address_L1 = request.GET.get("address", None)#Doing something with my input field in template
filedata= None
with open('interfaces.txt', 'r') as f:
filedata = f.readlines()
filedata=filedata.replace(get_address , change_address_L1)
with open('interfaces.txt', 'wb') as f:
f.writelines(filedata)
return render(request, 'interfaces.html')
Here basically what I want to do is get what's in my input address and replace for whatever I enter, I mean when I run my code I ll see my input with 192.168.5.5 I want to delete that value and enter 192.168.0.0 and change my value. When I try so I get this error:
'list' object has no attribute 'replace'
How can I solve this? how can I successful write in my plain text properly?
What am I doing wrong? thanks in advance!!
As the error says, filedata is a list. That's because f.readlines() gives you a list, where each element is a line in the file.
If you want the whole thing as a single string, do f.read() instead.

Problems with displaying the content of a text file in a tpl using the bottle framwork

Im trying to display the content of a text file in a template without any luck so far. This is
my code so far:
#route('/show_article/<filename>')
def show_article(filename):
stat_art=static_file(filename, root="articles")
return template('show_article', stat_art=stat_art)
And this is the paragraph in my template to display the content of the file
<p>
{{stat_art}}
</p>
I know that I could just return the static_file() but I will need to design the page with
some css and stuff later.
Thanks in advance and sorry for if my english is not correct!
You've misunderstood what static_file does.
Luckily, the fix is simple: just read the file yourself and pass its contents to the template, like so:
#route('/show_article/<filename>')
def show_article(filename):
with open(filename) as f: # <-- you'll need the correct path here, possibly including "articles"
stat_art = f.read()
return template('show_article', stat_art=stat_art)
That should do the trick.
[Btw, nice first question!]

Categories