Python 金字塔中的自定义路由谓词
我正在我的一个金字塔应用程序中使用一些自定义谓词。从1.5版开始,启动应用程序时,将显示以下消息:Python 金字塔中的自定义路由谓词,python,pyramid,Python,Pyramid,我正在我的一个金字塔应用程序中使用一些自定义谓词。从1.5版开始,启动应用程序时,将显示以下消息: my_project\__init__.py:110: DeprecationWarning: The "custom_predicates" argument to Configurator.add_route is deprecated as of Pyramid 1.5. Use "config.add_route_predicate" and use the registered rou
my_project\__init__.py:110: DeprecationWarning: The "custom_predicates"
argument to Configurator.add_route is deprecated as of Pyramid 1.5. Use
"config.add_route_predicate" and use the registered route predicate as a
predicate argument to add_route instead. See "Adding A Third Party
View,Route, or Subscriber Predicate" in the "Hooks" chapter
of the documentation for more information.
我想用新方法。。。但我找不到一条关于如何做到这一点的建议
即使是文档也说明了旧方法:
我尝试在我的my_project\\uu init\uuuuuuuuuuupy
文件中定义我的自定义谓词,使用类似于:
def my_predicate(info, request):
if request.something:
return True
return False
def main(global_config, **settings):
...
config.add_route_predicate('my_predicate_name', my_predicate)
config.add_route('my_route_name','/route_name/', 'my_predicate_name')
...
但是这没有任何效果,我知道使用“我的谓词名称”
不是好方法。。。我知道我错过了什么,但我就是不能得到什么
编辑
如果我将代码更改为:
config.add_route('my_route_name','/route_name/', my_predicate_name=True)
然后Pyramid抛出以下错误:
NameError: global name 'my_predicate_name' is not defined
看起来,
add\u route\u谓词
没有任何效果…文档中的这个位置应该解释如何实现自定义谓词:
这里还有一个例子。只有当查询参数中有lang=fr
时,才能返回法语响应,否则默认情况下,英语响应匹配
所以/
返回你好
和/?lang=fr
返回你好
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('Hello')
class LanguagePredicate():
def __init__(self, val, config):
self.val = val
def text(self):
return 'lang = %s' % (self.val,)
phash = text
def __call__(self, context, request):
return request.GET.get('lang') == self.val
def hello_world_fr(request):
return Response('bonjour')
def main():
config = Configurator()
config.add_route_predicate('lang', LanguagePredicate)
config.add_route('hello_fr', '/', lang='fr')
config.add_route('hello', '/')
config.add_view(hello_world_fr, route_name='hello_fr')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
return app
if __name__ == '__main__':
app = main()
server = make_server('0.0.0.0', 6547, app)
print ('Starting up server on http://localhost:6547')
server.serve_forever()
我更新了我的答案,使用add_route_谓词。模式相同,文档同时适用于视图谓词和路由谓词。。。如果有的话,它应该是
config.add_route('my_route_name','/route_name/',my_predicate_name=True)
对不起。。。这是一个打字错误,我更新了我的问题