Как произвести некоторые вычисления над данными моего POST-запроса в Django?

Я пытаюсь отправить POST запрос на мой Django backend т.е. djangorestframework, rest api, и я пытаюсь получить данные из этого запроса, произвести некоторые вычисления и отправить их обратно клиенту.

Вот мое мнение:

@api_view(['POST'])
def compute_linear_algebra_expression(request):
    """
    Given a Linear Algebra expression this view evaluates it.

    @param request: Http POST request
    @return: linear algbera expression
    """
    serializer = LinearAlgebraSerializer(data=request.data)
    
    if serializer.is_valid():
        serializer.save()
        data = serializer.data
        algebra_expr = data['expression']
        #algebra_expr = tuple(algebra_expr)
        print(algebra_expr)
        algebra_expr = evaluate(algebra_expr)
        return Response({"expression":algebra_expr}, status=status.HTTP_201_CREATED)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

вот мой оценщик: он потребляет кортеж python3:

def evaluate(exp):
    """
    Evaluate a Linea Algebra expression.
    """
    operand, op, operand2 = exp
    if isinstance(operand, Vec) and op == '+' and isinstance(operand2, Vec):
        return operand + operand2

    elif isinstance(operand, Vec) and op == '-' and isinstance(operand2, Vec):
        return operand - operand2

    elif isinstance(operand, Vec) and op == '*' and isinstance(operand2, Vec):
        return operand * operand2

    elif isinstance(operand, Vec) and op == '*' and isinstance(operand2, int):
        return operand * operand2

    elif isinstance(operand, Matrix) and op == '+' and isinstance(operand2, Matrix):
        return operand + operand2

    elif isinstance(operand, Matrix) and op == '-' and isinstance(operand2, Matrix):
        return operand - operand2

    elif isinstance(operand, Matrix) and op == '*' and isinstance(operand2, int):
        return operand * operand2

    elif isinstance(operand, Matrix) and op == '*' and isinstance(operand2, Matrix):
        return operand + operand2

    else:
        raise ValueError("{} is not type Vec or type Matrix.".format(operand))

Если я напишу свое представление таким образом, все будет работать, как ожидалось, за исключением вычислений, которые я хочу произвести.

@api_view(['POST'])
def compute_linear_algebra_expression(request):
    """
    Given a Linear Algebra expression this view evaluates it.

    @param request: Http POST request
    @return: linear algbera expression
    """
    serializer = LinearAlgebraSerializer(data=request.data)
    
    if serializer.is_valid():
        serializer.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Ошибка возникает в строке operand, op, operand2 = exp в функции evaluate. Вы предположили, что exp - это кортеж с 3 элементами, но мне кажется, что на самом деле это не так.

Сначала необходимо проверить длину кортежа с помощью команды print(len(exp).

Итак, после некоторого исследования я смог решить эту проблему.

Я добавил следующий код и смог увидеть, как выглядят данные:

def evaluate(exp):
    """
    Evaluate a Linea Algebra expression.
    """
    if isinstance(exp, tuple):
        if len(exp) == 3:
            operand, op, operand2 = exp
        else:
            raise ValueError("tuple {} is not of size 3.".format(exp))
    else:
        raise ValueError("{} in not a tuple.".format(exp))
                         
    if isinstance(operand, Vec) and op == '+' and isinstance(operand2, Vec):
        return operand + operand2
    ...

В моем представлении (см. выше) это выглядит так:


if serializer.is_valid():
        serializer.save()
        data = serializer.data
        algebra_expr = data['expression']
        algebra_expr = tuple(algebra_expr)

оказывается, tuple разбивал входные данные на символы, разделенные запятыми; отсюда и ошибка.

поэтому я решил эту проблему следующим образом:

if serializer.is_valid():
        serializer.save()
        data = serializer.data
        algebra_expr = data['expression']
        algebra_expr = eval(algebra_expr)
        algebra_expr = evaluate(algebra_expr)

обратите внимание на вызов eval. это решило проблему.

Вернуться на верх