How Do I Make A Trailing Slash Optional With Webapp2?
Solution 1:
To avoid creating duplicate URL:s to the same page, you should use a RedirectRoute with strict_slash set to True to automatically redirect /feed/ to /feed, like this:
from webapp2_extras.routes import RedirectRoute
route = RedirectRoute('/feed', handler=feed, strict_slash=True)
Read more at http://webapp2.readthedocs.io/en/latest/api/webapp2_extras/routes.html
Solution 2:
I don't like the RedirectRoute
class because it causes an unnecessary HTTP Redirect.
Based on the documentation for webapp2 Route class, here is a more detailed answer in this webapp2.Route with optional leading part thread.
Short Answer
My route patterns works for the following URLs.
- /
- /feed
- /feed/
- /feed/create
- /feed/create/
- /feed/edit/{entity_id}
SITE_URLS = [
webapp2.Route(r'/', handler=HomePageHandler, name='route-home'),
webapp2.Route(r'/feed/<:(create/?)|edit/><entity_id:(\d*)>',
handler=MyFeedHandler,
name='route-entity-create-or-edit'),
webapp2.SimpleRoute(r'/feed/?',
handler=MyFeedListHandler,
name='route-entity-list'),
]
Hope it helps :-)
Solution 3:
Here's how I handle these routes.
from webapp2 importRoutefrom webapp2_extras.routesimportPathPrefixRouteimport handlers
urls = [
Route('/foo<:/?>', handlers.Foo),
Route('/bars', handlers.BarList),
PathPrefixRoute('/bar', [
Route('/', handlers.BarList),
Route('/<bar_id:\w+><:/?>', 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.
classBar(webapp2.RequestHandler):
defget(bar_id, *args, **kwargs):
# Lookup and render this Bar using bar_id.
...
Solution 4:
webapp2.Route
template is not a regular expressions and your value is being escaped with re.escape
. You can use old style rules which provides regular expression templates:
webapp2.SimpleRoute('^/feed/?$', handler = feed)
Solution 5:
This works for me and is very simple. It uses the template format for URI routing in the webapp2 Route class. Trailing slash in this example is optional with no redirection:
webapp2.Route('/your_url<:/?>', PageHandler)
Everything after the colon between the chevrons is considered to be a regex: <:regex>
Post a Comment for "How Do I Make A Trailing Slash Optional With Webapp2?"