我将在@moraes 之上添加我的解决方案作为补充答案。
所以其他有以下问题的人可以获得更完整的答案。
- 斜线问题
- 可选参数问题
此外,我想出了如何在一个正则表达式中同时/entity/create
路由/entity/edit/{id}
。
以下是我支持以下 url 模式的路线。
- /
- /myentities
- /myentities/
- /myentities/创建
- /myentities/创建/
- /myentities/edit/{entity_id}
SITE_URLS = [
webapp2.Route(r'/', handler=HomePageHandler, name='route-home'),
webapp2.Route(r'/myentities/<:(create/?)|edit/><entity_id:(\d*)>',
handler=MyEntityHandler,
name='route-entity-create-or-edit'),
webapp2.SimpleRoute(r'/myentities/?',
handler=MyEntityListHandler,
name='route-entity-list'),
]
app = webapp2.WSGIApplication(SITE_URLS, debug=True)
下面是我BaseHandler
所有的处理程序都继承自。
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
# Sets the defaulte templates folder to the './app/templates' instead of 'templates'
jinja2.default_config['template_path'] = s.path.join(
os.path.dirname(__file__),
'app',
'templates'
)
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
下面是我的MyEntityHandler
python 类,带有Google App Engine Datastore APIget()
的方法签名。
class MyEntityHandler(BaseHandler):
def get(self, entity_id, **kwargs):
if entity_id:
entity = MyEntity.get_by_id(int(entity_id))
template_values = {
'field1': entity.field1,
'field2': entity.field2
}
else:
template_values = {
'field1': '',
'field2': ''
}
self.render_response('my_entity_create_edit_view_.html', **template_values)
def post(self, entity_id, **kwargs):
# Code to save to datastore. I am lazy to write this code.
self.redirect('/myentities')