我想知道:
是否可以在路由配置模式中提供默认值?
例如:我有一个视图,显示绑定到数据集的(可能很大)文件列表。
我想将视图拆分为多个页面,每个页面显示 100 个文件。当省略 url 模式中的页面部分时,我希望显示第一页。
所以我想要这样的东西:
config.add_route('show_files', '/show_files/{datasetid}/{page=1})
这是一个可行的替代方案吗? 我在金字塔文档中没有找到任何路由语法描述。
非常感谢!
您可能对这个答案感到满意,但另一种选择是使用分派到同一视图的多个路由。
config.add_route('show_files', '/show_files/{datasetid}')
config.add_route('show_files:page', '/show_files/{datasetid}/{page}')
@view_config(route_name='show_files')
@view_config(route_name='show_files:page')
def show_files_view(request):
page = request.matchdict.get('page', '1')
否,但您可以使用余数匹配使页面可选,然后决定在实际逻辑中显示哪个页面。
http://readthedocs.org/docs/pyramid/en/main/narr/urldispatch.html
另一种选择是让您的页面成为 GET 变量而不是 URL 的一部分。
设置此功能的一种(hacky)方法是使用自定义谓词。明确允许更改 matchdict。
def matchdict_default(**kw):
def f(info, request):
for k, v in kw.iteritems():
info['match'].setdefault(k, v)
return True
return f
config.add_route(
'show_files',
'/show_files/{datasetid}/{page}')
config.add_route(
'show_files',
'/show_files/{datasetid}',
custom_predicates=(matchdict_default(page=1),))
我无法让托马斯·荣格的例子发挥作用。我能够通过迭代键而不使用 iteritems() 来让 Thomas Jung 的示例工作。
def matchdict_default(**kw):
def f(info, request):
for k in kw:
info['match'].setdefault(k, kw[k])
return True
return f
config.add_route(
'show_files',
'/show_files/{datasetid}/{page}')
config.add_route(
'show_files',
'/show_files/{datasetid}',
custom_predicates=(matchdict_default(page=1),))`
now both of the following urls resolve to the page value, and, urls
can be created without needing to include a query
parameter
/show_files/an_id/
/show_files/an_id/?page=1