Esempio n. 1
0
    def __init__(self, formatter=None, parser=None, error_handler=None,
                       pre_processor=None, post_processor=None):
        self.route = singledispatch(self.route)
        self.route.register(str, self.route_decorator)

        if error_handler is None:
            error_handler = ErrorHandler()
            error_handler.register(BaseException, self._handle_exception)
            error_handler.register(HTTPException, self._handle_http_exception)

        if parser is None:
            parser = Parser()
        
        if formatter is None:
            formatter = Formatter()
            formatter.register('text/plain', str, default=True)

        self.formatter = formatter
        self.parser = parser
        self.error_handler = error_handler
        self.pre_processor = DataPipe() if pre_processor is None else pre_processor
        self.post_processor = DataPipe() if post_processor is None else post_processor

        self.resources = {}
        self.routes = []
        self.endpoints = {}
Esempio n. 2
0
    def dispatch(self):
        """
        Dispatch the current request to the appropriate resource, based on
        which resource the rule applies to.

        This function requires an active request context in order to work.
        """
        # TODO: document request context variables.
        request = ctx.request
        url_values = ctx.url_values
        resource = ctx.resource

        ctx.response = response = {'headers': {}} # response arguments

        try:
            data = resource.handle_request(request, url_values)
            response = {k:v for k,v in response.items() 
                        if k in ('status', 'headers')}

            if isinstance(data, (self.response_class, BaseResponse)):
                return data

            elif data is not None:
                process = DataPipe(
                    getattr(resource, 'post_processor', None),
                    self.post_processor
                )
                data = process(data)

                format = Formatter.compose(
                    getattr(resource, 'formatter', Formatter()),
                    self.formatter
                )
                mime_type, data = format(data)
                response['mimetype'] = mime_type
                response['response'] = data

            return self.response_class(**response)
        except BaseException as err:
            return self.error_handler(err)