Search code examples
pythondjangoapidjango-rest-frameworkdjango-signals

How to add a Django custom signal to worked out request


I have a Django project and some foreign API's inside it. So, I have a script, that changes product stocks in my store via marketplace's API. And in my views.py I have a CreateAPIView class, that addresses to marketplace's API method, that allows to get product stocks, and writes it to MYSQL DB. Now I have to add a signal to start CreateAPIView class (to get and add changed stocks data) immediately after marketplace's change stocks method worked out. I know how to add a Django signal with pre_save and post_save, but I don't know how to add a singal on request.

I found some like this: from django.core.signals import request_finished from django.dispatch import receiver

@receiver(request_finished) def my_callback(sender, **kwargs): print("Request finished!")

But it is not that I'm looking for. I need a signal to start an CreateAPIView class after another api class finished its request. I will be very thankfull for any advise how to solve this problem.


Solution

  • You could create a Custom Signal, which can be called after the marketplace API is hit.

    custom_signal = Signal(providing_args=["some_data"])
    

    Send the signal when marketplace API is hit:

    def marketplace_api():
        data = 'some_data'
        custom_signal.send(sender=None, some_data=data)
    

    Then simply define a receiver function which will contain the logic you need:

    @receiver(custom_signal)
    def run_create_api_view(sender, **kwargs):
        data = kwargs["some_data"]
        if data is not None:
            view = CreateAPIView()
            view.dispatch(data)