Search code examples
pythongoogle-app-enginewebapp2

have slug in urls using webapp2


Problem: From jQuery i send a post request to server, the url i call is something like this: /get_post_data/my-custom-slug meaning i make a request to localhost:8080/get_post_data/my-custom-slug. But this may change to /my-custom-slug-two depending upon where the user clicks in the template. I want the url router to catch the slug and the handler function for that url to get the slug and based on the slug, i would call some model in my database fetch some data and send it back.

Solution Strategy: With the above in mind here is how i have designed my url router:

app = webapp2.WSGIApplication([('/', MainPage),
                               ('/get_post_data/<my_slug:[-\w]+>', PostData)
                               ],
                              debug=True)

and following is the url handler function:

class PostData(webapp2.RequestHandler):
  def post(self, my_slug):
    self.response.out.write(my_slug)

The trouble is: Ideally the output should be my-custom-slug but the trouble is i dont get the my_slug variable in the handler function. Where am i wrong?


Solution

  • You are almost there, just put it this way: ('/get_post_data/([-\w]+)', TeamRates) make sure you put () and in the views as described above, things should work.