WSGI Middleware to intercept HTTP error responses.
This middleware checks the status code of the response. If it matches a known error (403, 404), it returns a custom HTML response instead of the default one.
WSGI Middleware to intercept HTTP error responses.
This middleware checks the status code of the response. If it matches a known error (403, 404), it returns a custom HTML response instead of the default one.
Initialize the middleware with the WSGI application.
def __init__(self, app):
"""Initialize the middleware with the WSGI application.
:param app: The WSGI application to wrap.
"""
self.app = app
Custom start_response function to capture and modify error responses.
def custom_start_response(status, headers, exc_info=None):
"""Custom start_response function to capture and modify error responses.
:param status: The HTTP status string (e.g., "404 Not Found").
:param headers: The list of HTTP headers.
:param exc_info: Optional exception info.
:return: The modified status code and headers.
"""
nonlocal response_body
status_code = int(status.split()[0])
if status_code == 403:
response_body = [line.encode('utf-8') for line in HTML_403]
elif status_code == 404:
response_body = [line.encode('utf-8') for line in HTML_404]
return start_response(status, headers, exc_info)
Intercept the response and modify it if a known error occurs.
def __call__(self, environ, start_response):
"""Intercept the response and modify it if a known error occurs.
:param environ: The WSGI environment dictionary containing request data.
:param start_response: The function to start the HTTP response.
:return: (list of bytes) The modified response body if an error occurs,
otherwise the original response.
"""
response_body = None
def custom_start_response(status, headers, exc_info=None):
"""Custom start_response function to capture and modify error responses.
:param status: The HTTP status string (e.g., "404 Not Found").
:param headers: The list of HTTP headers.
:param exc_info: Optional exception info.
:return: The modified status code and headers.
"""
nonlocal response_body
status_code = int(status.split()[0])
if status_code == 403:
response_body = [line.encode('utf-8') for line in HTML_403]
elif status_code == 404:
response_body = [line.encode('utf-8') for line in HTML_404]
return start_response(status, headers, exc_info)
response = self.app(environ, custom_start_response)
if response_body is not None:
return response_body
return response