Make push notification from celery function

Viewed 862

I'm trying to show a message using Django message, but this alert should be executed when a certain event happened on @shared_task. This is my celery function code in tasks.py

def show_message_in_time(self,response):
    while True:
        # get_info_to_show() this function will do something 
        messages.info(response, 'Your email is added successfully!')
        sleep(2*60)

and this is the function on views.py

def index(response):
    
    show_message_in_time.delay(response)
    return render(response, "Sales.html", {'zipped_list': objs})

Below is the error I received

Exception Value:    
Object of type 'WSGIRequest' is not JSON serializable

I have tried to convert WSGIRequest to JSON and also that's not working. Any help would be appreciated!

1 Answers

The simplest solution to your problem is to create a dictionary out of pieces of WSGIRequest/HttpRequest that you really need.

Let's say your WSGIRequest has "username" and "email" parts. Then you refactor your index to something like:

def index(response):
    data = { 
        "method": response.method,
        "username": response["username"],
        "email": response["email"]
    }

    if response.method == "POST":
        data["response_data"] = response.POST

    if response.method == "GET":
        data["response_data"] = response.GET

    show_message_in_time.delay(data)
    return render(response, "Sales.html", {'zipped_list': objs})

If you know it is a post method then the quickest test would be

def index(response):
    # POST is a dictionary, so it is definitely serializable
    show_message_in_time.delay(response.POST)
    return render(response, "Sales.html", {'zipped_list': objs})

Disclaimer: I never used Django or any other web framework, but I know little bit about Celery.

Related