简体   繁体   中英

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. 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.

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)

    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM