Search code examples
pythongoogle-app-enginewebapp2

How to return status code 418 in Webapp2


It seems Webapp2 does not support the status code 418 because it doesn't have a status message mapped to it. How do I get around it and return a 418?

response.set_status(418)    # does not work
response.status_int = 418   # does not work either

Traceback:

  File "/.../App Engine SDK/lib/webapp2-2.5.2/webapp2.py", line 425, in set_status
    self.status = code
  File "/.../App Engine SDK/lib/webapp2-2.5.2/webapp2.py", line 405, in _set_status
    message = message or Response.http_status_message(code)
  File "/.../App Engine SDK/lib/webapp2-2.5.2/webapp2.py", line 488, in http_status_message
    raise KeyError('Invalid HTTP status code: %d' % code)
KeyError: 'Invalid HTTP status code: 418'

Solution

  • By monkey patching, I am able to get the status code 418 to work, but only partially.

    class TeapotHandle(webapp2.RequestHandler):
        def get(self):
            from webob import util
            import httplib
    
            util.status_reasons[418] = "I'm a teapot"
            httplib.responses[418] = "I'm a teapot"
    
            self.response.set_status(418)
    

    yields, using the dev server:

    HTTP/1.1 418 Unknown Status Code
    [...]
    

    But in fact, it works as expected once deployed on App Engine Cloud:

    HTTP/1.1 418 I'm a Teapot
    [...]