I have a middleware set up in a Werkzeug based app to do some JSON escaping and manipulation for me (especially prefixing JSON with an escape string for an Angular-based REST-client).
I'd like to keep the whole logic in the middleware layer and don't add any tricks to my base view classes or my base app.
Because my middleware manipulates the content I strip the Content-Length header from headers, but I want to be a good netizen and provide the client with that information.
Unfortunately at the point where I have manipulated the content there seems to be no way to adjust headers anymore. Do I have to do this further down the pipeline? Wrap a second middleware around it?
Here's the code to the middleware:
class ContentManipulatingMiddle(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
app = self.app
def start_unpack_data(status, response_headers, exc_info=None):
# we need to strip content-length
response_headers = [ (name, value)
for name, value in response_headers
if name.lower() != 'content-length' ]
return start_response(status, response_headers, exc_info)
app_iter = app(environ, start_unpack_data)
data = []
for item in app_iter:
# do some content manipulation
data.append(manipulate_content(item))
# content length has changed, i should reset the content-length header
# but at this point, how?
return data
You dont need to worry about deleting/adding/changing content-length header, that will be auto handled by the server when it sends out the response. Sending a wrong length header might create problems for your website viewers / internet browsers.
You can test the Content-length headers here - http://www.dekho-ji.com/website-diagnostics-curl-http-request-response-headers-online