【问题标题】:Custom route predicates in PyramidPyramid 中的自定义路由谓词
【发布时间】:2015-07-18 03:02:00
【问题描述】:

我在我的一个 Pyramid 应用程序中使用了一些自定义谓词。从 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 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.

我想使用新方法...但我找不到一条关于如何做到这一点的建议...

即使是文档也说明了旧方法:https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#custom-route-predicates

我尝试在 my_project\__init__.py 文件中定义我的自定义谓词,使用类似:

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')
    ...

但这没有任何效果,我知道使用'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_route_predicate 没有任何作用...

【问题讨论】:

  • 请注意,您最后的代码 sn-p 不是有效的 Python...如果有的话,应该是 config.add_route('my_route_name', '/route_name/', my_predicate_name=True)
  • 对不起...这是一个错字,我更新了我的问题

标签: python pyramid


【解决方案1】:

文档中的此位置应说明如何实现自定义谓词:http://docs.pylonsproject.org/projects/pyramid/en/master/narr/hooks.html#view-and-route-predicates

这是一个额外的例子。仅当lang=fr 在查询参数中时才应返回法语响应,否则默认情况下匹配英语响应。

所以/ 返回Hello/?lang=fr 返回bonjour

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_predicate。模式是相同的,文档适用于视图和路由谓词。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 2017-06-11
  • 2017-10-27
  • 2011-07-13
  • 1970-01-01
相关资源
最近更新 更多