Optional URL Parameter in Route GAE webapp2

2019-04-10 02:32发布

I'm really new to Python and GAE. I'm setting up a basic CRUD app for some test data and am trying to get some routing for the admin pages going. I'd like to use the same page for creating and editing an object. So basically I want:

/admin/edit/<id>

where <id> is optional and /admin/edit will route to the same page. I tried adding <id:\w*> to the route which then allowed me to hit the page without supplying an id, but then when I supplied the id, I received a 404. Then I tried <id:\w+> and got a 404 with and without an id. I'm not having much luck.

Can anyone help me with what regex I need for this?

1条回答
成全新的幸福
2楼-- · 2019-04-10 03:16

You can set up a regex to parse IDs out of the URL. Here's a really premitive example using webapp2:

app = webapp2.WSGIApplication([('/', MainPage),
                               ('/property/(.*)', PropertyHandler)],
                              debug=True)

And you setup your request handler to accept the additional parameter:

class PropertyHandler(webapp2.RequestHandler):
    def get(self, propertyId):

For a real-world implementation, you'd want to be a bit more specific on the regex and add validation to the handler incase you get garbage or no ID.

查看更多
登录 后发表回答