问题描述
我的目标:在 Pyramid 中,调用另一个视图可调用对象,并在不知道该视图可调用对象的任何详细信息的情况下返回一个 Response
对象.
My goal: In Pyramid, to call another view-callable, and to get a Response
object back without knowing any details about that view-callable.
在我的 Pyramid 应用程序中,假设我有一个使用 view_config 装饰器定义的视图foo":
In my Pyramid application, say I have a view "foo" which is defined using a view_config decorator:
@view_config(route_name="foo",
renderer="foo.jinja2")
def foo_view(request):
return {"whereami" : "foo!"}
现在说我想将bar"路由到暂时执行相同操作的视图,因此它在内部调用 foo_view
并返回其响应:
Now say that I want to route "bar" to a view that does the same thing for the time being, so it internally calls foo_view
and returns its Response:
@view_config(route_name="bar")
def bar_view(request):
return foo_view(request)
...但是等等!这是行不通的,因为 foo_view
不返回 Response
,它的 renderer 会返回.
...but wait! That doesn't work, since foo_view
doesn't return a Response
, its renderer does.
所以,这会起作用:
@view_config(route_name="bar",
renderer="foo.jinja2")
def bar_view(request):
return foo_view(request)
因为它将应用与 foo_view
相同的渲染器.但这很糟糕,因为我现在必须通过复制渲染器值来重复自己,并且必须知道被调用视图的渲染器.
as it will apply the same renderer as foo_view
did. But this is bad, as I now must repeat myself by copying the renderer value AND having to know the renderer of the view being called.
所以,我希望 Pyramid 中有一些可用的函数,它允许调用另一个可调用的视图并返回一个 Response
对象,而无需知道或关心它是如何呈现的:
So, I am going to hope that there is some function available in Pyramid that allows calling another view-callable and getting a Response
object back without knowing or caring how it was rendered:
@view_config(route_name="bar")
def bar_view(request):
response = some_function_that_renders_a_view_callable(foo_view, request)
return response
some_function_that_renders_a_view_callable
是什么?
pyramid.views.render_view
似乎按名称搜索视图;我不想给我的观点命名.
pyramid.views.render_view
appears to search for a view by name; I don't want to give my views names.
(注意:返回 HTTPFound 导致客户端重定向到目标路由是我试图避免的.我想内部"重定向).
(Note: Returning HTTPFound to cause the client to redirect to the target route is what I am trying avoid. I want to "internally" redirect).
推荐答案
是的.有一些顾虑
- 不返回响应
- 谓词/渲染器
- 权限
- 与旧请求关联的请求属性
这就是为什么你不应该从视图中调用视图作为函数,除非你知道你在做什么
Thats why you should not call view from view as function, unless you know what you doing
金字塔创建者为服务器端重定向做了很棒的工具 - http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/subrequest.html
Pyramid creators did awesome tool for server side redirect - http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/subrequest.html
这篇关于在 Pyramid 中调用另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!