Last active
November 20, 2020 15:29
-
-
Save LegolasVzla/8cd37642c08749aa8cedbc1f23d208bf to your computer and use it in GitHub Desktop.
Django, Django Rest Framework, Postman validator of type of request in a Class Based View (API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
When you're developing an Endpoint with Django Rest Framework, in some situations you'll want to re-use it for generating example data, make tests (e.g. in DRF API View, Postman, Swagger IO...) and also to use it in your web app. For that reason, you'll receive differents types of request. On way to handle with this problem, is to create a decorator method to validate the type of request and then, in your CFA or CVB call the decorator. | |
_instance= MyNameViewSet() | |
_instance.endpoint_name(request,param1=1,param2=1) | |
''' | |
# Request validation is like that: | |
from functools import wraps | |
from rest_framework import exceptions | |
def validate_request(f): | |
@wraps(f) | |
def decorator(*args, **kwargs): | |
if(len(kwargs) > 0): | |
# HTML template | |
kwargs['data'] = kwargs | |
# DRF API View, Postman POST request made by body (JSON) | |
elif len(args[1].data) > 0: | |
kwargs['data'] = args[1].data | |
# Postman POST request made by params | |
elif len(args[1].query_params.dict()) > 0: | |
kwargs['data'] = args[1].query_params.dict() | |
return f(*args,**kwargs) | |
return decorator | |
# This return a dict. Then in your api.py: | |
class MyNameViewSet(viewsets.ModelViewSet): | |
'''Some atributes: queryset...''' | |
@validate_request | |
@action(methods=['post'], detail=False) | |
def endpoint_name(self, *args, **kwargs): | |
param1 = kwargs['data']['param1'] # You can access to your params like this | |
'''some logic''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment