Esempio n. 1
0
    def route (self, conf, *args):
        router = get_router()
        router.set_logger(conf["log"]["level"], conf["log"]["file"])
        router.info("RapidSMS Server started up")
        
        # add each application from conf
        for app_conf in conf["rapidsms"]["apps"]:
            router.add_app(app_conf)

        # add each backend from conf
        for backend_conf in conf["rapidsms"]["backends"]:
            router.add_backend(backend_conf)

        # wait for incoming messages
        router.start()
        
        # TODO: Had to explicitly do this to end the script. Will need a fix.
        sys.exit(0)
Esempio n. 2
0
    def __init__(self, backend, identity):
        # Ok, connections should be able to find their backend even
        # for a name. 
        #
        # NOTE: The whole 'finding' a backend from a stored 'slug'
        # is _messed_ and probably shouldn't be here, but putting it
        # here for now at least encapsulates it in core where it 
        # should be instead of floating around everyone's app
        #
        if isinstance(backend,basestring):
            # try to find it from the router
            backend=router.get_router().get_backend(backend)

        if backend is None:
            raise Exception(\
                '%s is not a valid backend, did you add it to your rapidsms.ini?' % backend)
        
        self.backend = backend
        # unique identity with respect to backend
        # (usually phone number, but may be a port number
        # or email address, etc)
        self.identity = identity
Esempio n. 3
0
def dispatch(hnd):
    """
    A function to dispatch request to appropriate handler class
    """
    # resolve the URL
    url = hnd.request.path
    r = get_router()
    route = r.match(url)

    if not route:
        fr = get_fallback_router()
        fr.match(url)
        route = fr.match(url)
        if not route:
            # raise exception because we couldn't find route for given url
            hnd.response.set_status(404)
            raise Exception('No route for url:%s' % url)

    # create the appropriate controller
    ctrlname = route['controller']
    plugin = ''
    if '.' in ctrlname:
        plugin, ctrlname = ctrlname.split('.')
    ctrl_clz = get_controller_class(ctrlname, plugin)

    # create a controller instance
    ctrl = ctrl_clz(hnd, route)
    #setting attributes

    # mixin application base controller
    try:
        exec('from controller import application') in globals()
        if application.Application not in ctrl_clz.__bases__:
            ctrl_clz.__bases__ += (application.Application,)
        if hasattr(ctrl, 'application_init'):
            ctrl.application_init()
    except:
        pass

    # dispatch
    logging.debug('URL "%s" is dispatched to: %sController#%s',
                 url,
                 route['controller'].capitalize(),
                 route.get('action', 'index'))

    ctrl.config = Config()

    # get the action from the controller
    actionmethod = getattr(ctrl, route.get('action', 'index'), None)

    # if the action is none ,
    #   or it is not decorated by using expose, raise exception
    #   to avoid unintended method traversal.
    if not actionmethod or not getattr(actionmethod, '_exposed_', False):
        if not ctrl.config.debug:
            try:
                PAGE_CACHE_EXPIRE = config.page_cache_expire
            except AttributeError:
                PAGE_CACHE_EXPIRE = 60*60
            p = urlsplit(hnd.request.url)[2]
            memcache.set(p, 'error', PAGE_CACHE_EXPIRE)
            logging.debug('%s is cahed as a error page' % p)
        ctrl.response.set_status(404)
        m = '%s %s (Method not found)'
        raise Exception(m % ctrl.response._Response__status)

    # if before_action returns False, terminate the remain action
    if ctrl.before_action() != False:
        if ismethod(actionmethod):
            actionmethod()
        else:
            actionmethod()
        ctrl.after_action()

    #check status
    st = ctrl.response._Response__status[0]
    if st == 401 and ctrl.response.headers.get('WWW-Authenticate'):
        ctrl.put_cookies()
        return
    if st >= 400:
        # error occured
        raise Exception('%s %s' % ctrl.response._Response__status)

    if not ctrl.has_rendered and not ctrl.has_redirected:
        ctrl.render(template = route['action'], values = ctrl.__dict__)

    ctrl.put_cookies()
Esempio n. 4
0
 def test_good_app(self):
     """Test a good app that conforms to the convention in router.py module
     docstring.
     """
     test_router = router.get_router(self.good_app_path, self.version)
     self.assertIsInstance(test_router, routers.SimpleRouter)