[web.py] Web Application on Both Google App Engine and Apache


This post shows a web.py application template which runs on both Apache with mod_wsgi and Google App Engine Python.

"Hello World" web.py application

mainweb.py | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import web

urls = (
  r"/", "MainPage"
)

class MainPage:
  def GET(self):
    return "Hello World"


app = web.application(urls, globals())
try:
  from google.appengine.ext import ndb
  # runs on Google App Engine
  app = app.gaerun()
except ImportError:
  application = app.wsgifunc()

if __name__ == '__main__':
  app.run()

Note

web.py is not included in the third-party libraries in GAE Python 2.7. To use web.py on GAE, please download web.py from Github. Put the web directory in web.py repo and this "Hello World" application in the same directory.

Sample GAE Python config

app.yaml | repository | view raw
1
2
3
4
5
6
7
8
9
application: webpy-gae
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: mainweb.app

Sample Apache config

apache.conf | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<VirtualHost *:80>
        ServerName      {{ domain_name }}
        ServerAdmin     {{ email }}
        ErrorLog        {{ SOME_DIR }}/logs/error_log
        CustomLog       {{ SOME_DIR }}/logs/access_log combined

        Alias           /favicon.ico {{ REPO_DIR }}/favicon.ico
        Alias           /robots.txt {{ REPO_DIR }}/robots.txt

        WSGIScriptAlias / {{ REPO_DIR }}/mainweb.py

        AddType         text/html .py
</VirtualHost>

Development

Makefile | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# path of Google App Engine Python SDK
GAE_PY_SDK=../../../../../google_appengine

all: local

devserver:
	$(GAE_PY_SDK)/dev_appserver.py .

local:
	python mainweb.py

Modify the path of GAE_PY_SDK in Makefile to your path of GAE Python SDK.

Test run the web.py application locally:

# open your terminal and run
$ make local
# OR
$ make
# open browser with URL: http://localhost:8080/

Test run the web.py application on local GAE Python environment:

# open your terminal and run
$ make devserver
# open browser with URL: http://localhost:8080/

Tested on: Ubuntu Linux 14.10, Google App Engine Python SDK 1.9.18


References:

[1]web.py
[2]Webpy + Apache with mod_wsgi on Ubuntu (web.py)
[3]Webpy + Google App Engine (web.py)
[4][web.py] Multiple Application with Same Context