Issues in displaying a flash message in my HTML page - python

I just started to learn python some months ago...
I would like to display an message when there is no result for a query in my Query page (html). I am using python and flask. The code that I tried did not display any message.
My id.html code is (I included the code outside the search form):
<div class="flashes">
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</div>
And my python code is:
#app.route('/id')
def id():
params={}
params['entryname']='Search ID'
idn=request.args.get('idn')
sql=text('select * from DATA where info LIKE :id')
words=engine.execute(sql,id=idn).fetchall()
params['objs']=words
if params['objs']==0:
flash('No Results')
return render_template('id.html', **params)
I also tried this just for testing and did not work
if params['objs']>0:
flash('Results')
I am not sure what is wrong in my code, the query search is working, but no message...

"I also tried this just for testing and did not work"
if params['objs']>0:
flash('Results')
I don't use Python but it sounds like you're trying to check the size to make sure it contains something? If yes, then possibly this logic might help you :
Either use is_empty or the len properties :
if is_empty(params)==True:
flash('No Results')
if len(params)==0:
flash('No Results')
Also if you wanted bigger-than then write as : if len(params) > 0: flash('Results')

Related

Jinja 2 - displaying all my words instead of one

Please excuse my code, I am still a relative beginner trying to complete a school project! Basically, I am trying to create a language learning system where you input a word and it checks if it is correct. However, on the page learn.html all of the words in my database are coming up. I want to get it so that when you load the page there is the first word and when you click the button it checks that word, allowing the page to display the next word to translate. An example of this would be memrise, this screenshot shows the kind of system that I am trying to emulate.
I know that this is because of the for loop but I have tried lots of solutions to no success. It seems like a really easy problem but I am really stuck. I have 0 JavaScript expertise so if possible I would try to stay away from JS solutions. I will really appreciate any help possible :)
learn.html
{% block content %}
<form class = "form" id="form1" action="/learn/check" methods=["POST"]>
<td>
<h5> Please enter the spanish for : {% for word in course_content %}{{ word.english }} {% endfor %} </h5>
<input type="text" name="language_learning_input" id="desc" value="" size="100" maxlength="140"/>
<p> </p>
</td>
<input type="submit" name="button" class="btn btn-success" value="Update"/>
</form>
{% endblock content %}
snippet of main.py
#LEARN SYSTEM
#STORING DB VALUES IN LISTS
def spanish():
#setting variables
holding_spanish = []
#running db query
course_content = db.session.query(Course).all()
#iterating through db
for row in course_content:
holding_spanish.append(row.spanish)
return holding_spanish
def english():
#setting variables
holding_english = []
#running db query
course_content = db.session.query(Course).all()
#iterating through db
for row in course_content:
holding_english.append(row.english)
return holding_english
def score():
#setting variables
holding_score = []
#running db query
account_settings = db.session.query(AccountSettings).all()
#iterating through db
for row in account_settings:
holding_score.append(row.words_per_lesson)
return holding_score
#MAIN LEARN PAGE
#app.route("/learn")
def learn():
#getting values
english()
spanish()
score()
x=1
testingvalue = [score()]
acccount_settings = db.session.query(AccountSettings).all()
course_content = db.session.query(Course).all()
return render_template('learn.html', course_content=course_content, acccount_settings=acccount_settings,testingvalue=testingvalue,x=x,english=english)
#ROUTE USED TO CHECK
#app.route("/learn/check", methods =['GET'])
def learncheck():
course_content = db.session.query(Course).all()
language_learning_input = request.args.get('language_learning_input')
for row in course_content:
if language_learning_input == row.spanish:
"<h1> correcto! </h1>"
print("true")
else:
"<h1> not correcto! :</h1>"
print("false")
Basically you need to understand two things.
First, of the many words you have to return only one. *
So, how do you know which word the user has already seen?
You don't. HTTP is a stateless protocoll. That means, each request (access by a browser) is independent of another one.
But you can work around this limitation.
So, second, you need to save the state. And there are several concepts.
From the top of my head, you could use
sessions
cookies
or pass a parameter with e.h. the current word, so you can deduct the next word
That's it. Enjoy your homework and do not hesitate to create a new question when you encounter a specific problem
You could also return all words, and then do the cycling through the words via Javascript.

Python flask - Encoding links based on JSON varibale

