Hey guys I need help on this one. I’m stacking API endpoints on each other which uses the same data my models provide. Let’s say the root endpoint is:
HTTP://localhost:8000/api/v1/my_model
Then, the stacked Api’s are:
HTTP://localhost:8000/api/v1/my_model/some_path
HTTP://localhost:8000/api/v1/my_model/another_path
I’ve set up my viewset like this:
class MyViewSet(mixins.ListModelMixin, viewsets.GenericViewset):
queryset = MyModel.objects.select_related()
serializer_class = MyModelSerializer
@action(methods=['GET'], detail=False, url_path='some_path')
def get_something_done(self, request):
cache_data = Cache.get('something')
if cache_data:
return Response(cache_data, status=status.HTTP_200_OK)
queryset = self.filter_queryset(self.get_queryset())
df = queryset.to_dataframe() #It's to convert data in my django model to pandas dataframe
df = df.drop(['s_n','id'], axis=1)
result = get_something_done(df)
result = result.to_json(orient='records')
data = json.loads(result)
cache_data = Cache.set('something', data)
return Response(data, status=status.HTTP_200_OK)
@action(methods=['GET'], detail=False, url_path='another_path')
def get_another_thing_done(self, request):
cache_data = Cache.get('another_thing')
if cache_data:
return Response(cache_data, status=status.HTTP_200_OK)
queryset = self.filter_queryset(self.get_queryset())
df = queryset.to_dataframe()
df = df.drop(['s_n','id'], axis=1)
result = get_another_thing_done(df)
result = result.to_json(orient='records')
data = json.loads(result)
cache_data = Cache.set('another_thing', data)
return Response(data, status=status.HTTP_200_OK)
This is just a demo of what I’m doing so far. There are numerous such stacked APIs within my project. I haven’t tried to move them around due to time issues and the consequences of something going south.
Is it good practice to do so?
Both of my detailed functions are dependent on the base queryset of the viewset. If I moved the logic from here to a different API for every function, will I be able to achieve same functionality with faster speed?