3

Currently I have pages accessed via:

www.foo.com/details.html?id=123

I'd like to make them more restful-like, such as by the following:

www.foo.com/details/123

I'm using Google App Engine. Currently the URL's are mapped in the html-mappings file:

 ('/details.html*', DetailsPage),

And then on the DetailsPage handler, it fetches the ID value via:

class DetailsPage(webapp.RequestHandler):
    def get(self):
        announcement_id = self.request.get("id")

How might I restructure this so that it can map the URL and a extract the ID via the other-formatted URL: www.foo.com/details/123

Thanks

Ofir
  • 8,194
  • 2
  • 29
  • 44
Cuga
  • 17,668
  • 31
  • 111
  • 166

1 Answers1

13

Rewrite your URL mapping like this:

('/details/(\d+)', DetailsPage),

(this requires that there be a trailing part of the URL that contains one or more digits and nothing else).

Then modify your DetailsPage::get() method to accept that id parameter, like:

class DetailsPage(webapp.RequestHandler):
    def get(self, announcement_id):
        # next line no longer needed
        # announcement_id = self.request.get("id") 

...and carry on with your code.

bgporter
  • 35,114
  • 8
  • 59
  • 65
  • Great! Thanks so much! One change-- I realized I was misleading with the description... what if the id I want to come after /details matches the regex: [a-zA-Z0-9-_] How can I make reflect this change? ('/details/[a-zA-Z0-9-_]', DetailsPage), doesn't seem to work (it kept giving me a 404 error). – Cuga Jan 05 '11 at 07:00
  • for that you can substitute `r"/details/(\w+)"` -- `\w` matches all those characters, the `+` requires that there be at least one matching character, and the parens capture the match into the parameter that's passed to your `get()` function. – bgporter Jan 05 '11 at 12:59