Как интегрировать валидатор между классом python и restful api?
Предполагается, что у меня должен быть валидатор между моим калькулятором и rest-api, который использует set calculator. Мой калькулятор представляет собой класс python следующего вида:
class Calculator:
reduced_tax = 7
standard_tax = 19
@staticmethod
def calculate_reduced_tax(price):
price_float = float(price)
calculated_tax = price_float + ((price_float/100) * Calculator.reduced_tax)
return calculated_tax
@staticmethod
def calculate_standard_tax(price):
price_float = float(price)
calculated_tax = price_float + ((price_float/100) * Calculator.standard_tax)
return calculated_tax
Мой (надеюсь) restful api выглядит следующим образом:
from django.http import HttpResponse
from calculator.calculator import Calculator
from calculator.validator import validate_number
import json
def get_standard_tax(request, price):
if request.method == 'GET':
try:
validated_input = validate_number(price)
calculated_tax = Calculator.calculate_standard_tax(validated_input)
response = json.dumps([{'price': price, 'with_standard_tax': calculated_tax}])
except:
response = json.dumps({'Error': 'Could not calculate standard tax'})
return HttpResponse(response, content_type='text/json')
def get_reduced_tax(request, price):
if request.method == 'GET':
try:
validated_input = validate_number(price)
calculated_tax = Calculator.calculate_reduced_tax(validated_input)
response = json.dumps([{'price': price, 'with_reduced_tax': calculated_tax}])
except:
response = json.dumps({'Error': 'Could not calculate standard tax'})
return HttpResponse(response, content_type='text/json')
Я попытался реализовать валидатор следующим образом, пытаясь выбросить ValidationError из фреймворка django, поскольку мой проект в целом использует Django:
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_number(value):
if not float(value):
print('a validation error should be thrown')
raise ValidationError(
_('%(value)s is not an number'),
params={'value': value}
)
return value
Однако это не работает и, вероятно, не имеет особого смысла. Итак, как я могу реализовать валидатор, который находится между моим api и моим python-классом калькулятора?
Любая помощь будет высоко оценена. Спасибо!