celery是什么
分布式异步任务框架:第三方框架,celery翻译过来是芹菜,吉祥物就是芹菜 项目中使用异步任务的场景,可以使用它 之前做异步,如何做? 异步发送短信---》开启多线程---》不便于管理
celery作用
执行异步任务 执行延迟任务 执行定时任务
celery原理
1)可以不依赖任何服务器,通过自身命令,启动服务 2)celery服务为为其他项目服务提供异步解决任务需求的 注:会有两个服务同时运行,一个是项目服务,一个是celery服务,项目服务将需要异步处理的任务交给celery服务,celery就会在需要时异步完成项目的需求 人是一个独立运行的服务 | 医院也是一个独立运行的服务 正常情况下,人可以完成所有健康情况的动作,不需要医院的参与;但当人生病时,就会被医院接收,解决人生病问题 人生病的处理方案交给医院来解决,所有人不生病时,医院独立运行,人生病时,医院就来解决人生病的需求 django如果不用异步,正常运行即可,如果想做异步,就借助于 celery来完成
celery架构
broker:消息中间件,任务中间件(消息队列:redis,rabbitmq) django要做异步,提交任务到 任务中间件中(redis),存储起来 Celery本身不提供消息服务,但是可以方便的和第三方提供的消息中间件集成。包括,RabbitMQ, Redis等等 worker:任务执行者,任务执行单元 不停的从任务中间件中取任务,执行 Worker是Celery提供的任务执行的单元,worker并发的运行在分布式的系统节点中 banckend:结果存储,任务结果存储 把任务执行结果(函数返回值),存放到结果存储中(redis) 用来存储Worker执行的任务的结果,Celery支持以不同方式存储任务的结果,包括AMQP, redis等
任务中间件:redis
结果存储:redis
celery的快速使用(开源的,小组织,不支持win)
win上:需要借助于第三方
安装
pip install celery # 最新 5.3.4
创建main.py文件
import time from celery import Celery # 1 实例化得到对象 broker = 'redis://127.0.0.1:6379/1' # 消息中间件 redis backend = 'redis://127.0.0.1:6379/2' # 结果存,用redis app = Celery('app', broker=broker, backend=backend) # 编写任务,必须用app.task 装饰,才变成了celery的任务 @app.task def send_sms(): time.sleep(1) print('短信发送成功') return '手机号短信发送成功' #### 3 提交任务,使用别的进程 from main import send_sms res=send_sms.delay() print(res) ### 4 启动worker---》可以在3之前 # windows: pip3 install eventlet celery -A main worker -l info -P eventlet # mac linux # celery -A main worker -l info
查看结果(创建results.py文件)
from celery.result import AsyncResult from main import app id = '92987636-ae9e-4be9-828b-8c2d10fe066a' if __name__ == '__main__': a = AsyncResult(id=id, app=app) if a.successful(): result = a.get() print(result) elif a.failed(): print('任务失败') elif a.status == 'PENDING': print('任务等待中被执行') elif a.status == 'RETRY': print('任务异常后正在重试') elif a.status == 'STARTED': print('任务已经开始被执行')
celery包结构
project ├── celery_task # celery包 │ ├── __init__.py # 包文件 │ ├── celery.py # celery连接和配置相关文件,且名字必须叫celery.py │ └── tasks.py # 所有任务函数 ├── add_task.py # 添加任务 └── get_result.py # 获取结果
celery.py
from celery import Celery broker = 'redis://127.0.0.1:6379/1' # 消息中间件 redis backend = 'redis://127.0.0.1:6379/2' # 结果存,用redis app = Celery('app', broker=broker, backend=backend,include=['celery_task.home_task','celery_task.user_task'])
tasks.py
写相关的任务
add_task.py
### 5 提交任务 from celery_task.home_task import add res=add.delay(3,4) print(res)
启动worker
celery -A celery_task worker -l info -P eventlet
get_result.py(固定语法,可以封装成函数)
from celery_task.celery import app from celery.result import AsyncResult id = 'e31441d9-e9a6-4d70-9a66-a9227a6bc273' if __name__ == '__main__': a = AsyncResult(id=id, app=app) if a.successful(): result = a.get() print(result) elif a.failed(): print('任务失败') elif a.status == 'PENDING': print('任务等待中被执行') elif a.status == 'RETRY': print('任务异常后正在重试') elif a.status == 'STARTED': print('任务已经开始被执行')
celery延迟任务和定时任务
异步任务(delay提交)
from celery_task.home_task import add res=add.delay(3,4) print(res)
延迟任务
提交延迟任务
apply_async
添加延迟任务
from datetime import datetime, timedelta print(datetime.utcnow()) # utc 时间,跟咱们差8个小时 # eta 就是 10s 后的实际 eta = datetime.utcnow() + timedelta(seconds=30) res = send_sms.apply_async(args=(18953675221,), eta=eta) print(res)
定时任务
celery.py
#### 1 在celery.py中 # 时区 app.conf.timezone = 'Asia/Shanghai' # 是否使用UTC app.conf.enable_utc = False # 任务的定时配置 from datetime import timedelta from celery.schedules import crontab app.conf.beat_schedule = { 'add': { 'task': 'celery_task.home_task.add', 'schedule': timedelta(seconds=3), # 'schedule': crontab(hour=8, day_of_week=1), # 每周一早八点 'args': (5, 6), }, 'send_sms': { 'task': 'celery_task.user_task.send_sms', # 'schedule': crontab(hour=8, day_of_week=1), # 每周一早八点 'schedule': crontab(hour=9, minute=39), # 每天9点39,执行 'args': (18923748221,), }, }
启动worker
celery -A celery_task worker -l info -P eventlet
启动beat
celery -A celery_task beat -l info
django中使用celery
通用方案
第一步:把之前写的包结构,放在项目路径下 第二步:提交异步或延迟任务,导入直接提交即可 from celery_task.user_task import cache_demo res=cache_demo.delay('phone','18762696893') 第三步:只要启动worker,这些任务就会被启动 第四步:如果使用Django中的东西,需要在celery中写 import os os.environ.setdefault('DJANGO_SETTINGS_MODULE',luffy_api.settings.dev') 第五步:使用Django内置东西的任务 @app.task def cache_demo(key, value): cache.set(key, value) return '缓存成功
接口缓存
首次获取轮播图接口,去数据库查的,每次来到首页都要查一次,数据量大就很慢,所以砸门轮播图数据放到redis中缓存,以后只要缓存中有就冲缓存中拿 如果没有,就从数据库中拿,拿完之后在放到缓存中 查询所有接口,我们都可以加缓存,提高并发量
轮播图加缓存
class BannerView(GenericViewSet, ListModelMixin): # 自动生成路由 queryset = Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT] serializer_class = BannerSerializer # 接口加缓存,重写list def list(self, request, *args, **kwargs): # 先去缓存中查,如果有,直接返回 banner_list = cache.get('banner_list') if not banner_list: # 如果没有,在查数据库,放到缓存,再返回 logger.info('走了数据库') res = super().list(request, *args, **kwargs) cache.set('banner_list', res.data) return APIResponse(result=res.data) logger.info('走了缓存') return APIResponse(result=banner_list)
缓存升级
序列化类
from django.core.cache import cache from utils.common_logger import logger class CacheListModelMixin(ListModelMixin): # 接口加缓存,重写list def list(self, request, *args, **kwargs): # 先去缓存中查,如果有,直接返回 data_list = cache.get(self.cache_key) if not data_list: # 如果没有,在查数据库,放到缓存,再返回 logger.info('走了数据库') res = super().list(request, *args, **kwargs) cache.set(self.cache_key, res.data) return APIResponse(result=res.data) logger.info('走了缓存') return APIResponse(result=data_list)
视图类
class BannerView(GenericViewSet, CacheListModelMixin): # 自动生成路由 queryset = Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT] serializer_class = BannerSerializer cache_key = 'banner_list
双写一致性
接口加缓存,MySQL数据改掉,缓存数据不会变,导致数据不一致
有的数据必须一致(缓存删除和修改,要在修改数据之后) 修改,插入数据(mysql),删除缓存 修改,插入数据(mysql),修改缓存 有的数据,可以容忍,实时性没有那么高,可以定时更新
以上高级名:双写性一致
当修改数据库中的数据,同时也要修改缓存中的数据,如何保证一致,这就是数据的双写性一致
解决方案
改数据,删除缓存,修改缓存 定时更新
Django缓存过期时间
cache.set(self.cache_key, res.data, None) # 永不过期 cache.set(self.cache_key, res.data) # 不写5分钟过期
通过定时耿欣缓存,实现双写一致性
home_task.py
@app.task def update_banner(): # 1 查出所有轮播图 banner_list = Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT] ser = BannerSerializer(instance=banner_list, many=True) for item in ser.data: item['image']=settings.BACKEND_URL+item['image'] # 2 把轮播图放到cache中 cache.set('banner_list', ser.data) return '更新成功
celery.py
app.conf.beat_schedule = { 'update_banner': { 'task': 'celery_task.home_task.update_banner', 'schedule': timedelta(minutes=2), 'args': (), }, }
启动worker
celery -A celery_task worker -l info -P eventlet
启动beat(定时任务必须启动)
celery -A celery_task beat -l info
异步秒杀逻辑
分析流程
同步流程:用户在前端,点击秒杀按钮----》提交请求到后端----》[扣减库存,生成订单]假设耗时---》同步操作--》10s钟处理完成,秒杀成功---》返回给前端---》如果秒杀人数过多,同步操作,不能承载更多人同时秒杀 异步流程:用户在前端,点击秒杀按钮----》提交请求到后端----》提交一个任务[扣减库存,生成订单]假设耗时---》异步操作--》10s钟处理完成,秒杀成功---》前端再发请求查询---》如果秒杀人数过多,异步操作,10s内能承载非常多用户操作
前端
路由
const routes = [ { path: '/', name: 'home', component: HomeView }, { path: '/seckill', name: 'seckill', component: SeckillView }, ]
SeckillView.vue
<template> <div class="home"> <Header></Header> <div style="padding: 50px;margin-left: 100px"> <h1>Go语言课程</h1> <img src="http://photo.liuqingzheng.top/2023%2002%2022%2021%2057%2011%20/image-20230222215707795.png" height="300px" width="300px"> <br> <el-button type="danger" @click="handleSeckill">秒杀课程</el-button> </div> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <Footer></Footer> </div> </template> <script> import Header from "@/components/Header.vue"; import Footer from "@/components/Footer.vue"; export default { name: "SeckillView", data() { return { seckill_id: '', t: '' } }, methods: { handleSeckill() { this.$axios.post(this.$settings.BASE_URL + 'home/seckill/seckill/', { course_id: 'go语言' }).then(res => { console.log(res.data) if (res.data.code == 100) { this.$message({ message: res.data.msg, type: 'warning', duration: 1500 }); // 起一个定时任务,每隔2s向后端查询一次,看是否秒杀成功 this.seckill_id = res.data.seckill_id this.t = setInterval(() => { this.$axios.get(this.$settings.BASE_URL + 'home/seckill/get_seckill_result/?seckill_id='+this.seckill_id).then(res => { if (res.data.code == 100 || res.data.code == 101) { alert(res.data.msg) clearInterval(this.t) this.t = null } else if (res.data.code == 102) { //秒杀逻辑还没开始执行 this.$message('等待开始秒杀'); } else if (res.data.code == 103) { this.$message('正在秒杀途中'); } }) }, 2000) } else { this.$message({ message: '服务端异常,请联系系统管理员', type: 'warning', duration: 1500 }); } }) } }, components: { Header, Footer } } </script> <style scoped> </style>
后端
views.py
from celery_task.home_task import seckill_course from rest_framework.decorators import action from celery_task.celery import app from celery.result import AsyncResult class SeckillView(GenericViewSet): @action(methods=['POST'], detail=False) def seckill(self, request, *args, **kwargs): # 1 取出课程id resquest.data.get('course_id'),取出当前用户 request.user.pk course_id = request.data.get('course_id') # 2 扣减库存---》数据库 --》课程id的课程 数量减一 # 3 订单表,生成一条记录 res = seckill_course.delay(course_id) # 4 返回给前端,秒杀成功 return APIResponse(seckill_id=str(res), msg='秒杀任务已经提交') @action(methods=['GET'], detail=False) def get_seckill_result(self, request, *args, **kwargs): seckill_id = request.query_params.get('seckill_id') a = AsyncResult(id=seckill_id, app=app) if a.successful(): result = a.get() if result: return APIResponse(msg='恭喜您,秒杀成功') else: return APIResponse(code=101, msg='很遗憾,您没有秒到') elif a.status == 'PENDING': print('任务等待中被执行') return APIResponse(code=102, msg='暂未轮到您') elif a.status == 'STARTED': print('任务已经开始被执行') return APIResponse(code=103, msg='正在秒杀,请稍后') else: return APIResponse(code=104, msg='服务端错误,秒杀失败')
路由
router.register('seckill', SeckillView, 'banner')
任务
@app.task def seckill_course(course_id): # 2 扣减库存---》数据库 --》课程id的课程 数量减一 # 3 订单表,生成一条记录 # 逻辑是:开启事务---》扣减库存---》生成订单 import time import random time.sleep(6) res = random.choice([100, 102]) if res == 100: print('%s被秒杀成功了' % course_id) return True else: print('%s被秒杀失败了' % course_id) return False
课程列表页前端
组件
LightCourse.vue FreeCourse.vue ActualCourse.vue
配置路由
import FreeCourse from "@/views/FreeCourse"; import ActualCourse from "@/views/ActualCourse"; import LightCourse from "@/views/LightCourse"; { path: '/free-course', name: 'free-course', component: FreeCourse }, { path: '/actual-course', name: 'actual-course', component: ActualCourse }, { path: '/light-course', name: 'light-course', component: LightCourse },
ActualCourse
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li class="this">全部</li> <li>Python</li> <li>Linux运维</li> <li>Python进阶</li> <li>开发工具</li> <li>Go语言</li> <li>机器学习</li> <li>技术生涯</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选:</li> <li class="default this">默认</li> <li class="hot">人气</li> <li class="price">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item"> <div class="course-image"> <img src="@/assets/img/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="@/assets/img/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="@/assets/img/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="@/assets/img/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="@/assets/img/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="@/assets/img/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="@/assets/img/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="@/assets/img/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <!--<Footer></Footer>--> </div> </template> <script> import Header from "@/components/Header" // import Footer from "@/components/Footer" export default { name: "Course", data() { return { category: 0, } }, components: { Header, // Footer, } } </script> <style scoped> .course { background: #f6f6f6; } .course .main { width: 1100px; margin: 35px auto 0; } .course .condition { margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list { border-bottom: 1px solid #333; border-bottom-color: rgba(51, 51, 51, .05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after { content: ""; display: block; clear: both; } .course .cate-list li { float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title { color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this { color: #ffc210; border: 1px solid #ffc210 !important; border-radius: 30px; } .course .ordering::after { content: ""; display: block; clear: both; } .course .ordering ul { float: left; } .course .ordering ul::after { content: ""; display: block; clear: both; } .course .ordering .condition-result { float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li { float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title { font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding: 0; line-height: 28px; } .course .ordering .this { color: #ffc210; } .course .ordering .price { position: relative; } .course .ordering .price::before, .course .ordering .price::after { cursor: pointer; content: ""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .price::before { border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .price::after { border-top: 5px solid #aaa; bottom: 2px; } .course .course-item:hover { box-shadow: 4px 6px 16px rgba(0, 0, 0, .5); } .course .course-item { width: 1100px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0, 0, 0, .1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after { content: ""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image { float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img { width: 100%; } .course .course-item .course-info { float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span { font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img { width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info { font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51, 51, 51, .05); } .course-item .course-info .teather-info span { float: right; } .course-item .lesson-list::after { content: ""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/src/assets/img/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title { /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display: inline-block; max-width: 200px; } .course-item .lesson-list li:hover { background-image: url("/src/assets/img/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free { width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free { color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after { content: ""; display: block; clear: both; } .course-item .pay-box .discount-type { padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price { font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price { text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now { width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover { color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
课程相关表
表关系分析
课程分类表:跟课程一对多:一个课程分类,有多个课程 课程表(实战课课表): 多种课程:免费,实战,轻课---》使用同一个表?使用三个表 多种课程,字段可能有一样的,也有不一样的 我们的设计是:多个课程,多个表,以后再加别的课程,再加表即可 章节表:一个课程,有多个章节 课时表:一个章节,有多个课时 老师表:实战课,一门课,就是一个老师讲, 一对多,一个老师可以讲多门课
models.py
# 创建表 from django.db import models from utils.common_model import BaseModel # Create your models here. ## 课程分类 class CourseCategory(BaseModel): """分类""" name = models.CharField(max_length=64, unique=True, verbose_name="分类名称") class Meta: db_table = "luffy_course_category" verbose_name = "分类" verbose_name_plural = verbose_name def __str__(self): return "%s" % self.name ### 课程表 class Course(BaseModel): """课程""" course_type = ( (0, '付费'), (1, 'VIP专享'), (2, '学位课程') ) level_choices = ( (0, '初级'), (1, '中级'), (2, '高级'), ) status_choices = ( (0, '上线'), (1, '下线'), (2, '预上线'), ) name = models.CharField(max_length=128, verbose_name="课程名称") course_img = models.ImageField(upload_to="courses", max_length=255, verbose_name="封面图片", blank=True, null=True) course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付费类型") brief = models.TextField(max_length=2048, verbose_name="详情介绍", null=True, blank=True) level = models.SmallIntegerField(choices=level_choices, default=0, verbose_name="难度等级") pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True) period = models.IntegerField(verbose_name="建议学习周期(day)", default=7) attachment_path = models.FileField(upload_to="attachment", max_length=128, verbose_name="课件路径", blank=True,null=True) status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="课程状态") students = models.IntegerField(verbose_name="学习人数", default=0) sections = models.IntegerField(verbose_name="总课时数量", default=0) pub_sections = models.IntegerField(verbose_name="课时更新数量", default=0) price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价", default=0) # 删除某个课程分类,如果使用models.CASCADE,所有课程都删除,很危险 # 删除某个课程分类models.SET_NULL,跟它相关联的课程,置为空 # db_constraint=False 逻辑外键,不建立物理外键 没有外键约束 course_category = models.ForeignKey("CourseCategory", on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True,verbose_name="课程分类") teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授课老师") class Meta: db_table = "luffy_course" verbose_name = "课程" verbose_name_plural = "课程" def __str__(self): return "%s" % self.name ### 章节表 class CourseChapter(BaseModel): """章节""" course = models.ForeignKey("Course", related_name='coursechapters', on_delete=models.CASCADE, verbose_name="课程名称") chapter = models.SmallIntegerField(verbose_name="第几章", default=1) name = models.CharField(max_length=128, verbose_name="章节标题") summary = models.TextField(verbose_name="章节介绍", blank=True, null=True) pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True) class Meta: db_table = "luffy_course_chapter" verbose_name = "章节" verbose_name_plural = verbose_name def __str__(self): return "%s:(第%s章)%s" % (self.course, self.chapter, self.name) #课时表 class CourseSection(BaseModel): """课时""" section_type_choices = ( (0, '文档'), (1, '练习'), (2, '视频') ) chapter = models.ForeignKey("CourseChapter", related_name='coursesections', on_delete=models.CASCADE,verbose_name="课程章节") name = models.CharField(max_length=128, verbose_name="课时标题") orders = models.PositiveSmallIntegerField(verbose_name="课时排序") section_type = models.SmallIntegerField(default=2, choices=section_type_choices, verbose_name="课时种类") section_link = models.CharField(max_length=255, blank=True, null=True, verbose_name="课时链接",help_text="若是video,填vid,若是文档,填link") duration = models.CharField(verbose_name="视频时长", blank=True, null=True, max_length=32) # 仅在前端展示使用 pub_date = models.DateTimeField(verbose_name="发布时间", auto_now_add=True) free_trail = models.BooleanField(verbose_name="是否可试看", default=False) class Meta: db_table = "luffy_course_section" verbose_name = "课时" verbose_name_plural = verbose_name def __str__(self): return "%s-%s" % (self.chapter, self.name) #老师表 class Teacher(BaseModel): """导师""" role_choices = ( (0, '讲师'), (1, '导师'), (2, '班主任'), ) name = models.CharField(max_length=32, verbose_name="导师名") role = models.SmallIntegerField(choices=role_choices, default=0, verbose_name="导师身份") title = models.CharField(max_length=64, verbose_name="职位、职称") signature = models.CharField(max_length=255, verbose_name="导师签名", help_text="导师签名", blank=True, null=True) image = models.ImageField(upload_to="teacher", null=True, verbose_name="导师封面") brief = models.TextField(max_length=1024, verbose_name="导师描述") class Meta: db_table = "luffy_teacher" verbose_name = "导师" verbose_name_plural = verbose_name def __str__(self): return "%s" % self.name
补充(字段参数)
ForeignKey 的on_delete 参数
models.CASCADE # 级联删除,注意使用时机,用户和用户详情 课程和课程章节 models.SET_NULL # 删除分类,课程这个字段设置为空,要有null=True参数的配合 models.SET_DEFAULT # 删除分类,课程这个字段设置为默认值,要有 defalut=xx参数的配合 models.DO_NOTHING # 删除分类,课程这个字段什么都不做 models.SET(值,函数内存地址) # 删除分类,课程这个字段设置为写的值,或者执行内部传入的函数,函数返回值放在这
ForeignKey 的db_constraint=False
如果 db_constraint=False 只逻辑外键,不建立物理外键 没有外键约束,如果这样设置,修改,新增速度快,可能会出现脏数据(程序层面控制) 连表查询没有任何区别,其他操作完全一致
ForeignKey 的 related_name='coursechapters'
基于对象的跨表查: 正向: 对象.字段 course.course_category 根据课程拿到了课程分类对象, course_category在表内部,就是正向 反向: 对象.表名小写 对象.表名小写_set.all() 字段在表中没有,但是有关联关系 related_name: 为了替换原来基于对象的跨表查反向查询 表名小写 或 表名小写_set.all() 的 related_query_name 为了替换原来__连表查询,中表名小写,现在直接用related_query_name指定的字符串即可
课程表数据录入(media中的图片copy到自己文件中)
INSERT INTO luffy_teacher(id, orders, is_show, is_delete, created_time, updated_time, name, role, title, signature, image, brief) VALUES (1, 1, 1, 0, '2022-07-14 13:44:19.661327', '2022-07-14 13:46:54.246271', 'Alex', 1, '老男孩Python教学总监', '金角大王', 'teacher/alex_icon.png', '老男孩教育CTO & CO-FOUNDER 国内知名PYTHON语言推广者 51CTO学院2016\2017年度最受学员喜爱10大讲师之一 多款开源软件作者 曾任职公安部、飞信、中金公司、NOKIA中国研究院、华尔街英语、ADVENT、汽车之家等公司'); INSERT INTO luffy_teacher(id, orders, is_show, is_delete, created_time, updated_time, name, role, title, signature, image, brief) VALUES (2, 2, 1, 0, '2022-07-14 13:45:25.092902', '2022-07-14 13:45:25.092936', 'Mjj', 0, '前美团前端项目组架构师', NULL, 'teacher/mjj_icon.png', '是马JJ老师, 一个集美貌与才华于一身的男人,搞过几年IOS,又转了前端开发几年,曾就职于美团网任高级前端开发,后来因为不同意王兴(美团老板)的战略布局而出家做老师去了,有丰富的教学经验,开起车来也毫不含糊。一直专注在前端的前沿技术领域。同时,爱好抽烟、喝酒、烫头(锡纸烫)。 我的最爱是前端,因为前端妹子多。'); INSERT INTO luffy_teacher(id, orders, is_show, is_delete, created_time, updated_time, name, role, title, signature, image, brief) VALUES (3, 3, 1, 0, '2022-07-14 13:46:21.997846', '2022-07-14 13:46:21.997880', 'Lyy', 0, '老男孩Linux学科带头人', NULL, 'teacher/lyy_icon.png', 'Linux运维技术专家,老男孩Linux金牌讲师,讲课风趣幽默、深入浅出、声音洪亮到爆炸'); -- 分类表 INSERT INTO luffy_course_category(id, orders, is_show, is_delete, created_time, updated_time, name) VALUES (1, 1, 1, 0, '2022-07-14 13:40:58.690413', '2022-07-14 13:40:58.690477', 'Python'); INSERT INTO luffy_course_category(id, orders, is_show, is_delete, created_time, updated_time, name) VALUES (2, 2, 1, 0, '2022-07-14 13:41:08.249735', '2022-07-14 13:41:08.249817', 'Linux'); -- 课程表 INSERT INTO luffy_course(id, orders, is_show, is_delete, created_time, updated_time, name, course_img, course_type, brief, level, pub_date, period, attachment_path, status, students, sections, pub_sections, price, course_category_id, teacher_id) VALUES (1, 1, 1, 0, '2022-07-14 13:54:33.095201', '2022-07-14 13:54:33.095238', 'Python开发21天入门', 'courses/alex_python.png', 0, 'Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土', 0, '2022-07-14', 21, '', 0, 231, 120, 120, 0.00, 1, 1); INSERT INTO luffy_course(id, orders, is_show, is_delete, created_time, updated_time, name, course_img, course_type, brief, level, pub_date, period, attachment_path, status, students, sections, pub_sections, price, course_category_id, teacher_id) VALUES (2, 2, 1, 0, '2022-07-14 13:56:05.051103', '2022-07-14 13:56:05.051142', 'Python项目实战', 'courses/mjj_python.png', 0, '', 1, '2022-07-14', 30, '', 0, 340, 120, 120, 99.00, 1, 2); INSERT INTO luffy_course(id, orders, is_show, is_delete, created_time, updated_time, name, course_img, course_type, brief, level, pub_date, period, attachment_path, status, students, sections, pub_sections, price, course_category_id, teacher_id) VALUES (3, 3, 1, 0, '2022-07-14 13:57:21.190053', '2022-07-14 13:57:21.190095', 'Linux系统基础5周入门精讲', 'courses/lyy_linux.png', 0, '', 0, '2022-07-14', 25, '', 0, 219, 100, 100, 39.00, 2, 3); -- 章节表 INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (1, 1, 1, 0, '2022-07-14 13:58:34.867005', '2022-07-14 14:00:58.276541', 1, '计算机原理', '', '2022-07-14', 1); INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (2, 2, 1, 0, '2022-07-14 13:58:48.051543', '2022-07-14 14:01:22.024206', 2, '环境搭建', '', '2022-07-14', 1); INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (3, 3, 1, 0, '2022-07-14 13:59:09.878183', '2022-07-14 14:01:40.048608', 1, '项目创建', '', '2022-07-14', 2); INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (4, 4, 1, 0, '2022-07-14 13:59:37.448626', '2022-07-14 14:01:58.709652', 1, 'Linux环境创建', '', '2022-07-14', 3); -- 课时表 INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (1, 1, 0, '2022-07-14 14:02:33.779098', '2022-07-14 14:02:33.779135', '计算机原理上', 1, 2, NULL, NULL, '2022-07-14 14:02:33.779193', 1, 1); INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (2, 1, 0, '2022-07-14 14:02:56.657134', '2022-07-14 14:02:56.657173', '计算机原理下', 2, 2, NULL, NULL, '2022-07-14 14:02:56.657227', 1, 1); INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (3, 1, 0, '2022-07-14 14:03:20.493324', '2022-07-14 14:03:52.329394', '环境搭建上', 1, 2, NULL, NULL, '2022-07-14 14:03:20.493420', 0, 2); INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (4, 1, 0, '2022-07-14 14:03:36.472742', '2022-07-14 14:03:36.472779', '环境搭建下', 2, 2, NULL, NULL, '2022-07-14 14:03:36.472831', 0, 2); INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (5, 1, 0, '2022-07-14 14:04:19.338153', '2022-07-14 14:04:19.338192', 'web项目的创建', 1, 2, NULL, NULL, '2022-07-14 14:04:19.338252', 1, 3); INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (6, 1, 0, '2022-07-14 14:04:52.895855', '2022-07-14 14:04:52.895890', 'Linux的环境搭建', 1, 2, NULL, NULL, '2022-07-14 14:04:52.895942', 1, 4);
课程列表页接口
接口分析
1 课程分类接口 2 查询所有课程 可以按人气(学生人数)和价格排序 可以按课程分类过滤 带分页(基本分页)
课程分类接口(查询所有分类接口)
路由
router.register('category', CourseCategoryView, 'category')
视图类
class CourseCategoryView(GenericViewSet, CommonListModelMixin): queryset = CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders') serializer_class = CourseCategorySerializer
序列化类
class BannerSerializer(serializers.ModelSerializer): class Meta: model = Banner fields = ['id', 'image', 'link']
查询所有课程接口
路由
# http://127.0.0.1:8000/api/v1/courses/actual/--- get router.register('actual', CourseView, 'actual')
视图类
class CourseView(GenericViewSet, CommonListModelMixin): queryset = Course.objects.filter(is_delete=False, is_show=True).order_by('orders') serializer_class = CourseSerializer filter_backends = [OrderingFilter, DjangoFilterBackend] ordering_fields = ['students', 'price'] filterset_fields = ['course_category'] # 分页 pagination_class = CommonPageNumberPagination
序列化类
class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = ['id', 'name', 'role_name', 'title', 'signature', 'image', 'brief'] class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = [ 'id', 'name', 'course_img', 'brief', 'attachment_path', 'pub_sections', 'price', 'students', 'period', 'sections', 'course_type_name', 'level_name', 'status_name', 'teacher', 'section_list', ] # 定制,返回课程的老师,课程章节及章节下的课时(总共课时最多显示4条,不足4条,就全部显示) # 子序列化 表模型中写,在序列化类中 teacher = TeacherSerializer()
定制高级返回格式(model.py)
class Course(BaseModel): """课程""" course_type = ( (0, '付费'), (1, 'VIP专享'), (2, '学位课程') ) level_choices = ( (0, '初级'), (1, '中级'), (2, '高级'), ) status_choices = ( (0, '上线'), (1, '下线'), (2, '预上线'), ) name = models.CharField(max_length=128, verbose_name="课程名称") course_img = models.ImageField(upload_to="courses", max_length=255, verbose_name="封面图片", blank=True, null=True) course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付费类型") brief = models.TextField(max_length=2048, verbose_name="详情介绍", null=True, blank=True) level = models.SmallIntegerField(choices=level_choices, default=0, verbose_name="难度等级") pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True) period = models.IntegerField(verbose_name="建议学习周期(day)", default=7) attachment_path = models.FileField(upload_to="attachment", max_length=128, verbose_name="课件路径", blank=True, null=True) status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="课程状态") students = models.IntegerField(verbose_name="学习人数", default=0) sections = models.IntegerField(verbose_name="总课时数量", default=0) pub_sections = models.IntegerField(verbose_name="课时更新数量", default=0) price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价", default=0) # 删除某个课程分类,如果使用models.CASCADE,所有课程都删除,很危险 # 删除某个课程分类models.SET_NULL,跟它相关联的课程,置为空 '''on_delete 可以选择的参数 models.CASCADE # 级联删除,注意使用时机,用户和用户详情 课程和课程章节 models.SET_NULL # 删除分类,课程这个字段设置为空,要有null=True参数的配合 models.SET_DEFAULT # 删除分类,课程这个字段设置为默认值,要有 defalut=xx参数的配合 models.DO_NOTHING # 删除分类,课程这个字段什么都不做 models.SET(值,函数内存地址) # 删除分类,课程这个字段设置为写的值,或者执行内部传入的函数,函数返回值放在这 ''' # db_constraint=False 逻辑外键,不建立物理外键 没有外键约束,如果这样设置,修改,新增速度快,可能会出现脏数据(程序层面控制) # 连表查询没有任何区别,其他操作完全一致 course_category = models.ForeignKey("CourseCategory", on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True, verbose_name="课程分类") teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授课老师") class Meta: db_table = "luffy_course" verbose_name = "课程" verbose_name_plural = "课程" def __str__(self): return "%s" % self.name # choice字段,返回中文 def course_type_name(self): return self.get_course_type_display() def level_name(self): return self.get_level_display() def status_name(self): return self.get_status_display() def section_list(self): l = [] # 先取出课程下所有章节 course_chapter_list = self.coursechapters.all() for course_chapter in course_chapter_list: # 拿出这个章节下所有课时 course_section_list = course_chapter.coursesections.all() for course_section in course_section_list: l.append({'id': course_section.id, 'name': course_section.name, 'section_type': course_section.section_type, 'section_link': course_section.section_link, 'duration': course_section.duration, 'free_trail': course_section.free_trail, }) if len(l) >= 4: return l # 循环章节,取出每个章节下的课时,追加到l中,如果超过4条,就结束了 return l
分页(创建一个py文件(utils下))
class CommonPageNumberPagination(PageNumberPagination): page_size = 2 page_query_param = 'page' page_size_query_param = 'size' max_page_size = 5
标签:verbose,models,celery,course,14,id,name From: https://www.cnblogs.com/shanghaipudong/p/17772871.html