I simply can't change python unicode - python

I'm working with flask and sqlalchemy to print a list in an html page. Code is below
Python code:
#app.route('/restaurants')
def showRestaurants():
restaurant = session.query(Restaurant.name)
return render_template('restaurants.html', restaurant = restaurant)
Html code:
<ul>
{% for i in range(0,9) %}
<li>
<strong>{% print(restaurant[i]) %}</strong>
</li>
{% endfor %}
</ul>
Page:
(u'Urban Burger',)
(u'Super Stir Fry',)
(u'Panda Garden',)
(u'Thyme for That Vegetarian Cuisine ',)
(u"Tony's Bistro ",)
(u"Andala's",)
(u"Auntie Ann's Diner ",)
(u'Cocina Y Amor ',)
(u'State Bird Provisions',)
So, what am I doing wrong? I have a database with restaurant names and wanna make a list of it but it seems impossible to decode it. I've already tried .encode() which print out an error says the variable encode is not define and when I put in create_engine encoding = 'acsii' simply does nothing. I appreciate any help.

SQLAlchemy's session.query returns a list of tuples. So, to display the name of each restaurant, you'd want to access the string in the first element of each tuple.
<strong>{% print(restaurant[i][0]) %}</strong>

encode('ascii') will work, but you have to apply it to the unicode string. The problem you have right now is that you are printing out a tuple not a string.
Instead, try referencing the restaurants like this:
restaurant[i][0].encode('ascii')
Even restaurant[i][0] might render correctly.

Related

how to change the value of the array when the user types a new value in reached form

i am working on my recommendation system,it works fine but
when the user searches for a book ,it gives title and image of the books,but when the user type some other title with reloading the file i ,it gives the correct book title but it loads the image of the pervious
searched book
here is my search route, which get book's title and its image
#app.route('/search',methods=['GET','POST'])
def search():
choice = request.args.get('search')
# removing all the characters except alphabets and numbers.
# passing the choice to the recommend() function
# passing the choice to the recommend() function
books = recommend(choice)
image=get_image()
# if rocommendation is a string and not list then it is else part of the
# recommend() function.
if type(books) == type('string'):
return render_template('read.html', book=books,image=image,s="oppps")
else:
return render_template('read.html', book=books,image=image)
here is my code to get the image, where i have defined img list gobally
for i in indices.flatten():
img.append(data[data.index == i]
['Image'].values[0])
return book_list
I can't understand why it gives the previous searched book's image,while it should display the current searched title image (But it works fine when i rerun the py file again)
here is my searched form
{% block body %}
<form action="{{url_for('search')}}" , class="navbar-form" role="search" ,method="POST">
<input type="text" placeholder="Search Books" class="search mb-3" name="search">
<button class="search-btn">Search</button>
</form>
{% endblock %}
can u pls help me out with this
Thanks you in Advance
I think you got some logic error in your code, but from posted piece it is not clear what exactly is your issue.
For example, how did you connect that data: title of the book and it's image:
books = recommend(choice) // here you get the book(s), based on **choice** variable
image=get_image() // but what did you based on when picking the image(s) from the list
I think more code would clarify this problem.

How do I take input data and print the input formatted in a pre-coded HTML format

I currently use txt editor to modify my email newsletter code that i send to vendors.
It is tedious, however it does allow for me to create a html table and edit it and send out to customers.
I thought it might be easier to code something that would allow me to type the input and the program would then give me and output of the formatted HTML code ready to copy and paste to my newsletter email service.
this is what i currently have, but it does not print the code with the necessary input values.
this is what i have so far
"""
VAN_REEFER = input("VAN OR REEFER OR POWER ONLY?")
PICKUP_LOCATION = input("WHERE DOES THIS PICKUP?")
PICKUP_TIME = input("WHAT TIME DOES THIS PICKUP?")
DROP_LOCATION = input("WHERE DOES THIS DROP?")
DROP_TIME = input("WHAT TIME DOES THIS DROP?")
ACCEPT_NOW = input("ACCEPT NOW RATE")
print ("""<tr>
<td>(VAN_REEFER)</td>
<td>(PICKUP_LOCATION)<br><b>(PICKUP_TIME)</b></br></td>
<td>(DROP_LOCATION)<br><b>DROP_TIME</b></br></td>
<TD><B>(ACCEPT_NOW)</B></TD>
<td>
<a href="mailto:Dispatch%40MYEMAIL.com?subject=%20%F0%9F%90%A2%20-%20%20-
PICK-
(PICKUP_TIME)
%20-%20-
(PICKUP_LOCATION)
%20
TO
%20-
(DROP_TIME)
-%20
(DROP_LOCATION)
DROP-
%20-%20
(VAN_REEFER)
%0A&body=
I%20HAVE%20A%20TRUCK%20FOR%20THIS%20LOAD-
%20%0A
MY%20RATE%20IS-
%20%0A
THIS%20IS%20MY%20ETA%20TO%20PICKUP%20THIS%20LOAD-
%20%0A
THIS%20IS%20MY%20PHONE%20NUMBER-
%20%0A">🐢<b>BID HERE</b>🐢</a>
</td>
</tr>
""")
"""
what i would like for this do is to take as many inputs that i want and when i am done it would recreate that code, with the different inputs that were entered by the end user. sometimes there might be 1 or 2 sets of inputs, sometimes there might be a dozen. once completed the program would compile each input into the code that i need to copy and paste to my email marketing service.
can someone help?
Take a look at template engines such as Jinja or mako.
You can write html templates like this (example is from this Jinja tutorial):
<p>My string: {{my_string}}</p>
<p>Value from the list: {{my_list[3]}}</p>
<p>Loop through the list:</p>
<ul>
{% for n in my_list %}
<li>{{n}}</li>
{% endfor %}
</ul>
and the template engine will dynamically replace the variables given in the double curly brackets {{}}. You can even create loops and conditions using {% ... %}.

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

