在Python Pyramid路由配置中使用查询字符串

mar*_*ark 6 python forms routes pyramid deform

这是我想要做的非常具体,所以我开始描述它是什么:

我想出了使用Matplotlib等渲染的所有部分,但我是Pyramid和Deform的新手.我还有一个工作视图,从文件中提供图.变形也是一种作品.目前还不清楚如何最好地构建ULR以区分服务,编辑和渲染用例.我猜在Pyramid中这意味着如何配置serve_view和edit_view的路由.

__init__.py:
    config.add_route('serve_route', 
        '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
    config.add_route('edit_route', 
        '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
# can I use query strings like "?action=edit" here to distinguish the difference?


views.py:
@view_config(context=Root, route_name='serve_route')
def plot_view(context, request):
... 
@view_config(context=Root, renderer='bunseki:templates/form.pt', route_name='edit_route')
def edit_view(request):
...
Run Code Online (Sandbox Code Playgroud)

我金字塔手册我找不到参考如何在路线中设置参数.我想指向一些文档或示例的指针就足够了,我可以自己弄清楚细节.谢谢!

Mic*_*kel 12

有两种方法可以执行此操作,具体取决于您希望分隔代码的方式.

  1. 将所有逻辑放入您的视图中,用'if'语句分隔request.GET.get('action').

    config.add_route('plot', '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
    config.scan()
    
    @view_config(route_name='plot')
    def plot_view(request):
        action = request.GET('action')
        if action == 'edit':
            # do something
            return render_to_response('bunseki:templates/form.pt', {}, request)
    
        # return the png
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用Pyramid的视图查找机制注册多个视图并在它们之间进行委托.

    config.add_route('plot', '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
    config.scan()
    
    @view_config(route_name='plot')
    def plot_image_view(request):
        # return the plot image
    
    @view_config(route_name='plot', request_param='action=edit',
                 renderer='bunseki:templates/form.pt')
    def edit_plot_view(request):
        # edit the plot
        return {}
    
    # etc..
    
    Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.这是注册单个url模式,并在该URL上对不同类型的请求使用不同视图的一个很好的示例.