I'm creating an application in Python flask and I'm struggling to encode my links. In my HTML template I'm calling data from JSON and based on a variable from JSON, I want to create a link to another page but the variables that have "space" in them, only take the first word and the link doesn't work as it should.
This is my JSON:
[
{
"team":"AFC Bournemouth"
},
{
"team":"Arsenal"
}
]
And this is my python:
#app.route('/<team>/')
def artist(team):
json_data=open('static/data.json').read()
data= json.loads(json_data)
urllib.quote_plus(data.team)
return render_template("team.html", team=team)
I'm trying to use "urllib.quote_plus" but I get an error
AttributeError: 'list' object has no attribute 'team'
I don't know how to fix it.
And this is my loop in html:
{% for data in results %}
<div class="team">
<p><a href=/{{ data.team }}>{{ data.team }}</a></p>
</div>
{% endfor %}
Before I used "urllib.quote_plus" the link for "Arsenal" worked perfect, but for "AFC Bournemouth" it only took the word "AFC".
That is strange that it is working correctly for "Arsenal". Actually you should iterate over the "data" because it is a list
Example:
#app.route('/<team>/')
def artist(team):
json_data=open('static/data.json').read()
data= json.loads(json_data)
data = [{'team': urllib.quote_plus(team['team'])} for team in data]
return render_template("team.html", results=data)
Another thing is that in render_template you are sending variable team and not results (changed in my example). This way it should be fine and work with your Jinja template.
Edit: changed list comprehension

How do I use Jinja2 filter on a block with argumets

I am trying to use jinja2 templates. I have custom filter called highlight, that takes string and language name and passes them to pyhments for code highlightning. I am trying to use it like this:
{% filter highlight("python") %}
import sys
def main():
pass
{% endfilter %}
But I get this error:
AttributeError: 'str' object has no attribute 'get_tokens'
Then I tried this:
{% filter highlight "python" %}
It does not work either.
There might be a trick via set block filtering and then pasting it back via {{ ... }}, but this technique is not merged in master source code yet, and seems too hacky for me.
So, is that even possible currently, or I am just doing it wrong?
EDIT: Here is filter:
#jinja2.contextfilter
def highlight(context, code, lang):
print("HIGHLIGHT")
print(code)
return jinja2.Markup(pygments.highlight(code, lexer=lang, formatter='html'))
I am an idiot, that was pygments error. By some mistake, I didn't see that last entry in stacktrace was from there.
You should use:
pygments.highlight(
code,
lexer=pygments.lexers.get_lexer_by_name(lang),
formatter=pygments.formatters.get_formatter_by_name('html')
)
instead of:
pygments.highlight(code, lexer=lang, formatter='html')

Python App Engine - Blobstore for non-images

In my Python Appengine 'app' I have been asked to 'attach any file' so I have the following code snippet to 'display' those files...
blobattach = ''
blobmime = 'None'
if pattachment.blobkey <> None:
blobattach = get_serving_url(pattachment.blobkey) # <-- line 104
blob_info = blobstore.BlobInfo.get(pattachment.blobkey)
blobmime = blob_info.content_type[:5]
blobname = blob_info.filename
Using the following HTML
{% if blobmime == 'None' %}
{% else %}
{% if blobmime == 'image' %}
<img src="{{ blobattach }}" alt='Attachment'/>
{% else %}
<br/>
<small><a class="fswideb" href="{{blobattach}}" Title="Download to view"><span>Download to view {{ blobname }}</span></a></small>
{% endif %}
{% endif %}
If the attachment is an image, it is displayed (blobmime=='image'). If not, a link is displayed so the user can download the file and view it however they can.
However, while this works in development, on my laptop (Google App Engine Launcher), I get the following error when trying to 'serve' a .xls file. (No error with .jpg attachments)
File "/base/data/home/apps/s~fs-rentals/20140101.382312463312950329/fmntjobattachmaint.py", line 104, in display
blobattach = get_serving_url(pattachment.blobkey)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1794, in get_serving_url
return rpc.get_result()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
return self.__get_result_hook(self)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1892, in get_serving_url_hook
raise _ToImagesError(e, readable_blob_key)
TransformationError
All of the examples use images and I have no problems with them, indeed no problems in development. Any thoughts on what I could have missed?
Many thanks
David
As suggested I changed the above to use Google Cloud Storage. I still get exactly the same error. The get_serving_url function errors if the blob is not an image. Is there an equivalent for a file that is not an image?
The sample at https://cloud.google.com/appengine/docs/python/tools/webapp/blobstorehandlers#BlobstoreUploadHandler provides a really good example of what I am trying to do except that I may want to add the person's CV instead of their photo.
Thanks
David
Fixed my problem. I was trying to do too much on one 'screen'
If the blob is an image - get_serving_url as above.
If the blob is not an image - display a link to a different page (target='_blank') that does the following (pretty much copied from another SO post):
if rmntjobattach.mntjobattachid <> 0 \
and rmntjobattach.blobkey:
blob_info = blobstore.BlobInfo.get(rmntjobattach.blobkey)
self.send_blob(blob_info)
else:
self.error(404)
The trick was to display an image blob on the same page and everything else on the new page when the user requested it (clicked the link)
David