Extending Jinja's {% trans %} to use JavaScript variables

I'd like to extend the behaviour of trans by rendering variables not as as values from the context, but instead as html (without using the context). My aim is to be able to populate those variables on the client through JavaScript.
Jinja as it seems doesn't allow for a great deal of customisation of this kind or I'm just unable to find the right hooks.
Here's what I'd like to achieve:
{% etrans name=username %}
My name is {{ name }}
{% endetrans %}
This should render to:
My name is <span id='#username'></span>
Of course, I could just use the normal {% trans %} directive and pass my html code to template.render(html_code_params), but that would require to have them defined in the template and the rendering code which I'd like to avoid.
Here's what I got so far (not much) which allows for a new etrans tag and the ability to use whatever goodies InternationalizationExtension has to offer.
from jinja2.ext import InternationalizationExtension
from jinja2.runtime import concat
class JavaScriptVariableExtension(InternationalizationExtension):
tagname = 'etrans'
tags = set([tagname])
def _parse_block(self, parser, allow_pluralize):
"""Parse until the next block tag with a given name.
Copy from InternationalizationExtension, as this uses hardcoded
`name:endtrans` instead of relying on tag name
"""
referenced = []
buf = []
while 1:
if parser.stream.current.type == 'data':
buf.append(parser.stream.current.value.replace('%', '%%'))
next(parser.stream)
elif parser.stream.current.type == 'variable_begin':
next(parser.stream)
name = parser.stream.expect('name').value
referenced.append(name)
buf.append('%%(%s)s' % name)
parser.stream.expect('variable_end')
elif parser.stream.current.type == 'block_begin':
next(parser.stream)
# can't use hardcoded "endtrans"
# if parser.stream.current.test('name:endtrans'):
if parser.stream.current.test('name:end%s' % self.tagname):
break
elif parser.stream.current.test('name:pluralize'):
if allow_pluralize:
break
parser.fail('a translatable section can have only one '
'pluralize section')
parser.fail('control structures in translatable sections are '
'not allowed')
elif parser.stream.eos:
parser.fail('unclosed translation block')
else:
assert False, 'internal parser error'
return referenced, concat(buf)
i18n_extended = JavaScriptVariableExtension
I don't mind overloading more methods (although the reason for above one should perhaps fixed upstream).
Stepping through the code is quite an interesting adventure. However, I hit a snag and am interested if anyone can give some advice.
The problem I see is that during the compilation, the function context.resolve() gets baked into the compiled code. jinja2.jinja2.compiler.CodeGenerator doesn't really allow any different handling here (correct me if I'm wrong). Ideally, I would define another node (for the variable) and this node would handle the way it's dealt with during compilation, but I don't see how this is possible. I might be too focussed on this as a solution, so perhaps someone can provide alternatives.
As suggested by #Garrett's comment, a much easier solution is to pass in a function to the template renderer that interpolates the variables. In my case, my target client-side framework is Angular, but this also works for any JS variables that you want to use within a {% trans %} environment. Here are the building blocks:
def text_to_javascript(string):
# modify as needed...
return "<span>{{ %s }}</span>" % string
def render():
tmpl = jinja_env.get_template(template_filename)
return tmpl.render({'js': text_to_javascript})
And this how I make use of it in the template file:
{% trans username=js('user.name') %}
My name is {{ username }}
{% endtrans %}
In the Angular controller, the variable user is bound to the $scope like so:
$scope.user = {'name': 'Bugs Bunny'}

Unescape html entities from JSON in Django templates

I'm getting the response from server that is escaped:
'item':'<b> Some Data </b>'
I pass such data to template useing item= json.loads(response)
By default django templates (in Google App Engine) escapes it further,
so its double escaped in results.
I can use safe to remove one level of escaping like:
{{item|safe}}
How do i turn entities to their corresponding signs?
You can do this:
{% autoescape off %}
{{ your_text_var }}
{% endautoescape %}
Warning - THIS IS NOT A RECOMMENDED SOLUTION. You should be using autoescaping instead (check Rafael's answer).
Following should do the job.
response.replace('&', '&').replace('<', '<').replace('>', '>')
Update -
After suggestion by Jan Schär, you should rather use the following :
response.replace('<', '<').replace('>', '>').replace('&', '&')
Because, if response is &gt;, it would result in > instead of the correct >. You should resolve & in the last.

Categories