How do I make a trailing slash optional with webapp2?

后端 未结 9 849
感情败类
感情败类 2021-02-12 15:30

I\'m using the new webapp2 (now the default webapp in 1.6), and I haven\'t been able to figure out how to make the trailing slash optional in code like this:

web         


        
9条回答
  •  春和景丽
    2021-02-12 16:14

    If you don't want to use redirects (and you probably don't), you can override Route.match():

    from webapp2 import Route, _get_route_variables
    import urllib
    from webob import exc
    
    
    class SloppyRoute(Route):
        """
        A route with optional trailing slash.
        """
        def __init__(self, *args, **kwargs):
            super(SloppyRoute, self).__init__(*args, **kwargs)
    
        def match(self, request):
            path = urllib.unquote(request.path)
            match = self.regex.match(path)
            try:
                if not match and not path.endswith('/'):
                    match = self.regex.match(path + '/')
            except:
                pass
            if not match or self.schemes and request.scheme not in self.schemes:
                return None
    
            if self.methods and request.method not in self.methods:
                # This will be caught by the router, so routes with different
                # methods can be tried.
                raise exc.HTTPMethodNotAllowed()
    
            args, kwargs = _get_route_variables(match, self.defaults.copy())
            return self, args, kwargs
    

提交回复
热议问题