在 Pyramid 中分离 view_config 路由和渲染
我正在尝试实现一种模式,其中使用中间函数来确定要调用哪个函数并让最终函数进行渲染,但流程不会最终渲染。我缺少什么?有没有办法调整它以使其工作?
这就是我正在尝试的。
@view_config(route='fork_route')
def fork(self):
x = True
if x:
self.my_func1
else:
self.my_func2
#I expected it to render before this point
return dict({'msg':'failed'})
@view_config(renderer="templates/derived/template1")
def my_func1:
return dict({'msg':'msg1'})
@view_config(renderer="templates/derived/template2")
def my_func2:
return dict({'msg':'msg2'})
I am attempting to implement a pattern where I use an intermediate function to determine which function to call and have the final function do the rendering, but the flow does not end up rendering. What am I missing? Is there a way to tweak this to make it work?
Here's what I'm attempting.
@view_config(route='fork_route')
def fork(self):
x = True
if x:
self.my_func1
else:
self.my_func2
#I expected it to render before this point
return dict({'msg':'failed'})
@view_config(renderer="templates/derived/template1")
def my_func1:
return dict({'msg':'msg1'})
@view_config(renderer="templates/derived/template2")
def my_func2:
return dict({'msg':'msg2'})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Pyramid 的渲染器非常简单,最终它“只是 python”。这意味着您正在从函数调用函数,没有什么特别的。
Pyramid 自动渲染的工作方式是:
view_config
仅与当前请求的视图相关。您调用的其他函数只是 Python 中的函数。如果您仍然想将工作委托给另一个视图,那么有多种选择,但我们告诉人们的是,您需要在子视图或 <代码>render_to_response。当然,如果您只调用
render
那么您必须将该 html 正文转换为完整的Response
对象。请注意
myfunc1
如何返回一个Response
对象,以便fork
(对此请求处于活动状态的视图)可以返回它。否则,您需要将结果转化为响应:
每种方法显然都有好处和注意事项。
Pyramid's renderers are pretty simple, and in the end it's "just python". Meaning you're calling functions from functions, nothing special.
The way Pyramid's automated rendering works is:
The
view_config
is only relevant to the current request's view. The other functions you are calling are simply functions in Python.If you still want to delegate the work to another view then there are several options, but the one we tell people is that you will need to explicitly call
pyramid.renderers.render
within the sub-view orrender_to_response
. Of course if you only callrender
then you must turn that html body into a fullResponse
object.Notice how
myfunc1
returns aResponse
object sofork
(the view that is active for this request) can just return it.Otherwise you need to turn the result into a response:
There are obviously benefits and caveats to each approach.