Google App Engine properties of write - python

I was looking at the code from this site, for a basic google app engine calculator. I am just as inexperienced with GAE as I am with HTML, so when I saw the code bellow I was a little confused. Mostly with the last line </html>""" % (result, buttons)). What is the % for and how does it relate result and buttons to the html code?
result = ""
try:
result = f[operator](x, y)
except ValueError:
result = "Error: Incorrect Number"
except ZeroDivisionError:
result = "Error: Division by zero"
except KeyError:
pass
# build HTML response
buttons = "".join(["<input type='submit' name='operator' value='"
+ o + "'>" for o in sorted(f.keys())])
self.response.out.write("""<html>
<body>
<form action='/' method='get' autocomplete='off'>
<input type='text' name='x' value='%s'/><br/>
<input type='text' name='y'/><br/>
%s
</form>
</body>
</html>""" % (result, buttons))

The % is for formatting strings in Python. See a good explanation at Dive Into Python. In your example they are used to replace the '%s' characters with the values from variables.
Modifying your example:
A modified version your example, hardcoding values of result and buttons.
result = "THIS IS MY RESULT"
buttons = "AND MY BUTTON"
output = """
<html>
<body>
<form action='/' method='get' autocomplete='off'>
<input type='text' name='x' value='%s'/><br/>
<input type='text' name='y'/><br/>
%s
</form>
</body>
</html>
""" % (result, buttons)
print output
would yield:
<html>
<body>
<form action='/' method='get' autocomplete='off'>
<input type='text' name='x' value='THIS IS MY RESULT'/><br/>
<input type='text' name='y'/><br/>
AND MY BUTTON
</form>
</body>
</html>
In your example buttons holds more Html, and format strings make more sense in a context where the values would actually change, but the above should illustrate the basic principle.
A simpler example:
The code below:
result = "THIS IS MY RESULT"
buttons = "AND MY BUTTON"
print "%s ... %s!" % (result, buttons)
Would yield:
THIS IS MY RESULT ... AND MY BUTTON!
How it relates to App Engine:
Both examples above say print: this prints the output to "stdout"—your console.
In your original example, it says self.response.out.write, which is how you tell App Engine to write the text (which is Html) to your browser.
Concretely, if you change:
result = "THIS IS MY RESULT"
buttons = "AND MY BUTTON"
print "%s ... %s!" % (result, buttons)
to:
result = "THIS IS MY RESULT"
buttons = "AND MY BUTTON"
self.response.out.write("%s ... %s!" % (result, buttons))
the text will appear in your browser when you visit the page instead of on the console.
References:
Dive Into Python, also linked above is a great resource for learning Python. The whole book is good if you're new to Python. As are the Udacity courses.
The Python documentation on format strings is a good reference for format strings specifically.
The book "Using Google App Engine" is a great resource for learning Python, Html, and App Engine all at once. I can honestly recommend it, having read it myself. It's very accessible, but it is a few years old now.
Have fun!

Related

Return button in flask

I'm learning to use Flask but I did not found a "easy solution" (by "easy solution" I mean easy for my noob level, few codes line) for this so I'm asking here for help.
How I can create a "back" button on the new generated page in flask?
This is my code:
calculator.py
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/")
def my_form():
return render_template("calc.html")
#app.route("/", methods=['POST'])
def my_form_post():
num_1 = request.form['Number 1']
num_2 = request.form['Number 2']
result = int(num_1) + int(num_2)
render = render_template("calc_result.html")
#return render_template("calc_result.html")
return "The result from " + str(num_1) + " plus " + str(num_2) + " is: " + str(result) + "."
app.run(host='127.0.0.1', port=5000)
calc.html
<html>
<body>
<form method = "POST">
<input name = "Number 1">
<input name = "Number 2">
<input type = "submit">
</body>
</form>
The code is working, is receiving the numbers and doing the math but the problem is, I'm not able to generate a "back" button in the new generated page with the result.
If I put for example 10 + 10 in the calc.html, I will receive:
The result from 10 plus 10 is: 20.
I would like to put a "back" button on this page or learn how to generate a new button in the new gelerated page, so I would receive something like:
The result from 10 plus 10 is: 20.
Back
Sorry the english.
Edit:
This is what user see on the first page:
What user see in first page
After put the two numbers to sum, they see:
Result page
I want allow user to come back to first page and be able to do another sum.
In both pages the link are the same: http://127.0.0.1:5000/
in your 'calc_result.html' file, make a link or button and use the 'url_for' command to bring you back to your 'calc.html' page. Flask allows you to insert Python code into your HTML via jinja templates. Check out the quickstart guide here. So:
Back
You can use the following code:
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script>
Please refer this.
<a href="/">
<form action="/">
<input class="btn" type="button" value="HOME" />
</form>
</a>

Basic Form In Flask Causing HTTP 400 - Python 3.5

I am new and have spent hours trying to setup a form in Flask for Python 3.5. I want the user to be able to enter a temperature setpoint and click submit button, and have the value stored in a variable.
I have this code in a template file called index.html:
<html>
<body>
<p><font size="6">Jewell Hot-Tub Controller</font>
<br>
<font size="4">Water Temperature: {{water_temp}}</p>
<br>
<font size="4">Set Point: {{set_point}}</p>
<br>
<font size="4">Enter New Set Point:</p>
<form class="form-newtemp" method="get" action="/ChangeTemp">
<input type="text" id="new_sp" name="new_sp" size="5" placeholder="New Temp." required>
<input id="1submit" type="submit">
</form>
</body>
</html>
and this code in the "flask-test.py" file:
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
#app.route('/')
def index():
return render_template('index.html', water_temp='12345')
#app.route('/ChangeTemp', methods=['GET'])
def process():
new = request.form['new_sp']
return 'New set point is:' + new
Entering "27" in the textbox sends the browser to a 400 Bad Request page at:
http://127.0.0.1:5000/ChangeTemp?new_sp=27
Why does this change a bad request error, rather than returning the value? The tutorials I saw used POST, but I used GET, does this require different syntax?
Also, please let me know if anything is messy, or done wrong.
Thank you!
EDIT: I also tried "request.form.get('new-sp', new)" and this causes a 500 internal server error.
multiple ways to fix your problem. i guess the fastest way is:
<form class="form-newtemp" method="post" action="{{ url_for('process')}}">
and then
#app.route('/ChangeTemp', methods=['POST])
def process():
new = request.form['new_sp']
return 'New set point is:' + new
or you can go with not changing your template and:
#app.route('/ChangeTemp', methods=['GET'])
def process():
new = request.args.get('new_sp')
return 'New set point is:' + new

Working in Python cgi with form. Empty input error

I am trying to work with forms on python and I have 2 problems which I can't decide for a lot of time.
First if I leave the text field empty, it will give me an error. url like this:
http://localhost/cgi-bin/sayHi.py?userName=
I tried a lot of variants like try except, if username in global or local and ect but no result, equivalent in php if (isset(var)). I just want to give a message like 'Fill a form' to user if he left the input empty but pressed button Submit.
Second I want to leave what was printed on input field after submit(like search form). In php it's quite easy to do it but I can't get how to do it python
Here is my test file with it
#!/usr/bin/python
import cgi
print "Content-type: text/html \n\n"
print """
<!DOCTYPE html >
<body>
<form action = "sayHi.py" method = "get">
<p>Your name?</p>
<input type = "text" name = "userName" /> <br>
Red<input type="checkbox" name="color" value="red">
Green<input type="checkbox" name="color" value="green">
<input type = "submit" />
</form>
</body>
</html>
"""
form = cgi.FieldStorage()
userName = form["userName"].value
userName = form.getfirst('userName', 'empty')
userName = cgi.escape(userName)
colors = form.getlist('color')
print "<h1>Hi there, %s!</h1>" % userName
print 'The colors list:'
for color in colors:
print '<p>', cgi.escape(color), '</p>'
On the cgi documentation page are these words:
The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator
One way to get what you want is to use the in operator, like so:
form = cgi.FieldStorage()
if "userName" in form:
print "<h1>Hi there, %s!</h1>" % cgi.escape(form["userName"].value)
From the same page:
The value attribute of the instance yields the string value of the field. The getvalue() method returns this string value directly; it also accepts an optional second argument as a default to return if the requested key is not present.
A second solution for you might be:
print "<h1>Hi there, %s!</h1>" % cgi.escape(form.getvalue("userName","Nobody"))

Python Variable in an HTML email in Python

How do I insert a variable into an HTML email I'm sending with python? The variable I'm trying to send is code. Below is what I have so far.
text = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1><% print code %></h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
"""
Use "formatstring".format:
code = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>{code}</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
""".format(code=code)
If you find yourself substituting a large number of variables, you can use
.format(**locals())
Another way is to use Templates:
>>> from string import Template
>>> html = '''\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>$code</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
'''
>>> s = Template(html).safe_substitute(code="We Says Thanks!")
>>> print(s)
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>We Says Thanks!</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
Note, that I used safe_substitute, not substitute, as if there is a placeholder which is not in the dictionary provided, substitute will raise ValueError: Invalid placeholder in string. The same problem is with string formatting.
use pythons string manipulation:
http://docs.python.org/2/library/stdtypes.html#string-formatting
generally the % operator is used to put a variable into a string, %i for integers, %s for strings and %f for floats,
NB: there is also another formatting type (.format) which is also described in the above link, that allows you to pass in a dict or list slightly more elegant than what I show below, this may be what you should go for in the long run as the % operator gets confusing if you have 100 variables you want to put into a string, though the use of dicts (my last example) kinda negates this.
code_str = "super duper heading"
html = "<h1>%s</h1>" % code_str
# <h1>super duper heading</h1>
code_nr = 42
html = "<h1>%i</h1>" % code_nr
# <h1>42</h1>
html = "<h1>%s %i</h1>" % (code_str, code_nr)
# <h1>super duper heading 42</h1>
html = "%(my_str)s %(my_nr)d" % {"my_str": code_str, "my_nr": code_nr}
# <h1>super duper heading 42</h1>
this is very basic and only work with primitive types, if you want to be able to store dicts, lists and possible objects I suggest you use cobvert them to jsons http://docs.python.org/2/library/json.html and https://stackoverflow.com/questions/4759634/python-json-tutorial are good sources of inspiration
Hope this helps

"%" character cause Error in strings substitution with locals()

I try to substitue strings with variables using locals() in python but I can find a way to use the % character inside the string without error. Here is a concrete example :
color = colors_generator() #the function return a color
html = """<html><head>
<style>#square{color:%(color)s;width:100%;height:100%;}</style>
</head> <body> <div id="square"> </div>
</body></html>""" % locals()
print "Content-Type: text/html\n"
print html
Result : TypeError: not enough arguments for format string
The problem is the % character in 100%. How can I escape it?
escape % with %
html = """<html><head>
<style>#square{color:%(color)s;width:100%%;height:100%%;}</style>
</head> <body> <div id="square"> </div>
</body></html>""" % locals()
Virhilo has already answered your direct question, but if you find you are building quite big/complicated templates it might be worth looking at a full blown template engine instead:
http://docs.python.org/library/string.html
http://jinja.pocoo.org/
http://www.makotemplates.org/

Categories