金字塔

时间:2015-05-07 13:37:40

标签: python pyramid

我在我的一个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没有任何影响......

1 个答案:

答案 0 :(得分:3)

文档中的这个位置应该解释如何实现自定义谓词: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()