A python coded "alert"-like dialog or template

update 0:
There is a subtle, but serious, error in my code and in my explanation below because I cannot only compare the name on the template with the hiddenname on the template (that much only tells me that the user has made a change like a checkbox change would tell me, but purposely there are no checkboxes), I also need to compare name to the status of name in the datastore of reservations to see if someone else has already reserved the time slot. So I cannot use javascript and I have to rewrite some of the code below to make the correct comparison, too. And may original question remains as suggested by the Title of this question. (In one of the comments I erroneously said that javascript would work.)
update 0:
I am trying to write a sort of "alert" in the way that this code suggests where I use the Trans model and the gae datastore (further below) to communicate between my main app and the "alert template". I have a few problems.
Initially I had my need for this alert in an another part of my code in an else: clause, not in an elif: clause. When I tried to use the simpler version of my alert in the elif code, python seemed to ignore the self.response.out.write(template.render(path, template_values)) and just went on to this code which ended my conditionals: return webapp2.redirect("/read/%s" % location_id). So, as you can see in my code I have commented out the ignored former code line and attempted to replace it with something more like the latter code line, but with that latter line directed to unexpected instead of read. You can see from my code it is still a mix between the two approaches and I could use help sorting that out. Is there really something different about else: and elif: regarding this?
Originally I had not anticipated my desire to call the same html template and Trans model from so many places in my code, so I did not design a key or ID or key_name into the design of using Trans. And now I am having trouble implementing a version with such detail.
I have been looking for an example of how such "alert templates" can be made in python. They are so easy in javascript, but I am trying to do the user input validation in my python code. Any pointers to examples or docs would be greatly appreciated.
weekday_key = db.Key.from_path('Locations',location_id,'Courts', court_id,'Days',weekday)
if name == hiddenname:
pass
elif name != hiddenname and hiddenname == "":
reservation = Reservations.get_or_insert(time[2],parent=weekday_key)
reservation.hour = time[0]
reservation.minute = time[1]
reservation.year = int(year)
reservation.nowmonth = int(nowmonth)
reservation.day = int(day)
reservation.nowweekday = int(nowweekday)
reservation.name = name
reservation.put()
elif name != hiddenname and name!="":
reservation = Reservations.get_by_key_name(time[2],parent=weekday_key)
reservation.hour = time[0]
reservation.minute = time[1]
reservation.year = int(year)
reservation.nowmonth = int(nowmonth)
reservation.day = int(day)
reservation.nowweekday = int(nowweekday)
reservation.name = name
reservation.put()
reason='This was in that time slot already: '
trans = Trans(parent=reservation.key().name()) #this line is iffy
trans.reason=reason
trans.name=hiddenname
trans.put()
iden = trans.key().id() # this is part of the iffy just above
template_values = {'trans':trans}
path = os.path.join(TEMPLATE_DIR, 'unexpected.html')
#self.response.out.write(template.render(path, template_values))
return webapp2.redirect("/unexpected/%s/%d" % (time[2],iden) #more iffy
else:
pass
My model for Trans in next.
class Trans(db.Model):
reason = db.StringProperty()
name = db.StringProperty()
My jinja2 equipped unexpected.html template is as follows.
{% extends "base.html" %}
{% block content %}
This unexpected result occurred. {{ trans.reason }}:<emph style="font-weight: bold">{{ trans.name }}</emph>
<br /><br />
<div id="inputdata">
<label>Click the "Ok" button to go back to the previous page so you can elect to edit your entry, or not.
</label>
<button onclick="window.history.back()">Ok</button>
</div>
{% endblock content %}
This question is answered here. It could have been answered in this question, but apparently there was too much information given and no one saw the answer.

Categories

Resources