Search code examples
google-app-engineurl-mapping

Google App engine Url Mapping using WSGIAppl and regex grouping Help Needed


take this example from google docs

class BrowseHandler(webapp.RequestHandler):

>     def get(self, category, product_id):
>         # Display product with given ID in the given category.
> 
> 
> # Map URLs like /browse/(category)/(product_id) to
> BrowseHandler. application =
> webapp.WSGIApplication([(r'/browse/(.*)/(.*)',
> BrowseHandler)
>                                      ],
>                                      debug=True)
> 
> def main():
>     run_wsgi_app(application)
> 
> if __name__ == '__main__':
>     main()

How can i change the regx groupings so that Product id is optional

ie the url http://yourdomain.com/category will be sent to the browse handler in the current above example you must add a product id or at least the / after the category

ie

http://yourdomain.com/category/

r'/browse/(.)/(.)'

Any ideas?


Solution

  • You can use two regular expressions mapped to same handler:

    class BrowseHandler(webapp.RequestHandler):
    
        def get(self, category, product_id=None):
            # Display product with given ID in the given category.
    
    
    # Map URLs like /browse/(category)/(product_id) to
    BrowseHandler. application =
    webapp.WSGIApplication([(r'/browse/(.*)/(.*)', BrowseHandler),
                            (r'/browse/(.*)', BrowseHandler),
                           ], debug=True)
    
    def main():
        run_wsgi_app(application)
    
    if __name__ == '__main__':
        main()