Search code examples
google-app-enginepython-2.7wsgiwebapp2

How to inject request headers before initializing a webapp2.WSGIApplication


Assuming the following AppEngine/webapp2 code:

import webapp2

# insert header injection code here...

class HelloWebapp2(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, webapp2!')

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

How can I inject request headers before app is initialized/called?


Solution

  • We decided to just extend webapp2.RequestHandler and create a base class for all other handlers that we use in our application. In this base class, we override the dispatch method, and inject headers. This makes those headers available to instances of any classes that derive from this base class.

    class BaseHandler(webapp2.RequestHandler):
      def dispatch(self):
        // inject headers here (self.request.headers)
        super(BaseHandler, self).dispatch() 
    
    class Page|SecurePage|APIEndPoint|ETC(BaseHandler):
      // ...