Skip to content

Instantly share code, notes, and snippets.

@sirrobot01
Last active September 13, 2021 09:03
Show Gist options
  • Save sirrobot01/2c728fcfbc6f74d8396457f0f489390b to your computer and use it in GitHub Desktop.
Save sirrobot01/2c728fcfbc6f74d8396457f0f489390b to your computer and use it in GitHub Desktop.
Multi-action endpoint
from .multi_action_view import BaseAction
# Sample action
class CheckDateView(BaseAction):
def print_date(self, *args, **kwargs):
r = Response(data={'current_date': datetime.now()}, status=200)
return r
from rest_framework.response import Response
import inspect
from datetime import datetime
from rest_framework.views import APIView
class BaseAction:
def process_action(self, target_name, request, *args, **kwargs):
target = getattr(self, target_name)
if target and inspect.ismethod(target):
return self.run(target, request, *args, **kwargs)
else:
raise TypeError
def run(self, func, request, *args, **kwargs):
kwargs.update({'request': request})
return func(self, *args, **kwargs)
class BaseConnector(APIView):
action_id = None
action_cls = None
target = None
actions = {}
def process_action(self, request, *args, **kwargs):
action = self.action_cls()
return action.process_action(request=request, target_name=self.target, *args, **kwargs)
def get_action(self, action_id):
action_cls = self.actions.get(action_id)
return action_cls
def instantiate_request(self, request):
self.action_id = self.get_request.get('action_id')
if not self.action_id:
raise ValueError('action_id missing in request')
self.action_cls = self.get_action(self.action_id)
if not self.action_cls:
raise ModuleNotFoundError('Can not find action with id: %s' % self.action_id)
self.target = self.get_request.get('target')
if not self.target:
raise ValueError('target not found in request')
@property
def get_request(self):
if self.request.method.lower() == "get":
return self.request.GET
else:
return self.request.data or self.request.POST
def post(self, request, *args, **kwargs):
self.instantiate_request(request)
return self.process_action(request, *args, **kwargs)
from .views import CrudAPIView
urlpatterns = [
path('', CrudAPIView.as_view())
]
from .multi_action_view import BaseConnector
from .actions import CheckDateView
class CrudAPIView(BaseConnector):
actions = {
'date': CheckDateView
}
@sirrobot01
Copy link
Author

Multiple actions on one single endpoint.

Steps

  • Create a view inheriting BaseConnector as shown in views.py
  • Create actions inheriting BaseAction as shown in actions.py
  • Add actions to your view(check line 4-6 in views.py

Pass 'action_id' and 'target' and other parameters you want.

Note: This uses Django rest framework

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment