def register_before_request(self, func): """ Register a function to called before we start to process request. """ if get_param_length(func) > 1: raise ValueError("`before_request` should have at most one param.") self.add_hook('_before_request', func)
def handle_after_request(self, response): func = self.hooks.get('_after_request') if func: if get_param_length(func) == 1: rsp = func(response) if not rsp or not isinstance(rsp, Response): raise ValueError('`after_request` must return a response.') else: rsp = func() else: rsp = response # do nothing and return the same reponse. return rsp
def make_error_response(self, err, request=None): """ Create error response from HTTP error. """ handler = self.error_handler.get(err.status) status = int(err.status) if not handler: reason = HTTP_STATUS.get(status) if not reason: status = 404 # reponse 404 while not reason find. reason = HTTP_STATUS[status] body = ERROR_TEMPLETE.format(status=status, reason=reason, message=err.message if self.debug else '') response = Response(body) else: if get_param_length(handler) == 1: response = handler(request) else: response = handler() return self.make_response(response, status)
def handle_before_request(self, request): func = self.hooks.get('_before_request') if func: if get_param_length(func) == 1: func = partial(func, request) # Pass current request context. return func()