3

python3.7.2+Django2.0.4 使用django-celery遇到的那些坑

 10 months ago
source link: https://v3u.cn/a_id_54
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

python3.7.2+Django2.0.4 使用django-celery遇到的那些坑

首页 - Python/2019-03-20

  1 首先为啥要用celery

  因为在Django Web平台开发中,碰到一些请求执行的任务时间较长(几分钟),为了加快用户的响应时间,因此决定采用异步任务的方式在后台执行这些任务。与此同时,celery除了异步任务,还可以开启定时任务,方便调度。
  2 安装需要的软件包
  
pip install celery

pip install celery-with-redis

pip install django-celery
  3 因为async这个单词在python3.7中已经作为系统关键字存在了,所以要把所有涉及到这个关键字的文件都要改掉,涉及的文件列表包含但不限于:
  
/kombu/async

/celery/utils/timer2.py

/concurrency/asynpool.py

/kombu/transport/redis.py

/celery/worker/auto_scale.py,components,consumer,strategy
  4 配置settings.py
  
INSTALLED_APPS = (
   ...
   'djcelery',
  }
# 末尾初始化
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_IMPORTS = ('应用名称.task')
  5 新增task.py
  
#导入异步任务
from celery.task import task
#导入定时任务库
from celery.decorators import periodic_task
  
#利用参数来设置任务周期
@periodic_task(run_every=10)
def some_task():
    print('每10秒执行一次')
    time.sleep(5)
    print('执行完毕')
    return True

#通过装饰器来注册异步任务
@task
def task_mail():
    #实例化一个对象
    sendmail = SendMail('欢迎注册','您的验证码是1324',   ['[email protected]'],DEFAULT_FROM_EMAIL)
    status = sendmail.do_send_mail()
    if status:
        print('发送邮件成功')
    else:
        print('发送邮件失败')
  6 新增celery.py
  
import os
import django
from celery import Celery
from django.conf import settings 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mymac.settings')
django.setup()
app = Celery('mymac')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))
  7 启动服务
  
#异步服务
celery -A mymac worker -l info  
#定时任务服务
celery -A myproject beat -l info
  8 但是执行异步任务的时候发现服务自动断掉,是因为python库里的redis版本太高了。。。所以通过pip卸载,然后指定安装低版本2.6.10
  
pip uninstall redis
pip install redis==2.6.10

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK