gpt4 book ai didi

python - 仅在 python 中对 POST 请求使用装饰器

转载 作者:行者123 更新时间:2023-11-28 22:54:09 25 4
gpt4 key购买 nike

我想定义一个装饰器,如果满足条件,它将应用另一个装饰器,
否则它只会简单地发挥作用。

下面不行..

def decorator_for_post(view_func):

@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):

if request.method == 'POST':
return another_decorator(view_func) # we apply **another_decorator**
return view_func # we just use the view_func

return wrapper

最佳答案

你的意思是这样的吗:

class Request:
def __init__ (self, method):
self.method = method

def another_decorator (f):
print ("another")
return f

def decorator_for_post (f):
def g (request, *args, **kwargs):
if request.method == "POST":
return another_decorator (f) (request, *args, **kwargs)
return f (request, *args, **kwargs)
return g

@decorator_for_post
def x (request):
print ("doing x")

print ("GET")
x (Request ("GET") )
print ("POST")
x (Request ("POST") )

关于python - 仅在 python 中对 POST 请求使用装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18397003/

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