目录
一、双写一致性之定时更新
任务逻辑
@app.task
def update_banner():
# 查询数据库,拿到所有轮播图,序列化后,放到缓存中
banner_list = Banner.objects.all().filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT]
ser = BannerSerializer(instance=banner_list, many=True)
# 如果在视图类,做序列化,因为视图类有request对象,
# 所以向图像这种,会自动加前面的地址
for item in ser.data:
# print(ser.data)
print(1111)
item['image'] = settings.BACKEND_URL + item['image']
cache.set('home_banner_list', ser.data)
return True
二、异步发送短信
视图函数
@action(methods=['GET'], detail=False)
def send_sms(self, request, *args, **kwargs):
mobile = request.query_params.get('mobile', None)
code = get_code() # 把code存起来,放到缓存中,目前在内存,后期换别的
cache.set('send_sms_code_%s' % mobile, code)
if mobile:
# 开启一个线程,执行发送短信
# t = Thread(target=send_sms_by_mobile, args=[mobile, code])
# t.start()
# 提交异步任务---》异步发送
res = send_sms.delay(mobile,code)
print(res)
return APIResponse(msg='短信已发送')
raise APIException('手机号没有携带')
任务
from libs.send_tx_sms import send_sms_by_mobile
@app.task
def send_sms(mobile, code):
res=send_sms_by_mobile(mobile,code)
if res:
return '%s的短信发送成功,验证码是%s'%(mobile,code)
else:
return '%s的短信发送失败'%mobile
三、异步秒杀逻辑前后端
1.1 前端 Sckill.vue
<template>
<div>
<h2>go语言从入门到放弃</h2>
<el-button type="danger" @click="handleSckill">秒杀</el-button>
</div>
</template>
<script>
export default {
name: "Sckill",
data() {
return {
t: null,
task_id: '',
}
},
methods: {
handleSckill() {
this.$axios.post(`${this.$settings.BASE_URL}user/sckill/`, {
name: "性感帽子",
}).then(res => {
if (res.data.code == 100) {
alert('您正在排队')
this.task_id = res.data.task_id
// 起个转圈的东西
// 起定时任务
this.t = setInterval(() => {
this.$axios.get(`${this.$settings.BASE_URL}user/sckill/?task_id=${this.task_id}`).then(res => {
if (res.data.code == 100 || res.data.code == 101) {
this.$message(res.data.msg)
//销毁定时器
clearInterval(this.t)
this.t = null
} else {
console.log('过会再查')
}
})
}, 3000)
}
})
}
}
}
</script>
<style scoped>
</style>
视图类
from celery_task.user_task import sckill_goods
from celery_task.celery import app
from celery.result import AsyncResult
class SckillView(APIView):
def post(self, request, *args, **kwargs):
name = request.data.get('name')
# 提交秒杀异步任务
res = sckill_goods.delay(name)
return APIResponse(task_id=str(res))
def get(self, request, *args, **kwargs):
task_id = request.GET.get('task_id')
a = AsyncResult(id=task_id, app=app)
if a.successful(): # 正常执行完成
result = a.get() # 任务返回的结果
if result:
return APIResponse(code=100, msg='秒杀成功')
else:
return APIResponse(code=101, msg='秒杀失败')
elif a.status == 'STARTED':
print('任务已经开始被执行')
return APIResponse(code=103, msg='还在排队')
else:
return APIResponse(code=102, msg='没成功')
路由
urlpatterns = [
path('sckill/', SckillView.as_view()),
]
任务
@app.task
def sckill_goods(name):
# 逻辑是:开启事务---》扣减库存---》生成订单
import time
time.sleep(6)
res = random.choice([100, 102])
if res == 100:
print('%s被秒杀成功了' % name)
return True
else:
print('%s被秒杀失败了' % name)
return False
四、课程相关表分析
# 表分析
-课程分类表:id,分类名,继承BaseModel
-跟课程表是一对多,一个分类下有很多课程
-课程表(实战课课表)
-如果一个表:
-不同课程直接,字段可能不一样
-多个课程,多个表
-只写实战课这条线
-章节表:
跟课程是一对多
-课时表
跟章节是一对多
-老师表
-跟课程一对多
# 表的关联关系---》公司中外键都是逻辑外键,不建物理外键
-靠一个东西建立出来的三种关系----》外键
-一对一
-一对多
-多对多
图书 作者 多对多
图书表
id name price
1 xx 33
2 yy 32
作者
id name addr
1 多对 上海
2 大师傅 北京
中间表
id book_id auth_id
1 1 1
2 1 2
3 2 1
先创建一个course.app
表数据
from django.db import models
from utils.common_models import BaseModel
# 课程分类
class CourseCategory(BaseModel):
"""分类 id name """
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专享'),
)
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)
teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授课老师")
course_category = models.ForeignKey("CourseCategory", on_delete=models.SET_NULL, db_constraint=False, 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):
"""章节"""
'''
基于对象的跨表查询:正:字段 反:表名小写(一对一是 表名小写,一对多 表名小写_set.all())
-related_name='coursechapters' 基于对象跨表查反向查询,替换表名小写
基于双下划线的连表查询:正:字段 反:表名小写
-related_query_name='xxx' 基于连表查反向查询,替换表名小写
'''
# related_name='coursechapters'
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="课时标题")
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
迁移表
六、课程表数据录入
# 把sql执行
# 把 media文件夹下的图片放到对应位置
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);
七、课程主页接口
# 课程分类接口
# 查询所有课程接口
-带过滤
-带排序
-带分页
视图类
from .models import CourseCategory
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from .serializer import CourseCategorySerializer
from utils.common_mixin import CommonListModelMixin as ListModelMixin
class CourseCategoryView(GenericViewSet, ListModelMixin):
# 查询所有
queryset = CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders')
serializer_class = CourseCategorySerializer
序列化类
class CourseCategorySerializer(serializers.ModelSerializer):
class Meta:
model = CourseCategory
fields = ['id','name']
路由
from django.contrib import admin
from django.urls import path
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
from .views import CourseCategoryView
router.register('category', CourseCategoryView, 'category')
urlpatterns = [
]
urlpatterns += router.urls
标签:异步,verbose,name,课程,2022,07,课程表,id,14
From: https://www.cnblogs.com/yuezongke/p/17516903.html