celery的用法,以发送激活邮箱为例

2018-07-03  本文已影响0人  bboyAyao

示例一:

用户发起request,并等待response返回。在本些views中,可能需要执行一段耗时的程序,那么用户就会等待很长时间,造成不好的用户体验

示例二:

网站每小时需要同步一次天气预报信息,但是http是请求触发的,难道要一小时请求一次吗?

使用celery后,情况就不一样了

示例一的解决:将耗时的程序放到celery中执行,再开一个进程

示例二的解决:使用celery定时执行


首先在linux下安装:django版本为1.8.2

pip install 
celery==3.1.25
celery-with-redis==3.0
django-celery==3.1.17

配置settings:

INSTALLED_APPS = (
  ...
  'djcelery',
}
...
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1(本机地址):6379/0'
CELERY_IMPORTS = ('应用名称.(文件名,如)task')

在应用目录下创建task.py文件

import time
from celery import task

@task
def sayhello():
    print('hello ...')
    time.sleep(2)
    print('world ...')

迁移,生成celery需要的数据表:

python manage.py migrate

启动Redis:

sudo redis-server /etc/redis/redis.conf

启动worker:

python manage.py celery worker --loglevel=info

调用语法:

函数名.delay(参数)


views.py中:
from user import tasks
from django.http import HttpResponse,HttpResponseRedirec

def register_handle(request):
    user_name = request.POST.get('user_name')
    user_pwd = request.POST.get('user_pwd')
    user_email = request.POST.get('user_email')
    # if UserInfo.objects.filter(userName=user_name).exists():
    #     return HttpResponseRedirect("register_ui")
    #实例化用户信息到数据库
    userinfo = UserInfo.objects.create_user(user_name,user_email,user_pwd)
    userinfo.is_active = 0
    userinfo.save()
    tasks.task_register_send_email.delay(userinfo.id, user_name, user_email)

    return HttpResponseRedirect('login')

tasks.py中(自己在user文件下创建:)

import time
from celery import task
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from EverydayFresh import settings
from django.core.mail import send_mail


@task
def task_register_send_email(uid, username, email):
    time.sleep(30)
    serializer = Serializer(settings.SECRET_KEY, 3600)
    info = {'confirm': uid}
    token = serializer.dumps(info).decode()

    # 发邮件
    subject = '主题信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [email]
    html_message = '<h1>%s,信息语句</h1>请点击下面的链接激活您的帐号<br/><a href="http://192.168.12.77:8888/user/active/%s">http://192.168.12.77:8888/user/active/%s</a>' % (
        username, token, token)

    send_mail(subject, message, sender, receiver, html_message=html_message)
    print('发送成功。。。')

settings中的celery配置,同时还要配置email

import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_IMPORTS = [
    'user.tasks'
]
上一篇下一篇

猜你喜欢

热点阅读