Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a trailing slash optional with webapp2?

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:

webapp.Route('/feed', handler = feed)

I've tried /feed/?, /feed/*, /feed\/* and /feed\/?, all to no avail.

like image 790
Sudhir Jonathan Avatar asked Jan 12 '12 11:01

Sudhir Jonathan


2 Answers

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

like image 103
Aneon Avatar answered Sep 20 '22 01:09

Aneon


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.

  1. /
  2. /feed
  3. /feed/
  4. /feed/create
  5. /feed/create/
  6. /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 :-)

like image 27
stun Avatar answered Sep 21 '22 01:09

stun