comparison piecrust/serving.py @ 200:76e459d48c43

serve: Correctly pass on the HTTP status code when an error occurs.
author Ludovic Chabant <ludovic@chabant.com>
date Tue, 13 Jan 2015 21:53:22 -0800
parents 430ee5b80962
children e725af1d48fb
comparison
equal deleted inserted replaced
199:aaf08277b96d 200:76e459d48c43
89 run_simple(self.host, self.port, wsgi_wrapper, 89 run_simple(self.host, self.port, wsgi_wrapper,
90 use_debugger=self.debug, use_reloader=self.use_reloader) 90 use_debugger=self.debug, use_reloader=self.use_reloader)
91 91
92 def _run_request(self, environ, start_response): 92 def _run_request(self, environ, start_response):
93 try: 93 try:
94 return self._run_piecrust(environ, start_response) 94 return self._try_run_request(environ, start_response)
95 except Exception as ex: 95 except Exception as ex:
96 if self.debug: 96 if self.debug:
97 raise 97 raise
98 return self._handle_error(ex, environ, start_response) 98 return self._handle_error(ex, environ, start_response)
99 99
100 def _run_piecrust(self, environ, start_response): 100 def _try_run_request(self, environ, start_response):
101 request = Request(environ) 101 request = Request(environ)
102 102
103 # We don't support anything else than GET requests since we're 103 # We don't support anything else than GET requests since we're
104 # previewing something that will be static later. 104 # previewing something that will be static later.
105 if self.static_preview and request.method != 'GET': 105 if self.static_preview and request.method != 'GET':
375 response.mimetype = self._mimetype_map.get( 375 response.mimetype = self._mimetype_map.get(
376 ext.lstrip('.'), 'text/plain') 376 ext.lstrip('.'), 'text/plain')
377 return response 377 return response
378 378
379 def _handle_error(self, exception, environ, start_response): 379 def _handle_error(self, exception, environ, start_response):
380 code = 500
380 path = 'error' 381 path = 'error'
381 if isinstance(exception, NotFound):
382 path += '404'
383 description = str(exception) 382 description = str(exception)
384 if isinstance(exception, HTTPException): 383 if isinstance(exception, HTTPException):
384 code = exception.code
385 description = exception.description 385 description = exception.description
386 if isinstance(exception, NotFound):
387 path += '404'
386 env = Environment(loader=ErrorMessageLoader()) 388 env = Environment(loader=ErrorMessageLoader())
387 template = env.get_template(path) 389 template = env.get_template(path)
388 context = {'details': description} 390 context = {'details': description}
389 response = Response(template.render(context), mimetype='text/html') 391 response = Response(template.render(context), mimetype='text/html')
392 response.status_code = code
390 return response(environ, start_response) 393 return response(environ, start_response)
391 394
392 395
393 class WsgiServer(object): 396 class WsgiServer(object):
394 def __init__(self, server): 397 def __init__(self, server):