以其最简单的形式可调用的金字塔视图可以写成:
def myview(request):
pass
另一种形式是接受另一个参数 - 上下文:
def myview(context, request):
pass
金字塔视图查找机制如何知道视图可调用是否接受上下文?
答案 0 :(得分:4)
Pyramid使用inspect
模块检查视图(特别是requestonly()
function中的.getargspec()
调用:
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
如果视图不接受上下文,则其余代码会调整代码路径以省略上下文。