I want to create a RESTFUL web service that gets a request via the URL that is accessed and then returns the appropriate document for that client. For example, if it was a weather app and I wanted to get the weather for Atlanta through a web browser, I would access http://weatherapp.appspot.com/temperature/Atlanta and it would return an HTML document with the information for Atlanta. I don't want anything that ties into a database as I am just trying to wrap another website via screen-scraping. Does anyone have any examples on how to get arguments from the url?
1 Answer
Using the webapp framework, you can capture regular expression groups and pass them to your handler like this:
class WeatherHandler(webapp.RequestHandler):
def get(self, location):
# Do something for location
application = webapp.WSGIApplication([
('/temperature/(.*)', WeatherHandler),
])
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Any parenthesized groups in the regular expression are collected and passed as positional arguments to the get/post/etc methods on your handler.
3 Comments
Chris Jaynes
Couldn't you use the app.yaml file to map the URLs?
Nick Johnson
@Chris app.yaml instructs the infrastructure to what script to route the request. Since requests are made using CGI, there's no way to capture subgroups there. It's still up to the individual script to route requests to the appropriate handler, as above.
Nick Johnson
@AvinashRaj It doesn't matter in this case, because there are no escape sequences in the regex.