Celery asynchronous task sends SMS verification code

1. Create celery_tasks package

2 in the project. Create config.py file in celery_tasks directory to save celery configuration information

broker_url = "redis://"

3. in celery_tasks Create the main.py file in the directory for use as the startup file for celery

from celery import Celery

# Use the django configuration file for celery to set the 
import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = ' project configuration path '

# Create celery applicationapp = Celery(' casually start a name ')

# import celery configurationapp.config_from_object('celery_tasks.config')

# auto registration celery taskapp.autodiscover_tasks(['celery_tasks.sms'])

4. Create sms package in celery_tasks directory, use The asynchronous task related code for placing SMS messages

5. Create the tasks.py file in the celery_tasks/sms/ directory (the file name must be tasks) to save the asynchronous task for sending SMS

from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.main import app
import logging

logger = logging.getLogger("django")

def send_sms_code(mobile, sms_code):
	sending text verify code
:param mobile: mobile number
:param sms_code: SMS verification code
:return: None
		ccp = CCP()
		result = ccp.send_template_sms(mobile, [sms_code, '5'], 1)
	except Exception as e:
		logger.error("Send SMS verification code [Exception][mobile: %s, message: %s ]" % (mobile, e))
		if result == 0:
			logger.info("Send SMS verification code [success][mobile: %s ]" % mobile)
			logger.warning( "Send verification code SMS [Fail] [mobile: %s ]" % mobile)

6.apps/users/views.py to rewrite the SMSCodeView view, use celery asynchronous task to send SMS

class SMSCodeView(APIView):

	def get(self, request, mobile):

		# Send SMSsend_sms_code .delay(mobile, sms_code)

		# Return to the result 
		return Response({"message": "ok"})

7. Enter the virtual environment, switch to the path of the celery_tasks folder, open the asynchronous

celery -A celery_tasks.main worker -l info

parameter explanation:

  • -A celery_tasks.main Specify the startup file
  • Worker Create task executor
  • -l info View detailed execution process