23 lines
800 B
Python
23 lines
800 B
Python
from rest_framework import permissions
|
|
from rest_framework.exceptions import ValidationError
|
|
from rest_framework.response import Response
|
|
from rest_framework.throttling import ScopedRateThrottle
|
|
from rest_framework.views import APIView
|
|
|
|
from .engine import calculate
|
|
|
|
|
|
class CalculatorView(APIView):
|
|
permission_classes = [permissions.AllowAny]
|
|
throttle_classes = [ScopedRateThrottle]
|
|
throttle_scope = "calculator"
|
|
|
|
def post(self, request):
|
|
try:
|
|
payload = calculate(request.data)
|
|
except ValidationError:
|
|
raise
|
|
except (ArithmeticError, NotImplementedError, TypeError, ValueError) as exc:
|
|
raise ValidationError({"expression": "该计算暂时无法完成,请缩小表达式范围"}) from exc
|
|
return Response(payload)
|