Post on 27-Dec-2015
transcript
Background: how cgi works
• Request : content/url sent by the client• Response: content return to the client’s
browser
3
Client server
Request: request a url, click a button, etc
Request a url: “get” urlResponse: CGI returns some html code Click buttons: “post” something
Python “hello world” CGI program
helloworld.py
print 'Content-Type: text/plain'print ''print 'Hello, world!'
Preparation
• Have your gmail account• Installing google apps tool
– dev_appserver.py, the development web server– appcfg.py, for uploading your app to App Engine
Setup the development env
• Windows/mac: check http://code.google.com/appengine/downloads.html to find the package
• Nimbus17: already installed at /usr/local/gae
Webapp does
• Wraps the CGI functions– API for handling request/response
• Python Web Server Gateway Interface (WSGI)– A framework for developing CGI programs with
Python
7
from google.appengine.ext import webappfrom google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, webapp World!')
application = webapp.WSGIApplication( [('/', MainPage)], debug=True)
def main(): run_wsgi_app(application)
if __name__ == "__main__": main()
Configuration file
• app.yaml– A standard file format for configuration– A set of API designed to access the configuration– http://www.yaml.org/– Don’t need to know much about yaml– Check GAE’s typical configurations
9
App.yaml
application: helloworld version: 1 runtime: python27 threadsafe: falseapi_version: 1
handlers: - url: /.* script: helloworld.py
If threadsafe is set to true,use helloworld.application
Start development server
• How to start/usr/local/gae/dev_appserver.py helloworld/ -p
port -a address
Using users service
user = users.get_current_user()if user:
self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, ' + user.nickname())
else: self.redirect(users.create_login_url(self.request.uri))
Handling forms with webapp
self.response.out.write(""" <html> <body> <form action="/sign" method="post"> <div><textarea name="content" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Sign Guestbook"></div> </form> </body> </html>""")
db - datastore
• db.Model• GQL: sql like query language• greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY
date DESC LIMIT 10")• Or omit select *: greetings = Greeting.gql("ORDER BY date
DESC LIMIT 10")• With parameters: greetings = Greeting.gql("WHERE author
= :1 ORDER BY date DESC",users.get_current_user())• greetings = Greeting.all()
greetings.filter("author =", users.get_current_user()) greetings.order("-date")
16