Question

I have just started using Google App Engine and the webapp2 famework. Usually ,we start of building applications with the following code

class MainPage(webapp2.RequestHandler):
    def get(self):
        #do something

app = webapp2.WSGIApplication([('/blog',MainPage)])

Now sometimes when we register the handlers like this

app = webapp2.WSGIApplication([('/blog/(\d+)',MainPage)]

When we request the corresponding URL ,the get() method has to defined like

def get(self,post_id):

this post_id is the id present at the end of the URL we requested.

Now what I don't understand when does the get() method accept additional arguments like post_id in this case ? I mean ,all the regular expression (\d+) says is that if the URL ends with digits then map it to the MainPage handler . So when does webapp2 know when to send arguments/parameter to the get() function of the MainPage handler ?

Était-ce utile?

La solution

The pattern is matches against URLs as a regular-expression, and the brackets in the pattern constitute a 'capturing group', which means the part of the URL that matches that part of the pattern are, well, 'captured'. As it stands, the capture group is anonymous, and the argument passed to the handler is done so positionally (you don't have to call it post_id). Changing the pattern to (?P<post_id>\d+) makes it a 'named' group, and the argument to the handler will be a keyword-arg (the name of the argument is significant).

For completeness, if you want a group in your regular expression to be not-capturing (and so not passed as an argument), then indicate it like (?:\d+)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top