Skip to content

Instantly share code, notes, and snippets.

@ThiefMaster
Last active December 18, 2015 00:39
Show Gist options
  • Save ThiefMaster/5698549 to your computer and use it in GitHub Desktop.
Save ThiefMaster/5698549 to your computer and use it in GitHub Desktop.
class XAccelMiddleware(object):
"""A WSGI Middleware that converts X-Sendfile headers to X-Accel-Redirect
headers if possible.
If the path is not mapped to a URI usable for X-Sendfile we abort with an
error since it likely means there is a misconfiguration.
"""
def __init__(self, app, mapping):
self.app = app
self.mapping = mapping.items()
def __call__(self, environ, start_response):
def _start_response(status, headers, exc_info=None):
xsf_path = None
new_headers = []
for name, value in headers:
if name.lower() == 'x-sendfile':
xsf_path = value
else:
new_headers.append((name, value))
if xsf_path:
uri = self.make_x_accel_header(xsf_path)
if not uri:
raise ValueError('Could not map %s to an URI' % xsf_path)
new_headers.append(('X-Accel-Redirect', uri))
return start_response(status, new_headers, exc_info)
return self.app(environ, _start_response)
def make_x_accel_header(self, path):
for base, uri in self.mapping:
if path.startswith(base + '/'):
return uri + path[len(base):]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment