Example #1
0
    def __call__(self, environ, start_response):
        """Resolves the URL in PATH_INFO, and uses wsgi.routing_args
        to pass on URL resolver results."""
        old_method = None
        if self.use_method_override:
            req = None
            
            # In some odd cases, there's no query string
            try:
                qs = environ['QUERY_STRING']
            except KeyError:
                qs = ''
            if '_method' in qs:
                req = Request(environ)
                req.errors = 'ignore'
                if '_method' in req.GET:
                    old_method = environ['REQUEST_METHOD']
                    environ['REQUEST_METHOD'] = req.GET['_method'].upper()
                    if self.log_debug:
                        log.debug("_method found in QUERY_STRING, altering request"
                                " method to %s", environ['REQUEST_METHOD'])
            elif environ['REQUEST_METHOD'] == 'POST' and is_form_post(environ):
                if req is None:
                    req = Request(environ)
                    req.errors = 'ignore'
                if '_method' in req.POST:
                    old_method = environ['REQUEST_METHOD']
                    environ['REQUEST_METHOD'] = req.POST['_method'].upper()
                    if self.log_debug:
                        log.debug("_method found in POST data, altering request "
                                  "method to %s", environ['REQUEST_METHOD'])
        
        # Run the actual route matching
        # -- Assignment of environ to config triggers route matching
        if self.singleton:
            config = request_config()
            config.mapper = self.mapper
            config.environ = environ
            match = config.mapper_dict
            route = config.route
        else:
            results = self.mapper.routematch(environ=environ)
            if results:
                match, route = results[0], results[1]
            else:
                match = route = None
                
        if old_method:
            environ['REQUEST_METHOD'] = old_method
        
        if not match:
            match = {}
            if self.log_debug:
                urlinfo = "%s %s" % (environ['REQUEST_METHOD'], environ['PATH_INFO'])
                log.debug("No route matched for %s", urlinfo)
        elif self.log_debug:
            urlinfo = "%s %s" % (environ['REQUEST_METHOD'], environ['PATH_INFO'])
            log.debug("Matched %s", urlinfo)
            log.debug("Route path: '%s', defaults: %s", route.routepath, 
                      route.defaults)
            log.debug("Match dict: %s", match)
                
        url = URLGenerator(self.mapper, environ)
        environ['wsgiorg.routing_args'] = ((url), match)
        environ['routes.route'] = route
        environ['routes.url'] = url

        if route and route.redirect:
            route_name = '_redirect_%s' % id(route)
            location = url_for(route_name, **match)
            log.debug("Using redirect route, redirect to '%s' with status"
                      "code: %s", location, route.redirect_status)
            start_response(route.redirect_status, 
                           [('Content-Type', 'text/plain; charset=utf8'), 
                            ('Location', location)])
            return []

        # If the route included a path_info attribute and it should be used to
        # alter the environ, we'll pull it out
        if self.path_info and 'path_info' in match:
            oldpath = environ['PATH_INFO']
            newpath = match.get('path_info') or ''
            environ['PATH_INFO'] = newpath
            if not environ['PATH_INFO'].startswith('/'):
                environ['PATH_INFO'] = '/' + environ['PATH_INFO']
            environ['SCRIPT_NAME'] += re.sub(r'^(.*?)/' + re.escape(newpath) + '$', 
                                             r'\1', oldpath)
        
        response = self.app(environ, start_response)
        
        # Wrapped in try as in rare cases the attribute will be gone already
        try:
            del self.mapper.environ
        except AttributeError:
            pass
        return response
Example #2
0
    def __call__(self, environ, start_response):
        """Resolves the URL in PATH_INFO, and uses wsgi.routing_args
        to pass on URL resolver results."""
        config = request_config()
        config.mapper = self.mapper

        old_method = None
        if self.use_method_override:
            req = None

            # In some odd cases, there's no query string
            try:
                qs = environ['QUERY_STRING']
            except KeyError:
                qs = ''
            if '_method' in qs:
                req = Request(environ)
                req.errors = 'ignore'
                if '_method' in req.GET:
                    old_method = environ['REQUEST_METHOD']
                    environ['REQUEST_METHOD'] = req.GET['_method'].upper()
                    if self.log_debug:
                        log.debug(
                            "_method found in QUERY_STRING, altering request"
                            " method to %s", environ['REQUEST_METHOD'])
            elif environ['REQUEST_METHOD'] == 'POST' and is_form_post(environ):
                if req is None:
                    req = Request(environ)
                    req.errors = 'ignore'
                if '_method' in req.POST:
                    old_method = environ['REQUEST_METHOD']
                    environ['REQUEST_METHOD'] = req.POST['_method'].upper()
                    if self.log_debug:
                        log.debug(
                            "_method found in POST data, altering request "
                            "method to %s", environ['REQUEST_METHOD'])

        # Run the actual route matching
        # -- Assignment of environ to config triggers route matching
        config.environ = environ

        match = config.mapper_dict
        route = config.route

        if old_method:
            environ['REQUEST_METHOD'] = old_method

        if not match:
            match = {}
            if self.log_debug:
                urlinfo = "%s %s" % (environ['REQUEST_METHOD'],
                                     environ['PATH_INFO'])
                log.debug("No route matched for %s", urlinfo)
        elif self.log_debug:
            urlinfo = "%s %s" % (environ['REQUEST_METHOD'],
                                 environ['PATH_INFO'])
            log.debug("Matched %s", urlinfo)
            log.debug("Route path: '%s', defaults: %s", route.routepath,
                      route.defaults)
            log.debug("Match dict: %s", match)

        url = URLGenerator(self.mapper, environ)
        environ['wsgiorg.routing_args'] = ((url), match)
        environ['routes.route'] = route
        environ['routes.url'] = url

        if route and route.redirect:
            route_name = '_redirect_%s' % id(route)
            location = url_for(route_name, **match)
            log.debug(
                "Using redirect route, redirect to '%s' with status"
                "code: %s", location, route.redirect_status)
            start_response(route.redirect_status,
                           [('Content-Type', 'text/plain; charset=utf8'),
                            ('Location', location)])
            return []

        # If the route included a path_info attribute and it should be used to
        # alter the environ, we'll pull it out
        if self.path_info and 'path_info' in match:
            oldpath = environ['PATH_INFO']
            newpath = match.get('path_info') or ''
            environ['PATH_INFO'] = newpath
            if not environ['PATH_INFO'].startswith('/'):
                environ['PATH_INFO'] = '/' + environ['PATH_INFO']
            environ['SCRIPT_NAME'] += re.sub(
                r'^(.*?)/' + re.escape(newpath) + '$', r'\1', oldpath)
            if environ['SCRIPT_NAME'].endswith('/'):
                environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1]

        response = self.app(environ, start_response)

        # Wrapped in try as in rare cases the attribute will be gone already
        try:
            del config.environ
            del self.mapper.environ
        except AttributeError:
            pass
        return response
Example #3
0
    def __call__(self, environ, start_response):
        """Resolves the URL in PATH_INFO, and uses wsgi.routing_args to pass 
        on URL resolver results."""
        config = request_config()
        config.mapper = self.mapper

        old_method = None
        if self.use_method_override:
            req = WSGIRequest(environ)
            req.errors = "ignore"
            if "_method" in environ.get("QUERY_STRING", "") and "_method" in req.GET:
                old_method = environ["REQUEST_METHOD"]
                environ["REQUEST_METHOD"] = req.GET["_method"].upper()
                log.debug("_method found in QUERY_STRING, altering request" " method to %s", environ["REQUEST_METHOD"])
            elif (
                environ["REQUEST_METHOD"] == "POST"
                and "application/x-www-form-urlencoded" in environ.get("CONTENT_TYPE", "")
                and "_method" in req.POST
            ):
                old_method = environ["REQUEST_METHOD"]
                environ["REQUEST_METHOD"] = req.POST["_method"].upper()
                log.debug("_method found in POST data, altering request " "method to %s", environ["REQUEST_METHOD"])

        config.environ = environ
        match = config.mapper_dict
        route = config.route

        if old_method:
            environ["REQUEST_METHOD"] = old_method

        urlinfo = "%s %s" % (environ["REQUEST_METHOD"], environ["PATH_INFO"])
        if not match:
            match = {}
            log.debug("No route matched for %s", urlinfo)
        else:
            log.debug("Matched %s", urlinfo)
            log.debug("Route path: '%s', defaults: %s", route.routepath, route.defaults)
            log.debug("Match dict: %s", match)

        for key, val in match.iteritems():
            if val and isinstance(val, basestring):
                match[key] = urllib.unquote_plus(val)

        environ["wsgiorg.routing_args"] = ((), match)
        environ["routes.route"] = route

        # If the route included a path_info attribute and it should be used to
        # alter the environ, we'll pull it out
        if self.path_info and match.get("path_info"):
            oldpath = environ["PATH_INFO"]
            newpath = match.get("path_info") or ""
            environ["PATH_INFO"] = newpath
            if not environ["PATH_INFO"].startswith("/"):
                environ["PATH_INFO"] = "/" + environ["PATH_INFO"]
            environ["SCRIPT_NAME"] += re.sub(r"^(.*?)/" + newpath + "$", r"\1", oldpath)
            if environ["SCRIPT_NAME"].endswith("/"):
                environ["SCRIPT_NAME"] = environ["SCRIPT_NAME"][:-1]

        response = self.app(environ, start_response)
        del config.environ
        del self.mapper.environ
        return response
Example #4
0
    def __call__(self, environ, start_response):
        """Resolves the URL in PATH_INFO, and uses wsgi.routing_args to pass 
        on URL resolver results."""
        config = request_config()
        config.mapper = self.mapper

        old_method = None
        if self.use_method_override:
            req = WSGIRequest(environ)
            req.errors = 'ignore'
            if '_method' in environ.get('QUERY_STRING', '') and \
                '_method' in req.GET:
                old_method = environ['REQUEST_METHOD']
                environ['REQUEST_METHOD'] = req.GET['_method'].upper()
                log.debug(
                    "_method found in QUERY_STRING, altering request"
                    " method to %s", environ['REQUEST_METHOD'])
            elif is_form_post(environ) and '_method' in req.POST:
                old_method = environ['REQUEST_METHOD']
                environ['REQUEST_METHOD'] = req.POST['_method'].upper()
                log.debug(
                    "_method found in POST data, altering request "
                    "method to %s", environ['REQUEST_METHOD'])

        # Run the actual route matching
        # -- Assignment of environ to config triggers route matching
        config.environ = environ

        match = config.mapper_dict
        route = config.route

        if old_method:
            environ['REQUEST_METHOD'] = old_method

        urlinfo = "%s %s" % (environ['REQUEST_METHOD'], environ['PATH_INFO'])
        if not match:
            match = {}
            log.debug("No route matched for %s", urlinfo)
        else:
            log.debug("Matched %s", urlinfo)
            log.debug("Route path: '%s', defaults: %s", route.routepath,
                      route.defaults)
            log.debug("Match dict: %s", match)

        for key, val in match.iteritems():
            if val and isinstance(val, basestring):
                match[key] = urllib.unquote_plus(val)

        environ['wsgiorg.routing_args'] = ((), match)
        environ['routes.route'] = route

        # If the route included a path_info attribute and it should be used to
        # alter the environ, we'll pull it out
        if self.path_info and match.get('path_info'):
            oldpath = environ['PATH_INFO']
            newpath = match.get('path_info') or ''
            environ['PATH_INFO'] = newpath
            if not environ['PATH_INFO'].startswith('/'):
                environ['PATH_INFO'] = '/' + environ['PATH_INFO']
            environ['SCRIPT_NAME'] += re.sub(r'^(.*?)/' + newpath + '$', r'\1',
                                             oldpath)
            if environ['SCRIPT_NAME'].endswith('/'):
                environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1]

        response = self.app(environ, start_response)
        del config.environ
        del self.mapper.environ
        return response
Example #5
0
    def __call__(self, environ, start_response):
        """Resolves the URL in PATH_INFO, and uses wsgi.routing_args to pass 
        on URL resolver results."""
        config = request_config()
        config.mapper = self.mapper
        
        old_method = None
        if self.use_method_override:
            req = WSGIRequest(environ)
            req.errors = 'ignore'
            if '_method' in environ.get('QUERY_STRING', '') and \
                '_method' in req.GET:
                old_method = environ['REQUEST_METHOD']
                environ['REQUEST_METHOD'] = req.GET['_method'].upper()
                log.debug("_method found in QUERY_STRING, altering request"
                          " method to %s", environ['REQUEST_METHOD'])
            elif is_form_post(environ) and '_method' in req.POST:
                old_method = environ['REQUEST_METHOD']
                environ['REQUEST_METHOD'] = req.POST['_method'].upper()
                log.debug("_method found in POST data, altering request "
                          "method to %s", environ['REQUEST_METHOD'])
        
        # Run the actual route matching
        # -- Assignment of environ to config triggers route matching
        config.environ = environ
        
        match = config.mapper_dict
        route = config.route
        
        if old_method:
            environ['REQUEST_METHOD'] = old_method
        
        urlinfo = "%s %s" % (environ['REQUEST_METHOD'], environ['PATH_INFO'])
        if not match:
            match = {}
            log.debug("No route matched for %s", urlinfo)
        else:
            log.debug("Matched %s", urlinfo)
            log.debug("Route path: '%s', defaults: %s", route.routepath, 
                      route.defaults)
            log.debug("Match dict: %s", match)
                
        environ['wsgiorg.routing_args'] = ((), match)
        environ['routes.route'] = route

        # If the route included a path_info attribute and it should be used to
        # alter the environ, we'll pull it out
        if self.path_info and match.get('path_info'):
            oldpath = environ['PATH_INFO']
            newpath = match.get('path_info') or ''
            environ['PATH_INFO'] = newpath
            if not environ['PATH_INFO'].startswith('/'):
                environ['PATH_INFO'] = '/' + environ['PATH_INFO']
            environ['SCRIPT_NAME'] += re.sub(r'^(.*?)/' + newpath + '$', 
                                             r'\1', oldpath)
            if environ['SCRIPT_NAME'].endswith('/'):
                environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1]
        
        response = self.app(environ, start_response)
        del config.environ
        del self.mapper.environ
        return response