Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 1. First install celery
- # pip install celery
- # --------------------------
- # Inside main project directory, create celery.py file
- # celery.py
- import os
- from celery import Celery
- from django.conf import settings
- # set the default Django settings module for the 'celery' program.
- os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ProjectName.settings')
- app = Celery('ProjectName')
- # Using a string here means the worker will not have to
- # pickle the object when using Windows.
- app.config_from_object('django.conf:settings')
- app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
- # --------------------------
- # in settings.py
- BROKER_URL = 'redis://127.0.0.1:6379'
- CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379'
- CELERY_ACCEPT_CONTENT = ['application/json']
- CELERY_TASK_SERIALIZER = 'json'
- CELERY_RESULT_SERIALIZER = 'json'
- CELERY_ENABLE_UTC = False
- CELERY_TIMEZONE = 'MST'
- # --------------------------
- # create python package called tasks and store all your long running tasks as module here
- # email_sender_tasks.py
- from celery import shared_task
- @shared_task
- def send_notification_email(data, email):
- # your logic here
- try:
- msg_html = render_to_string('templates/email_template.html',{})
- send_mail('Welcome!', msg_html, email,
- [data['email']], html_message=msg_html)
- except Exception as error:
- return error
- # ------------------
- # Now call the task from your view
- from email_sender_tasks import send_notification_email
- def register(request):
- # your logic here
- if register_status == True:
- send_notification_email.delay({"user_info": request.user}, email='insight@gmail.com')
- # -------------------
- # Start celery server in your local machine
- celery -A ProjectName worker -l info
- # *******************************************
- # in the EC2 instance, you need to configure the EC2 for celery and django
- # the supervisor configuration: celery_supervisor.conf
- [program:project_celery_conf]
- command = /var/www/start_celery.sh ; Command to start app
- user = www-data ; User to run as
- stdout_logfile = /var/www/logs/celery.log ; Where to write log messages
- redirect_stderr = true ; Save stderr in the same log
- environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding
- # start_celery.sh
- #!/usr/bin/env bash
- NAME="project_celery_conf" # name of the application
- PROJECT_DIR=/var/www/proj-name # project directory
- APP_DIR=/var/www/proj-name # can be project dir
- APP_MODULE=ProjectName # application module name
- echo "Starting $NAME as `whoami`"
- # Activate the virtual environment
- source $PROJECT_DIR/venvpp/bin/activate
- export PYTHONPATH=$APP_DIR:$PYTHONPATH
- cd $APP_DIR
- # Start Celery
- exec celery -A ${APP_MODULE} worker -l info
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement