win10+celery4.x以上+redis的天坑
1.用redis作为中间的话,有密码必须加上
app = Celery('celery_tasks.tasks', broker='redis://:123456@127.0.0.1:6379/5')
2.win配celery4.X以上必须pip一个eventlet包
3.启动异步任务的时候需要
celery -A celery_tasks.tasks worker -l info -P eventlet
4.在Django中的celery_tasks下的tasks必须加入初始化
import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dailyfresh1.settings") django.setup() 不然会出现迭代次数超限制的bug
5.电脑的TCP/IP出问题的情况下最好是使用手机热点,不然STMP服务器方会认为你的名字过于简单,不让过
6.django的版本最好是1.11.1 ,不然报错不断
tasks.py代码如下
# 使用celery
from django.core.mail import send_mail
from django.conf import settings
from celery import Celery
import time
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dailyfresh1.settings")
django.setup()
# 创建一个Celery类的实例对象
app = Celery('celery_tasks.tasks', broker='redis://:123456@127.0.0.1:6379/5')
# 启动的代码celery -A celery_tasks.tasks worker -l info -P eventlet
# 定义任务函数
@app.task
def send_register_active_email(to_email, username, token):
'''发送激活邮件'''
# 组织邮件信息
subject = '天天生鲜欢迎信息'
message = ''
sender = settings.EMAIL_FROM
receiver = [to_email]
html_message = '<h1>%s, 欢迎您成为天天生鲜注册会员</h1>请点击下面链接激活您的账户<br/><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>' % (username, token, token)
send_mail(subject, message, sender, receiver, html_message=html_message)
time.sleep(5)
user.views中的类模型如下:
class RegisterView(View):
'''注册'''
def get(self, request):
'''显示注册页面'''
return render(request, 'register.html')
def post(self, request):
'''进行注册处理'''
# 接收数据
username = request.POST.get('user_name')
password = request.POST.get('pwd')
email = request.POST.get('email')
allow = request.POST.get('allow')
# 进行数据校验
if not all([username, password, email]):
# 数据不完整
return render(request, 'register.html', {'errmsg': '数据不完整'})
# 校验邮箱
if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
return render(request, 'register.html', {'errmsg': '邮箱格式不正确'})
if allow != 'on':
return render(request, 'register.html', {'errmsg': '请同意协议'})
# 校验用户名是否重复
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# 用户名不存在
user = None
if user:
# 用户名已存在
return render(request, 'register.html', {'errmsg': '用户名已存在'})
# 进行业务处理: 进行用户注册
user = User.objects.create_user(username, email, password)
user.is_active = 0
user.save()
# 发送激活邮件,包含激活链接: http://127.0.0.1:8000/user/active/3
# 激活链接中需要包含用户的身份信息, 并且要把身份信息进行加密
# 加密用户的身份信息,生成激活token
serializer = Serializer(settings.SECRET_KEY, 3600)
info = {'confirm':user.id}
token = serializer.dumps(info) # bytes
token = token.decode()
# 发邮件
send_register_active_email.delay(email, username, token)
# 返回应答, 跳转到首页
return redirect(reverse('goods:index'))
smartcat.994