1
votes

I want to send an email after saving the data into a database,but I don't want to wait after completed send email return the HTTP response ,I want to return the HTTP response direct ,then send the email by Django self.

def received(request):
    login=get_login(request)
    received=True
    cluster_list=models.Cluster.objects.all()
    Asset_Type=models.CategoryOfAsset.objects.all()
    if request.method=="GET":
        return render(request,"received.html",locals())
    if request.is_ajax():
        try:
            req=json.loads(request.body)
            meta_data_dict=req['meta_data']
            item_data_dict=req['all_item_data']['item_data']
            received_or_shipment=True
            insert_meta_item_to_DB(meta_data_dict,item_data_dict,received_or_shipment)
            sendTemplateEmail(meta_data_dict,item_data_dict)
            return HttpResponse(json.dumps('sucessful'))
        except Exception, e:
            logger.error(e)

Now the code will cause this error:

ValueError: The view tool.views.received didn't return an HttpResponse object

It returned None instead.

2

2 Answers

2
votes

Use a local SMTP server.

Will result in the mail being queued (even if it's not delivered) almost instantly, so you are able to send your http response without being held up by the delays in sending the email.

Use a Task Queue

In it's simplest form, you can just chuck in the email message into a table and have cron job periodically inspect that table and send whatever messages that need to be sent.

A slightly more sophisticated method is to use Redis and have a django CLI listen in on it.

An even more sophisticated(?) solution is to use a Celery Task.

1
votes

Simplest solution is to run is asynchronously:

import threading

def run_async(func, args):
    threading.Thread(target=func, args=args).start()

and then:

run_async([function], ([args]))