Ejemplo n.º 1
0
    def dispatch(self, controller, request):
        """Dispatch a route and return back the appropiate response.

        :param controller: the mamba controller
        :type controller: :class:`~mamba.Controller`
        :param request: the HTTP request
        :type request: :class:`twisted.web.server.Request`
        """

        try:
            route = RouteDispatcher(self, controller, request).lookup()

            if type(route) is Route:
                # at this point we can get a Deferred or an inmediate result
                # depending on the user code
                result = defer.maybeDeferred(route, controller, request)
                result.addCallback(self._process, request)
                result.addErrback(self._process_error, request)
            elif route == 'NotImplemented':
                result = defer.succeed(response.NotImplemented(
                    UrlSanitizer().sanitize_container(
                        [controller.get_register_path()] + request.postpath
                    )
                ))
            else:
                msg = 'ERROR 404: {} not found'.format(
                    UrlSanitizer().sanitize_container(
                        [controller.get_register_path()] + request.postpath
                    )
                )
                result = defer.succeed(response.NotFound(
                    msg,
                    {'content-type': 'text/plain'}
                ))
        except TypeError as error:
            log.msg(error, logLevel=logging.WARN)
            result = defer.succeed(response.BadRequest(
                str(error),
                {'content-type': 'text/plain'}
            ))
        except Exception as error:
            log.err(error)
            result = response.InternalServerError(
                'ERROR 500: Internal server error: {}\n\t{}'.format(
                    type(error), error
                )
            )

        return result
Ejemplo n.º 2
0
    def __init__(self, router, controller, request, url=True):
        self.router = router
        self.request = request
        self.method = request.method
        self.controller_object = controller
        self.controller = controller.__class__.__name__
        if url is True:
            self.url = UrlSanitizer().sanitize_container(
                [controller.get_register_path()] + request.postpath)
        else:
            i = 0
            if controller.__parent__ in request.postpath:
                i = request.postpath.index(controller.__parent__) + 1

            self.url = UrlSanitizer().sanitize_container(request.postpath[i:])
Ejemplo n.º 3
0
 def __init__(self, router, controller, request):
     self.router = router
     self.request = request
     self.method = request.method
     self.controller = controller.__class__.__name__
     self.url = UrlSanitizer().sanitize_container(
         [controller.get_register_path()] + request.postpath)
Ejemplo n.º 4
0
    def install_routes(self, controller):
        """Install all the routes in a controller.

        :param controller: the controller where to fid routes
        :type controller: :class:`~mamba.Controller`
        """

        for func in inspect.getmembers(controller, predicate=inspect.ismethod):
            error = False
            if hasattr(func[1], 'route'):
                route = getattr(func[1], 'route')
                route.url = UrlSanitizer().sanitize_string(
                    controller.get_register_path() + route.url
                )
                route.compile()
                # normalize parameters
                real_args = inspect.getargspec(route.callback)[0]
                if real_args:
                    real_args = real_args[real_args.index('request') + 1:]
                    for arg in real_args:
                        if arg not in route.arguments.keys():
                            green = output.darkgreen
                            log.msg(
                                '{ERROR}: {arg} is not present in the {rout} '
                                'url for function {func_name}. Please, revise '
                                'your @route url string. The paramters names '
                                'in the url string should match the ones in '
                                'the function call. Skipping route registering'
                                '... this route ({route}) shouldn\'t be'
                                ' available at {controller}'.format(
                                    ERROR=output.brown('ERROR'),
                                    rout=green('@route'),
                                    arg=output.darkgreen(arg),
                                    func_name=green(route.callback.__name__),
                                    route=green('@route -> {}'.format(
                                        route.url
                                    )),
                                    controller=green(
                                        controller.__class__.__name__
                                    )
                                )
                            )
                            error = True

                if not error:
                    self.register_route(controller, route, func[0])
Ejemplo n.º 5
0
 def test_sanitize_container(self):
     self.assertEqual(
         UrlSanitizer().sanitize_container(['//test', '//url///']),
         '/test/url')
Ejemplo n.º 6
0
 def test_sanitize_string(self):
     self.assertEqual(UrlSanitizer().sanitize_string('//test////url///'),
                      '/test/url')