I have an api with django rest framework.
The api is for user signup. After signup api will send verification email to the user but sending email takes a little time so for this purpose i want to send email in background.
For this requirement what should be the approach ?
CodePudding user response:
This should be your approach to achieve the task which you want to execute.
- Install celery
- create a celery.py file in your project folder, where your settings.py file is located(recommended but not necessary) and paste the following code into your file. Replace example with your project name
from celery import Celery
import os
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')
app = Celery('example')
app.config_from_object(settings, namespace='CELERY')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
- Add these lines in your settings:
CELERY_BROKER_URL = 'redis://{}:{}'.format(REDIS_SERVER_HOST, REDIS_SERVER_PORT)
CELERY_RESULT_BACKEND = 'redis://{}:{}'.format(REDIS_SERVER_HOST, REDIS_SERVER_PORT)
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
Make sure to start the Redis server and assign values to REDIS_SERVER_HOST and REDIS_SERVER_PORT variables with appropriate values.
- Open init.py file of your project directory and paste this code
from .celery import app as celery_app
__all__ = ['celery_app']
- create a task.py file in your app directory and write a function that sends an email For ex:
from example import celery_app
from django.core.mail import send_mail
@celery_app.task
def send_celery_email(self, recipient_list):
# your actual mail function
send_mail("subject", "message", from_email = '[email protected]', recipient_list = [recipient_list])
- Start your celery server using
celery -A project worker --loglevel=info
- call this_function from the views as a normal function and pass the required arguments.
from .task import send_celery_email
send_celery_email.delay(recipient_list = [])
Note: This is just a roadmap of the workflow, actual code may vary according to your requirements and version of celery. Also checkout the documentation
CodePudding user response:
Primary use of celery is message queue. For your sending email, I recommend to use thread.