Calling another view in Pyramid

前端 未结 6 1396
庸人自扰
庸人自扰 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

    You can invoking a view with using request.invoke_subrequest:

    from wsgiref.simple_server import make_server
    
    from pyramid.config import Configurator
    
    from pyramid.request import Request
    
    
    def view_one(request):
    
        subreq = Request.blank('/view_two')
        response = request.invoke_subrequest(subreq)
        return response
    
    def view_two(request):
    
        request.response.body = 'This came from view_two'
        return request.response
    
    if __name__ == '__main__':
    
        config = Configurator()
        config.add_route('one', '/view_one')
        config.add_route('two', '/view_two')
        config.add_view(view_one, route_name='one')
        config.add_view(view_two, route_name='two')
        app = config.make_wsgi_app()
        server = make_server('0.0.0.0', 8080, app)
        server.serve_forever()`
    

    When /view_one is visted in a browser, the text printed in the browser pane will be "This came from view_two". The view_one view used the pyramid.request.Request.invoke_subrequest() API to obtain a response from another view (view_two) within the same application when it executed. It did so by constructing a new request that had a URL that it knew would match the view_two view registration, and passed that new request along to pyramid.request.Request.invoke_subrequest(). The view_two view callable was invoked, and it returned a response. The view_one view callable then simply returned the response it obtained from the view_two view callable.

提交回复
热议问题