0

I want to send verification email to new users. But because of slow connection it takes a long time to send an email and user will see a CONNECTION TIMED OUT error. I want to return the response to user and after that send the email. I already tried StreamingHttpResponse and using yield. But it returned a creepy response instead of the response I wanted.
I prefer to do it using function view but there is no problem if I HAVE to use class view. What should I do?

from django.shortcuts import render
from django.http import HttpRequest

def sign_up (request: HttpResponse):
    method = request.method
    if method == 'GET':
        # checking cookies
        return render(request, "template name", context)
    if method == 'POST':
        # validating data
        if unvalid_data:
            return render(request, "template name", context)
        # saving data
        return render(request, "template name", context)
        # sending email
mhn2
  • 119
  • 9
  • You can solve the issue by running the email sending in another thread and run it asynchronously. (either by subclassing `threading.Thread` or using Celery tasks) – S.Mohsen sh Sep 14 '20 at 07:18
  • @S.Mohsensh Can you post it as an answer with some examples? – mhn2 Sep 14 '20 at 08:24

1 Answers1

0

Thanks to NeuronQ in this question I got this Idea and it's working:

# myclass.py
from django.http import HttpResponse

__all__ = ['do_after_render']

class do_after_response (HttpResponse):
    def __init__(self, do_after, content=b'', do_after_args=[], *args, **kwargs):
        self.do_after = do_after
        self.do_after_args = do_after_args
        super().__init__(content=content, *args, **kwargs)
    def close(self):
        super().close()
        self.do_after(*self.do_after_args)

def do_after_render (do_after, request, template_name, context=None, do_after_args=[], content_type=None, status=None, using=None):
    content = render_to_string(template_name, context, request, using=using)
    return do_after_response(do_after=do_after, content=content, do_after_args=do_after_args, content_type=content_type, status=status)
# views.py
from .myclass import *

from django.shortcuts import render
from django.http import HttpRequest

def send_mail (some_args, some_other_args):
    # sending email

def sign_up (request: HttpResponse):
    method = request.method
    if method == 'GET':
        # checking cookies
        return render(request, "template name", context)
    if method == 'POST':
        # validating data
        if unvalid_data:
            return render(request, "template name", context)
        # saving data
        do_after_args = [some_args, some_other_args]
        return do_after_render(send_mail, request, "template name", context, do_after_args)
mhn2
  • 119
  • 9