Neil's News

App Engine Python 3

31 January 2020

App Engine is a great platform for creating minimal cloud-hosted applications without fuss and bother. Here's a simple Python 2.7 application that takes two numbers as URL parameters, adds them, and prints them back out:

import cgi

print("Content-Type: text/plain\n")
forms = cgi.FieldStorage()

a = 0
if "a" in forms:
  a = int(forms["a"].value)
b = 0
if "b" in forms:
  b = int(forms["b"].value)

print(a + b)

Thus when you visit /add.py?a=1&b=2 the result is 3.

Unfortunately App Engine's 'upgrade' from Python 2 to Python 3 appears to have made such lightweight applications impossible. First, app.yaml no longer provides routing of different URLs, so that logic needs to be moved into a singular Python program named main.py. Furthermore, the documentation states:

In the Python 3 runtime, your app needs to use a web framework such as Flask or Django
A quick glance at Flask (which describes itself as a "micro framework") reveals 300 kb of code. No.

Fortunately the documentation is a lie, it is perfectly possible to use Python 3 on App Engine without a framework:

import cgi

def app(environ, start_response):
  # Route to requested handler.
  if environ["PATH_INFO"] == "/add.py":
    return add(environ, start_response)
  start_response("404 Not Found", [])
  return [b"Page not found."]

def add(environ, start_response):
  forms = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
  a = 0
  if "a" in forms:
    a = int(forms["a"].value)
  b = 0
  if "b" in forms:
    b = int(forms["b"].value)
  out = str(a + b)

  headers = [
    ("Content-Type", "text/plain")
  ]
  start_response("200 OK", headers)
  return [out.encode("utf-8")]

Hope this helps anyone else who is struggling to retain the simplicity of their Python 2 App Engine services during the forced upgrade to Python 3.

< Previous | Next >

 
-------------------------------------
Legal yada yada: My views do not necessarily represent those of my employer or my goldfish.