classSanic: #..... asyncdefhandle_request(self, request, write_callback, stream_callback): """Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here :param request: HTTP Request object :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing """ try: # -------------------------------------------- # # Request Middleware # -------------------------------------------- #
# Fetch handler from router handler, args, kwargs, uri = self.router.get(request) request.uri_template = uri if handler isNone: raise ServerError( ("'None' was returned while requesting a " "handler from the router"))
# Run response handler response = handler(request, *args, **kwargs) if isawaitable(response): response = await response except Exception as e: # -------------------------------------------- # # Response Generation Failed # -------------------------------------------- #
try: response = self.error_handler.response(request, e) if isawaitable(response): response = await response except Exception as e: if self.debug: response = HTTPResponse( "Error while handling error: {}\nStack: {}".format( e, format_exc())) else: response = HTTPResponse( "An error occurred while handling an error") finally: # -------------------------------------------- # # Response Middleware # -------------------------------------------- # try: response = await self._run_response_middleware(request, response) except BaseException: error_logger.exception( 'Exception occurred in one of response middleware handlers' )
# pass the response to the correct callback ifisinstance(response, StreamingHTTPResponse): await stream_callback(response) else: write_callback(response)