gpt4 book ai didi

python - 具有多个 View 参数的 Django 装饰器

转载 作者:太空宇宙 更新时间:2023-11-04 09:11:46 25 4
gpt4 key购买 nike

我在我的项目中使用了 Django 装饰器。我正在使用带参数的多个 View ,我需要调用 1 个装饰器。

我只希望一个 View 使用其参数调用一次。但是无论我在哪里使用装饰器,装饰器都会给出每个 View 的值。

我希望参数属于我调用的特定 View 。

我的观点和装饰者是:

def d(msg='my default message'):
def decorator(func):
print msg
def newfn(request, **kwargs):
return func(request, **kwargs)
return newfn
return decorator

@d('This is working')
def company_add(request):
return ...

@d('Dont come')
def company_list(request, comp_id = None):
return ...

如果我调用 company_add View ,我得到的输出为:

This is working
Dont come

但我的预期结果是

This is working.

任何人都可以帮助我只打印属于特定 View 的参数。

最佳答案

当你用 @d(arg) 包装函数时,你实际上在运行之前用 msg=arg 运行了 d 函数的主体修饰函数,当然还有打印 msg。您可以将 print 语句放在其他地方,例如:

def d(msg='my default message'):
def decorator(func):
def newfn(request, **kwargs):
print msg
return func(request, **kwargs)
return newfn
return decorator

关于python - 具有多个 View 参数的 Django 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14053050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com