Calling another view in Pyramid

前端 未结 6 1407
庸人自扰
庸人自扰 2021-02-02 16:02

My goal: In Pyramid, to call another view-callable, and to get a Response object back without knowing any details about that view-callable.

In my Pyramid a

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-02 16:25

    The Pyramid documentation here indicates that leaving the name key word argument out of view_config will cause the view to be registered by the function itself (rather than a string):

    Such a registration... implies that the view name will be *my_view*

    So, in your case you should be able to use pyramid.view.render_view or pyramid.view.render_view_to_response referencing foo_view directly:

    @view_config(route_name="bar")
    def bar_view(request):
        return pyramid.views.render_view_to_response(None, request, name=foo_view)
    

    Update:

    Yep, your right, passing the view function does not work.

    It's interesting, but taking your example code and applying the route_name to the config did not work for me. However, the following example, just giving the view a name sets the route url and gives the view a name. In this fashion render_view_to_response works as advertised. Naming, your views may not be what you want, but this configuration accomplishes the same thing as your example code without added configuration.

    @view_config(name="foo")
    def foo_view(request):
        # returning a response here, in lieu of having
        # declared a renderer to delegate to...
        return Response('Where am i? `{0[whereami]}'.format({"whereami" : "foo!"}))
    
    @view_config(name="bar")
    def bar_view(request):
        # handles the response if bar_view has a renderer 
        return render_view_to_response(None, request, name='foo')
    
    @view_config(name="baz")
    def baz_view(request):
        # presumably this would not work if foo_view was
        # not returning a Response object directly, as it
        # skips over the rendering part. I think you would
        # have to declare a renderer on this view in that case.
        return foo_view(request)
    
    if __name__ == '__main__':
        config = Configurator()
        config.scan()
        app = config.make_wsgi_app()
        serve(app, host='127.0.0.1', port='5000')
    

提交回复
热议问题