# order_task.pyfrom.celery import app
@app.task
defprocess_order(a,b):print(a)print(b)return'订单处理完了'
@app.task
defcancel_order():import random
res = random.choice([1,0])if res ==0:print('订单取消成功')returnTrueelse:print('订单取消失败')returnFalse# user_task.py from.celery import app
@app.task
defsend_sms(phone):import time
time.sleep(1)print('%s短信发送成功'%phone)return'%s短信发送成功'%phone
4. submit_tast.py
from celery_task import order_task,user_task
# 提交一个给用户发短信的任务
res = user_task.send_sms.delay('17635261921')print(res)# 提交一个取消订单的任务
res = order_task.cancel_order.delay()print(res)
5. result.py
from celery_task.celery import app
from celery.result import AsyncResult
# 发送短信任务: 3771b709-dcc0-43b2-868a-1249ee4beae1# 取消订单任务: 75d2c112-e7ab-4d9f-a75e-4bbc7cfb82f4id='75d2c112-e7ab-4d9f-a75e-4bbc7cfb82f4'if __name__ =='__main__':
res = AsyncResult(id=id, app=app)if res.successful():
result = res.get()print(result)elif res.failed():print('任务失败')elif res.status =='PENDING':print('任务等待中被执行')elif res.status =='RETRY':print('任务异常后正在重试')elif res.status =='STARTED':print('任务已经开始被执行')
from celery_task.celery import app
@app.task
defupdate_banner():from django.core.cache import cache
from django.conf import settings
from home import models
from home import serializer
banners = models.Banner.objects.filter(is_delete=False,is_show=True).order_by('-order')[:settings.BANNER_SIZE]
ser = serializer.BannerModelSerializer(instance=banners,many=True)
banner_data=ser.data
# 拿不到request对象,所以图片的连接base_url要自己组装for banner in banner_data:
banner['img']='http://127.0.0.1:8000%s'%banner['img']# 把数据存储在缓存中
cache.set('banner_data',banner_data)returnTrue
2. home/views.py
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import ViewSetMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from.import models
from.import serializer
from django.conf import settings
from django.core.cache import cache
from rest_framework.response import Response
# Create your views here.# GenericViewSet: 自动生成路由 (配置: queryset serializer_class)# ListModelMixin: listclassBannerView(GenericViewSet,ListModelMixin):
queryset = models.Banner.objects.filter(is_delete=False,is_show=True).order_by('-order')[:settings.BANNER_SIZE]
serializer_class = serializer.BannerModelSerializer
# 重写list 先从缓存中取 缓存有直接返回 没有再去数据取数据deflist(self, request,*args,**kwargs):# 如果缓存中有值,直接取出来返回,速度很快
banner_data = cache.get('banner_data')if banner_data:print('走了缓存')return Response(data=banner_data)# 如果缓存中没有,再走数据,查出来,放到缓存中
res =super().list(request,*args,**kwargs)# 把首页轮播图数据放到缓存中
cache.set('banner_data',res.data)print('没走缓存')return res