Reputation: 1074
In the last days I saw a lot of codes, like GAE Boilerplate, and almost all are using Routes to manage the page calls. And I'm wondering why? The official examples always uses the "normal" method:
app = webapp2.WSGIApplication([('/', MainPage),
('/lang', ChangeLanguage)], debug=True)
but now I discovered this alternatives:
from webapp2_extras.routes import RedirectRoute
RedirectRoute('/lang/<lang>', ChangeLanguage, name='lang', strict_slash=True),
RedirectRoute('/', MainPage, name='home', strict_slash=True)
In the first case, I'm using parameters to pass my vars on the request (like /lang?hl=en_US
) and in the second I must pass it as a path (like /lang/en_US
).
But why use one method or the other? Is there any advantage?
Also, I notice that with the first method my forms can be called, in the get and put methods, e.g., /register
, but with the routes, a get call for the same works, but when a post is done, it only works if the form action is /register/
(whith the last slash).
Upvotes: 1
Views: 180
Reputation: 435
One of the primary features webapp2
introduced over the original webapp
is precisely the extension of functionality the Route class provides.
The documentation gives a pretty good explanation of what it attempts to achieve:
webapp2 introduces a routing mechanism that extends the webapp model to provide additional features:
URI building: the registered routes can be built when needed, avoiding hardcoded URIs in the app code and templates. If you change the route definition in a compatible way during development, all places that use that route will continue to point to the correct URI. This is less error prone and easier to maintain.
Keyword arguments: handlers can receive keyword arguments from the matched URIs. This is easier to use and also more maintanable than positional arguments.
Nested routes: routes can be extended to match more than the request path. We will see below a route class that can also match domains and subdomains.
Bottom line, they're a more powerful version of routing, providing more features for the programmer.
As per your specific parameter question, you don't have to pass lang
any specific way. In the first case, lang
would be available as part of request.GET
, in the second, as a positional argument to your request handler's method that matches the request method (GET
, POST
).
The difference is largely that in the case of /lang?hl=en_US
, the argument is technically optional. Your request will still be matched with the handler even when the argument is absent, therefore you have to verify that request.GET
contains data.
In the second case, /lang/en_US
, the route is only matched, and thus the handler is only called when there's something to match in place of <lang>
.
As per the slashes issue, you're using the strict_slash
in your routes. more here
Upvotes: 3