Reputation: 117
I'm starting to develop in django/django rest framework and I needed to make a kind of calculator, send a and b, python would take these values, process, for example, do the sum and return in a json, but I only find examples with database data, would it be possible to do this?
Upvotes: 1
Views: 742
Reputation: 1
#importing the required libraries
from rest_framework import APIView
from rest_framework.response import Response
class calculateView(APIView):
if request.method == 'POST':
def calc(request,a,b):
result = a+b
return Response(result)
from django.urls import path
from . import views
pattern_urls = [
path('calculate/<int:a>/<int:b>/', views.calculateView.as_view(), name='calculate'),
]
Upvotes: -2
Reputation: 2893
You can pass the values of a and b using URL param into view, and could return the response after calculations.
Example:
# views.py
# imports
from rest_framework.decorators import api_view
from rest_framework.response import Response
# function-based view
@api_view(['POST'])
def calculate(request, a, b):
result = a + b
return Response({"message": f"{result}"})
urls.py would look like this;
# imports
from django.urls import path
from . import views as views # if urls.py and views.py are in same dir
urlpatterns = [
path('calculate/<int:a>/<int:b>/',
views.calculate, name="calculate"),
]
It's not mandatory to use function-based views. but that made it easier to achieve functionally what you wanted.
Upvotes: 2