3

可以以最简单的形式调用的 Pyramid 视图可以写成:

def myview(request):
    pass

另一种形式是接受另一个参数——上下文:

def myview(context, request):
    pass

Pyramid 视图查找机制如何知道可调用视图是否接受上下文?

4

1 回答 1

4

Pyramid 使用inspect模块检查视图(特别是函数.getargspec()中的调用:requestonly()

def requestonly(view, attr=None):
    ismethod = False
    if attr is None:
        attr = '__call__'
    if inspect.isroutine(view):
        fn = view
    elif inspect.isclass(view):
        try:
            fn = view.__init__
        except AttributeError:
            return False
        ismethod = hasattr(fn, '__call__')
    else:
        try:
            fn = getattr(view, attr)
        except AttributeError:
            return False

    try:
        argspec = inspect.getargspec(fn)
    except TypeError:
        return False

    args = argspec[0]

    if hasattr(fn, im_func) or ismethod:
        # it's an instance method (or unbound method on py2)
        if not args:
            return False
        args = args[1:]
    if not args:
        return False

    if len(args) == 1:
        return True

    defaults = argspec[3]
    if defaults is None:
        defaults = ()

    if args[0] == 'request':
        if len(args) - len(defaults) == 1:
            return True

    return False

如果视图不接受上下文,则其余代码会调整代码路径以省略上下文。

于 2013-03-09T19:42:30.507 回答