是否可以从渲染器访问视图配置?通过视图配置,我的意思是传递给view_config()装饰器的参数。我的目标是在视图配置中添加一些设置,供渲染器使用。
我有一个自定义渲染器:
x === Object(x)
注册为:
class MyRenderer(object):
def __init__(self, info):
pass
def __call__(self, value, system):
# Get view options.
my_renderer_opts = ...
# Render using options.
...
然后在我看来,我有:
config.add_renderer('my_renderer', MyRenderer)
是否可以访问从class Page(object):
def __init__(self, request):
self.request = request
@pyramid.view.view_config(
route_name='root',
renderer='my_renderer',
my_renderer_opts={...}
)
def view(self):
pass
传递到my_renderer_opts
的{{1}}?
答案 0 :(得分:2)
如果您仍然不会按照说明实施它,也许deriver
会有所帮助:
from wsgiref.simple_server import make_server
from pyramid.view import view_config
from pyramid.config import Configurator
@view_config(route_name="hello", renderer="myrend", renderer_options={"a": 1})
def hello_world(request):
return "Hello World!"
def rendereropt_deriver(view, info):
options = info.options.get("renderer_options", {})
def wrapped(context, request):
setattr(request, "_renderer_options", options)
return view(context, request)
return wrapped
rendereropt_deriver.options = ("renderer_options",)
class MyRendererFactory:
def __init__(self, info):
self.info = info
def __call__(self, value, system):
options = getattr(system["request"], "_renderer_options", {})
print("`renderer_options` is {}".format(options))
return value
if __name__ == "__main__":
with Configurator() as config:
config.add_route("hello", "/")
config.add_view_deriver(rendereropt_deriver)
config.add_renderer("myrend", MyRendererFactory)
config.scan(".")
app = config.make_wsgi_app()
server = make_server("0.0.0.0", 8000, app)
server.serve_forever()