Created
February 21, 2016 19:03
-
-
Save yiboyang/c51427f591fa71ba89ff to your computer and use it in GitHub Desktop.
My fancy hello world app on Google App Engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import webapp2 | |
mainForm=""" | |
<form method='post' action='#'> | |
<label>What world do you come from? | |
<br> | |
<input name='world' value='%(world)s' placeholder='Minecraft World'> | |
</label> | |
<label>What's your name? | |
<input name='name' value='%(name)s'> | |
</label> | |
<label>How old are you? | |
<input name='age' value='%(age)s'> | |
</label> | |
<br> | |
<br> | |
<br> | |
<div style='color:red'>%(error)s</div> | |
<input type='submit'> | |
</form> | |
""" | |
class MainPage(webapp2.RequestHandler): | |
def get(self): | |
#self.response.headers['Content-Type'] = 'text/plain' | |
#self.response.write('Hello, World!') | |
#self.response.write(form) | |
self.write_form() | |
# writes the form with an optional error message | |
# can also take in form inputs from previous submission to populate the | |
# value attributes so as to preserve user input on error | |
def write_form(self, error='', world='', name='', age=''): | |
import cgi | |
self.response.write(mainForm % {'error': cgi.escape(error), | |
'world': cgi.escape(world), | |
'name': cgi.escape(name), | |
'age': cgi.escape(age), | |
}) | |
def post(self): | |
w = self.request.get('world').split(' ')[0] | |
n = self.request.get('name') | |
a = self.request.get('age') | |
# validate form | |
err=None | |
worlds=('Minecraft', 'Hello Kitty', 'Disney', 'Fantasy') | |
if w not in worlds: | |
err="Sorry %(n)s I've never heard of your %(w)s world!" %{'n':n, 'w':w} | |
strw=', '.join(w+' world' for w in worlds) | |
err+="\nI've only heard of " + strw | |
elif not a.isdigit(): | |
err="Sorry %s, '%s' doesn't seem like a valid age to me" %(n, a) | |
elif int(a)>18: | |
err="Sorry %s, I'm afraid you're too old to enjoy this site..." %n | |
elif int(a)<=6: | |
err="Sorry %s, this site is not for kindergarteners" %n | |
if err: | |
self.write_form(err,w,n,a) | |
else: # redirect to success page | |
from urllib import urlencode | |
self.redirect('/hello?'+urlencode({'world':w, 'name':n, 'age':a})) | |
# success page; prints a customized greeting | |
class GreetHandler(webapp2.RequestHandler): | |
def get(self): | |
#self.response.write(self.request) | |
greeting=""" | |
<h1>Oh hai dear %s from %s World!</h1> | |
""" | |
n = self.request.get('name') | |
w = self.request.get('world') | |
self.response.write(greeting %(n, w)) | |
app = webapp2.WSGIApplication([ | |
('/', MainPage), | |
('/hello', GreetHandler), | |
], debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment