Today small for everyone to share an example of using celery python asynchronous task execution, a good reference value, we want to help. Come and see, to follow the small series together
using celery django projects implemented in asynchronous send text messages
Created under the directory to save the project celery_tasks celery asynchronous tasks.
In celery_tasks create config.py file directory, configuration information is stored celery
```broker_url = "redis://127.0.0.1/14"```
Main.py create files in the directory celery_tasks for as celery startup file
from celery import Celery
# 为celery使用django配置文件进行设置
import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
os.environ['DJANGO_SETTINGS_MODULE'] = 'model.settings.dev'
# 创建celery应用
app = Celery('model')
#导入celery配置
app.config_from_object('celery_tasks.config')
#自动注册celery任务
app.autodiscover_tasks(['celery_tasks.sms'])
Create a directory under celery_tasks sms directory, send text messages for placing asynchronous tasks related code.
Send SMS will provide cloud communication SDK put under celery_tasks / sms / directory.
Creating tasks.py in celery_tasks / sms / directory (the name is fixed, and very important, the system will automatically find the task queue from this file) file to save to send text messages asynchronous tasks
import logging
from celery_tasks.main import app
from .yuntongxun.sms import CCP
logger = logging.getLogger("django")
#验证码短信模板
SMS_CODE_TEMP_ID = 1
@app.task(name='send_sms_code')
def send_sms_code(mobile, code, expires):
发送短信验证码
:param mobile: 手机号
:param code: 验证码
:param expires: 有效期
:return: None
try:
ccp = CCP()
result = ccp.send_template_sms(mobile, [code, expires], SMS_CODE_TEMP_ID)
except Exception as e:
logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
else:
if result == 0:
logger.info("发送验证码短信[正常][ mobile: %s ]" % mobile)
else:
logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)
Rewriting SMSCodeView view verifications / views.py, the asynchronous task to send text messages using celery
from celery_tasks.sms import tasks as sms_tasks
class SMSCodeView(GenericAPIView):
...
# 发送短信验证码 这是将时间转化为分钟,constants.SMS_CODE_REDIS_EXPIRES 是常量
sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)
return Response({"message": "OK"})
This python use celery to achieve the above examples of asynchronous task execution is small series to share the entire contents of all of the
We recommend the python learning sites, click to enter , to see how old the program is to learn! From basic python script, reptiles, django, data mining, programming techniques, work experience, as well as senior careful study of small python partners to combat finishing zero-based information projects! The method has timed programmer Python explain everyday technology, to share some of the learning and the need to pay attention to small details