The simplest example that I know is the hello world in the documentation:
# helloworld.py
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello, World!')
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
The corresponding app.yaml
is:
application: your-app-id
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: helloworld.application
You create a class MainPage
-- whenever you make a request to localhost:8080/
(note the slash is unncessary), you will be directed to the main page. the application
is responsible for routing the request to the proper class and creating a new instance of that class for each request. It also calls the get
or post
or whatever HTTP method. Whatever you write into the response is what gets returned to the browser as the web page.
Now a single page isn't all that interesting. Maybe you want localhost:8080/goodbye
as well. Then you just add another class and "register" it with the application:
# helloworld.py
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello, World!')
class GoodbyePage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Goodbye, World. Time to sleep.')
application = webapp2.WSGIApplication([
('/', MainPage),
('/goodbye', GoodbyePage),
], debug=True)
No changes to app.yaml
are necessary at this point.
Life might be kind of frustrating if you needed to keep all your pages in a single file though. We can break this into 2 (or more) files by modifying app.yaml
.
application: your-app-id
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /goodbye
script: goodbye.app
- url: /.*
script: helloworld.application
helloworld.py
is the same as the first example. goodbye.py
looks like this:
# goodbye.py
import webapp2
class GoodbyePage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write('<html><head></head><body>Goodbye!</body></html>')
app = webapp2.WSGIApplication([
('/goodbye', GoodbyePage),
], debug=True)
The urls in app.yaml
are regular expressions -- you want to order them from most specific to least specific (otherwise, you might handle the request with the wrong handler). Also note that the convention in app.yaml
is script: <module_name>.<variable_name>
when we set it up this way.