11

How can http headers be added within a WSGI middleware?

deamon
  • 89,107
  • 111
  • 320
  • 448

1 Answers1

21

I've found a nice example from the pylons book.

class Middleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):

        def custom_start_response(status, headers, exc_info=None):
            headers.append(('Set-Cookie', "name=value"))
            return start_response(status, headers, exc_info)

        return self.app(environ, custom_start_response)

The trick is to use a nested method.

deamon
  • 89,107
  • 111
  • 320
  • 448