Replace webapp2 usage for self.response.write in python script

Posted on 07 May, 2016 in Products

I recently began to learn python and started by creating a simple app on google app engine, but then I decided to deploy it somewhere else.

(Although I know I can install webapp2 in a non-appengine python environment I would rather not because I prefer vanilla environments whenever possible.)

It's a very basic python controlled/created welcome page with a link that goes to my single-page website, index.html. But how to change the following python code so that it did the same thing but without webapp2?

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write('<a href="index.html">Search</a>')

app = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)

I tried the print command, urllib, redirects and even considered scripting a basic web server, but none of those worked, or seemed like overkill. Obviously I could convert the whole thing to a full-scale Flask or Django application but before doing that I wanted to have a python script work in this simple manner.

In the end pythonanywhere gave me what I needed via WSGI and it turned out to be fairly straightforward:

SEARCH = """<html>
<head></head>
<body>
    <div style="text-align: center; padding-left: 50px; padding-top: 50px; font-size: 1.75em;">
        <p>Welcome:</p><a href="index.html">Search</a>
    </div>
</body>
</html>
"""

def application(environ, start_response):
    if environ.get('PATH_INFO') == '/':
        status = '200 OK'
        content = SEARCH
    else:
        status = '404 NOT FOUND'
        content = 'Page not found.'
    response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(content)))]
    start_response(status, response_headers)
    yield content.encode('utf8')