简体   繁体   English

金字塔:从列表生成 json 视图

[英]Pyramid: generate json views from list

How to generate json views from a list of strings with Pyramid?如何使用 Pyramid 从字符串列表生成json视图?

With the following attempt only the view of the last element of the list is generated;通过以下尝试,只生成列表最后一个元素的视图; jkl_json in this case, the others produce 404 Not Found . jkl_json在这种情况下,其他人产生404 Not Found

names = ['abc', 'def', 'ghi', 'jkl']
for nm in names:
    @view_config(route_name='{}_json'.format(nm),
                 renderer='json',)
    def names_json(request):
        nm_cls = globals()[nm.title()]
        ...

This does actually work with html views;这实际上适用于 html 视图; but not with json views.但不是 json 视图。

I would suggest using the Configurator.add_view method to add views programmatically:我建议使用Configurator.add_view方法以编程方式添加视图:

def json_view(request):
    ...

names = ['abc', 'def', 'ghi', 'jkl']
for nm in names:
    config.add_view(json_view, route_name='{}_json'.format(nm),
                 renderer='json',)

Your approach with decorators in a loop is unlikely to work even with html I think...我认为,即使使用 html,您在循环中使用装饰器的方法也不太可能起作用......

This happens because Pyramid uses the Venusian library for decorators;发生这种情况是因为 Pyramid 使用 Venusian 库作为装饰器; they attach information to functions instead of registering the view instantly.他们将信息附加到函数而不是立即注册视图。 This information is later processed by config.scan , and only then is the route actually registered.此信息稍后由config.scan处理,然后才实际注册路由。 In your code you're replacing the names_json function with another function by the same name on each loop.在您的代码中,您将在每个循环中用另一个names_json函数替换names_json函数。 Since only last of them is visible in the module, with only the last view_config data attached to it, this is what Venusian picks up when scanning.由于模块中只有最后一个是可见的,只有最后一个view_config数据附加到它,这是 Venusian 在扫描时拾取的。


You should instead apply the decorators to exactly one function.相反,您应该将装饰器应用于一个函数。 If you remember that如果你记得那

 @view_config(route_name='foo')
 def bar(request):
     return Response()

is just syntactic sugar for只是语法糖

 def bar(request):
     return Response()

 bar = view_config(route_name='foo')

you can do你可以

def names_json(request):
    ...

names = ['abc', 'def', 'ghi', 'jkl']
for nm in names:
    names_json = view_config(route_name='{}_json'.format(nm),
             renderer='json')(names_json)

On the other hand, if the paths are like this, perhaps you can just use a single route for all of them:另一方面,如果路径是这样的,也许您可​​以只对所有路径使用一条路径:

config.add_route('names', '/foo/{name:abc|def|ghi|jkl}.json')

where the route would match any of /foo/abc.json , /foo/def.json , /foo/ghi.json or /foo/jkl.json , and the name would be available as request.matchdict['name'] within the view.其中路由将匹配/foo/abc.json/foo/def.json/foo/ghi.json/foo/jkl.json中的任何一个,并且名称可以作为request.matchdict['name']视图内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM