| 1 |
import sys |
| 2 |
|
| 3 |
from .recursive import ForwardRequestException, RecursionLoop |
| 4 |
|
| 5 |
|
| 6 |
class StatusPersist(object): |
| 7 |
|
| 8 |
def __init__(self, app, status, url): |
| 9 |
self.app = app |
| 10 |
self.status = status |
| 11 |
self.url = url |
| 12 |
|
| 13 |
def __call__(self, environ, start_response): |
| 14 |
def keep_status_start_response(status, headers, exc_info=None): |
| 15 |
return start_response(self.status, headers, exc_info) |
| 16 |
parts = self.url.split('?') |
| 17 |
environ['PATH_INFO'] = parts[0] |
| 18 |
if len(parts) > 1: |
| 19 |
environ['QUERY_STRING'] = parts[1] |
| 20 |
else: |
| 21 |
environ['QUERY_STRING'] = '' |
| 22 |
|
| 23 |
try: |
| 24 |
return self.app(environ, keep_status_start_response) |
| 25 |
except RecursionLoop as e: |
| 26 |
environ['wsgi.errors'].write( |
| 27 |
'Recursion error getting error page: %s\n' % e |
| 28 |
) |
| 29 |
keep_status_start_response( |
| 30 |
'500 Server Error', |
| 31 |
[('Content-type', 'text/plain')], |
| 32 |
sys.exc_info() |
| 33 |
) |
| 34 |
return [ |
| 35 |
b'Error: %s. (Error page could not be fetched)' % ( |
| 36 |
self.status.encode('utf-8') |
| 37 |
) |
| 38 |
] |
| 39 |
|
| 40 |
|
| 41 |
class ErrorDocumentMiddleware(object): |
| 42 |
''' |
| 43 |
Intersects HTTP response status code, looks it up in the error map defined |
| 44 |
in the Pecan app config.py, and routes to the controller assigned to that |
| 45 |
status. |
| 46 |
''' |
| 47 |
def __init__(self, app, error_map): |
| 48 |
self.app = app |
| 49 |
self.error_map = error_map |
| 50 |
|
| 51 |
def __call__(self, environ, start_response): |
| 52 |
|
| 53 |
def replacement_start_response(status, headers, exc_info=None): |
| 54 |
''' |
| 55 |
Overrides the default response if the status is defined in the |
| 56 |
Pecan app error map configuration. |
| 57 |
''' |
| 58 |
try: |
| 59 |
status_code = int(status.split(' ')[0]) |
| 60 |
except (ValueError, TypeError): # pragma: nocover |
| 61 |
raise Exception(( |
| 62 |
'ErrorDocumentMiddleware received an invalid ' |
| 63 |
'status %s' % status |
| 64 |
)) |
| 65 |
|
| 66 |
if status_code in self.error_map: |
| 67 |
def factory(app): |
| 68 |
return StatusPersist( |
| 69 |
app, |
| 70 |
status, |
| 71 |
self.error_map[status_code] |
| 72 |
) |
| 73 |
raise ForwardRequestException(factory=factory) |
| 74 |
return start_response(status, headers, exc_info) |
| 75 |
|
| 76 |
app_iter = self.app(environ, replacement_start_response) |
| 77 |
return app_iter |