How do I make a trailing slash optional with webapp2?

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

    Here's how I handle these routes.

    from webapp2 import Route
    from webapp2_extras.routes import PathPrefixRoute
    import handlers
    
    urls = [
      Route('/foo<:/?>', handlers.Foo),
      Route('/bars', handlers.BarList),
      PathPrefixRoute('/bar', [
        Route('/', handlers.BarList),
        Route('/<:/?>', handlers.Bar),
      ]),
    ]
    ...
    

    It's important to note that your handlers will need to define *args and **kwargs to deal with the potential trailing slash, which gets sent to them as an argument using this method.

    class Bar(webapp2.RequestHandler):
    
      def get(bar_id, *args, **kwargs):
        # Lookup and render this Bar using bar_id.
        ...
    

提交回复
热议问题