How do I make a trailing slash optional with webapp2?

后端 未结 9 821
感情败类
感情败类 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:08

    I came up with a sort of hacky way. I define the following class:

    class UrlConf(object):
    
        def __init__(self, *args, **kwargs):
            self.confs = []
            for arg in args:
                if isinstance(arg, webapp2.Route):
                    slash_route = webapp2.Route(arg.template + '/', arg.handler)
                    self.confs += [arg, slash_route]
    
        def __iter__(self):
            for route in self.confs:
                yield route
    

    Then I set up my routes like the following:

    MIRROR_URLS = list(UrlConf(
        Route('/path/to/stuff', handler=StuffHandler, name='stuff.page'),
        Route('/path/to/more/stuff', handler= MoreStuffHandler, name='more.stuff.page')
    ))
    

    If you do choose to go this route, you can obviously improve upon it to be more flexible with other types of BaseRoute objects.

提交回复
热议问题