Understanding webapp2 routes

时间:2017-08-04 12:12:00

标签: python google-app-engine web-applications webapp2

Lets suppose i have the following webapp2 route.

webapp2.Route('/api/users/register/verify/<user_id:\d+>/<signup_token:.+>', users.VerificationHandler, name='verification')  

I know first part is the URL, then is the name of request handler, but i don't understand the purpose of name='verification'. Can someone please explain why name is used in webapp2 routes?

Moreover, what is the purpose of uri_for() function? why do we use it?

1 个答案:

答案 0 :(得分:2)

programatically webapp2 is class and Route was a function defined inside a class.

webapp2 is nothing but 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.

  • Keyword arguments: handlers can receive keyword arguments from the matched URIs.

  • 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.

Eg: webapp2.Route('/api/users/register/verify/<user_id:\d+>/<signup_token:.+>', handler=HomeHandler, name='verification')

from your example, name='verification'

it is alias for your url...

in your example,

your URL is : '/api/users/register/verify/<user_id:\d+>/<signup_token:.+>' you cant able to remember it right, so name will help you to alias it with memorable one verification.

so your URL, /api/users/register/verify/<user_id:\d+>/<signup_token:.+> = verification

alias will translate into original url in runtime

next, uri_for()

as i said, you assigned alias for your big URL.. so you knew shortest alias of it. if you want to retrieve URL from alias you can use this function,

print uri_for('verification') 

will give you, /api/users/register/verify/<user_id:\d+>/<signup_token:.+>