Henrique Buzin
Henrique Buzin

Reputation: 117

Django Rest Framework for Calculations

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

Answers (2)

Muhammad Abdullah
Muhammad Abdullah

Reputation: 1

Views.py

#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)

URL of the listing page

from django.urls import path

from . import views

pattern_urls = [
    path('calculate/<int:a>/<int:b>/', views.calculateView.as_view(), name='calculate'),   
]

Upvotes: -2

Faisal Nazik
Faisal Nazik

Reputation: 2893

Try Function-Based Views

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

Related Questions