[英]How do i pass a variable in a function to a decorator
I have a function that defines a variable inside of it called animal. 我有一个函数,在其中定义了一个称为动物的变量。 I also have a decorator for that function, but it needs the variable that's defined in the original function. 我也为该函数提供了一个装饰器,但是它需要在原始函数中定义的变量。
Either I need the animal variable from the original function, or I need to somehow pass the model_data variable from the decorator into the original function. 我需要原始函数中的动物变量,或者我需要以某种方式将装饰器中的model_data变量传递到原始函数中。 Any input? 有输入吗?
Here is the code: 这是代码:
@csrf_exempt
@require_http_methods(["GET", "PUT", "DELETE"])
@parse_model_data
def base_animal(request, model_id):
try:
animal = Animal.objects.get(pk=model_id)
except ObjectDoesNotExist:
return json_error(error="No animal found for id: %s" % model_id)
if request.method == "GET":
return json_success(model=animal)
if request.method == "DELETE":
animal.delete()
return json_success("Animal deleted.")
if request.method == "PUT":
animal.save()
return json_success()
Here is the decorator function: 这是装饰器函数:
def parse_model_data(originalFunction):
def parse(*args, **kwargs):
request = args[0]
model_data = request.get_json_body()
if not model_data:
return json_error("no json body detected")
model_data = Animal.parse_model_data(model_data)
for attr, value in model_data.items():
setattr(animal, attr, value)
return originalFunction(*args, **kwargs)
return parse
A decorator is not meant for this. 装饰器并非为此目的。 It cannot access an object created inside the function because that object does not exist yet when the decorated function, parse
, is called. 它无法访问在函数内部创建的对象,因为调用修饰函数parse
时该对象尚不存在。
It seems what you need here is a plain simple function. 似乎您在这里需要的是一个简单的函数。
def parse(animal, request):
model_data = request.get_json_body()
if not model_data:
return json_error("no json body detected")
model_data = Animal.parse_model_data(model_data)
for attr, value in model_data.items():
setattr(animal, attr, value)
@csrf_exempt
@require_http_methods(["GET", "PUT", "DELETE"])
def base_animal(request, model_id):
try:
animal = Animal.objects.get(pk=model_id)
except ObjectDoesNotExist:
return json_error(error="No animal found for id: %s" % model_id)
# Here we use our parse function
# It cannot be called before that point since animal did not exist
parse(animal, request)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.