コード例 #1
0
def application(environ, start_response):
    # entry point
    global _url_map
    if not _url_map:
        _init_url_map()
    request = Request(environ)
    match_app = ''
    for regexp, app in _url_map:
        match_obj = regexp.match(request.path)
        if match_obj:
            # path info hack
            path_prefix = environ['PATH_PREFIX'] = match_obj.group()
            path_info = environ['ROOT_PATH_INFO'] = environ['PATH_INFO']
            new_path_info = path_info[len(path_prefix):]
            if new_path_info.startswith('/'):
                environ['PATH_INFO'] = new_path_info
            else:
                environ['PATH_INFO'] = '/' + new_path_info
            match_app = app
            break
    else:
        # no match patterns.
        raise Http404

    # select app
    from core.loader import get_application
    real_app = get_application(match_app)
    # run app
    return real_app(environ, start_response)
コード例 #2
0
def get_cache():
    if users.is_current_user_admin():
        return None
    env = dict(os.environ)
    env["wsgi.input"] = sys.stdin
    env["wsgi.errors"] = sys.stderr
    env["wsgi.version"] = (1, 0)
    env["wsgi.run_once"] = True
    env["wsgi.url_scheme"] = wsgiref.util.guess_scheme(env)
    env["wsgi.multithread"] = False
    env["wsgi.multiprocess"] = False
    req = Request(env)
    cached_resp = memcache.get(req.path_url.rstrip('/'))

    if cached_resp:

        def cache_app(env, start_resp):
            logging.info('returning cached page (%s)' % req.path_url)
            #BREAKPOINT()
            write_handle = start_resp(cached_resp.status,
                                      (cached_resp.headers.items()))
            write_handle(cached_resp.body)

        return cache_app
    else:

        return None
コード例 #3
0
 def test_search_4(self):
     handler = MyHandler()
     form = 'searchKeyword=Kony'
     handler.request = Request({
         'ACTION': '/searchQuery',
         'METHOD': 'get',
         'wsgi.input': StringIO(form),
         'CONTENT_LENGTH': len(form),
     })
コード例 #4
0
 def test_export_3(self):
     handler = MyHandler()
     s = "<crises>name </crises>"
     handler.request = Request({
         'ACTION': '/xmlExport',
         'METHOD': 'get',
         'wsgi.input': StringIO(s),
         'CONTENT_LENGTH': len(s),
     })
コード例 #5
0
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""
        request = Request(environ)
        response = Response()
        WSGIApplication.active_instance = self

        # Match the path against registered routes.
        kargs = self.mapper.match(request.path)
        if kargs is None:
            raise TypeError(
                'No routes match. Provide a fallback to avoid this.')

        # Extract the module and controller names from the route.
        try:
            module_name, class_name = kargs['controller'].split(':', 1)
        except (KeyError, ValueError):
            module_name = kargs['controller']
            class_name = module_name
        del kargs['controller']
        module_name = _CONTROLLERS_MODULE_PREFIX + '.' + module_name

        # Initialize matched controller from given module.
        try:
            __import__(module_name)
            module = sys.modules[module_name]
            controller = getattr(module, class_name)()
            controller.initialize(request, response)
        except (ImportError, AttributeError):
            logging.exception('Could not import controller %s:%s', module_name,
                              class_name)
            raise ImportError(
                'Controller %s from module %s could not be initialized.' %
                (class_name, module_name))

        # Use the action set in the route, or the HTTP method.
        if 'action' in kargs:
            action = kargs['action']
            del kargs['action']
        else:
            action = environ['REQUEST_METHOD'].lower()
            if action not in [
                    'get', 'post', 'head', 'options', 'put', 'delete', 'trace'
            ]:
                action = None

        if controller and action:
            try:
                # Execute the requested action, passing the route dictionary as
                # named parameters.
                getattr(controller, action)(**kargs)
            except error.AccessDenied, acl_e:
                logging.exception(acl_e)
                response.set_status(404)
            except Exception, e:
                # We want to catch any exception thrown by the controller and
                # pass it on to the controller's own exception handler.
                controller.handle_exception(e, self.__debug)
コード例 #6
0
 def test_upload_3(self):
     handler = MyHandler()
     f = open('nalmanza-WC1.xml')
     s = ""
     for line in f:
         s += line
     handler.request = Request({
         'ACTION': '/xmlupload',
         'METHOD': 'get',
         'wsgi.input': StringIO(s),
         'CONTENT_LENGTH': len(s),
     })
コード例 #7
0
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""

        url = URLGenerator(self.mapper, environ)
        environ['routes.url'] = url

        request = Request(environ)
        response = Response()
        WSGIApplication.active_instance = self
        # Match the path against registered routes.
        kargs = self.mapper.match(request.path)
        if kargs is None:
            raise TypeError(
                'No routes match. Provide a fallback to avoid this.')
        # Extract the module and controller names from the route.
        try:
            module_name, class_name = kargs['controller'].split(':', 1)
            del kargs['controller']
        except:
            raise TypeError(
                'Controller is not set, or not formatted in the form "my.module.name:MyControllerName".'
            )
        # Initialize matched controller from given module.
        try:
            __import__(module_name)
            module = sys.modules[module_name]
            controller = getattr(module, class_name)()
            controller.initialize(request, response)
        except:
            raise ImportError(
                'Controller %s from module %s could not be initialized.' %
                (class_name, module_name))
        # Use the action set in the route, or the HTTP method.
        if 'action' in kargs:
            action = kargs['action']
            del kargs['action']
        else:
            action = environ['REQUEST_METHOD'].lower()
            if action not in [
                    'get', 'post', 'head', 'options', 'put', 'delete', 'trace'
            ]:
                action = None
        if controller and action:
            try:
                # Execute the requested action, passing the route dictionary as
                # named parameters.
                getattr(controller, action)(**kargs)
            except Exception, e:
                controller.handle_exception(e, self.__debug)
            response.wsgi_write(start_response)
            return ['']
コード例 #8
0
ファイル: application.py プロジェクト: tobibeer/bidix
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""

        request = Request(environ)
        response = Response()

        # BidiX 2008-09-22 : try to setup a firewall at least a nop
        if banned_ip.is_banned(request.remote_addr):
            response.set_status(403)
            response.wsgi_write(start_response)
            return ['']

        WSGIApplication.active_instance = self

        handler = None
        groups = ()
        for regexp, handler_class in self._url_mapping:
            match = regexp.match(request.path)
            if match:
                handler = handler_class()
                handler.match = match  # BidiX 2008-05-22
                handler.initialize(request, response)
                groups = match.groups()
                break
        self.current_request_args = groups

        if handler:
            try:
                method = environ['REQUEST_METHOD']
                if method == 'GET':
                    handler.get(*groups)
                elif method == 'POST':
                    handler.post(*groups)
                elif method == 'HEAD':
                    handler.head(*groups)
                elif method == 'OPTIONS':
                    handler.options(*groups)
                elif method == 'PUT':
                    handler.put(*groups)
                elif method == 'DELETE':
                    handler.delete(*groups)
                elif method == 'TRACE':
                    handler.trace(*groups)
                else:
                    handler.error(501)
            except Exception, e:
                #handler.handle_exception(e, self.__debug) # BidiX 2008-05-22
                handler.handle_exception(e, True)  # BidiX 2008-05-22