当你发现自己的才华撑不起野心时,就请安静下来学习吧。

Personal site

↑点击传送

Django---django-rest-framework(drf)-luffycity projects

目录

http://liuqingzheng.top/python/Python%E7%B3%BB%E5%88%97%E6%95%99%E7%A8%8B/

pip换源

永久配置安装源

windows:

文件管理器敲%APPDATA%,进去之后新建pip文件夹,创建pip.ini配置文件,文件内容:

[global]
index-url = http://pypi.douban.com/simple
[install]
use-mirrors =true
mirrors =http://pypi.douban.com/simple/
trusted-host =pypi.douban.com

虚拟环境搭建

#优点
1 使用不同应用开发环境相互独立
2 环境升级不影响其他应用、不会冲突全局的python环境
3 防止出现包管理混乱及版本冲突
windown:
#建议使用pip3安装到python环境下
pip3 install virtualenv
pip3 install virtualenvwrapper-win
#创建文件夹D:\Virtualenvs
配置虚拟环境管理器工作目录
#配置环境变量
# 控制面板 => 系统和安全 => 系统 => 高级系统设置 => 环境变量 => 系统变量 => 点击新建 => 填入变量名与值
变量名:WORKON_HOME  变量值:自定义存放虚拟环境的绝对路径
eg: WORKON_HOME: D:\Virtualenvs
#同步配置信息
# 去向Python3的安装目录 => Scripts文件夹 => virtualenvwrapper.bat => 双击
使用
#终端命令
1 创建虚拟环境到配置的WORKON_HOME路径下
	mkvirtualenv -p python3 自定义的虚拟环境名称(比如:luffy)	使用的是python3
	mkvirtualenv -p python2 自定义的虚拟环境名称(比如:luffy)	使用的是python2
2 查看已有的虚拟环境
	workon
3 使用虚拟环境
	workon 已有的虚拟环境名称(比如:luffy)
4 进入、退出该虚拟环境的Python环境
	python、exit()
5 为虚拟环境安装模块
	pip install 模块名称(比如:django==2.2)
6 退出当前虚拟环境
	deactivate
7 删除虚拟环境(删除当前虚拟环境要先退出)
	rmvirtualenv
PyCharm的使用(使用虚拟环境)(我们使用这种方式,不建app)

新建项目

使用虚拟环境

环境使用

luffy后台搭建

环境
#给虚拟环境luffy安装依赖环境
    pip install django==2.2
	pip install djangorestframework
	pip install pymysql
创建项目(我们前面已经用PyCharm创建好了)
在目标目录下创建luffy文件夹
cd 进入luffy项目
django-admin startproject luffyapi
用PyCharm打开项目,使用已经建好的虚拟环境
重构项目目录
luffyapi
	-logs	#项目运行时/开发时的日志目录
	-manage.py	#脚本文件
	-scripts	#保存项目运营时的脚本文件
	-luffyapi	#项目的主应用,开发时的代码保存
		-utils(包带__init__.py)公共函数库
		-urls.py	#总路由
		-apps(包带__init__.py)	#子应用保存目录
		-libs	#第三方类库的保存目录
		-settings(包带__init__.py)	#配置目录
			-dev.py	#项目开发时的本地配置
			-prod.py	#项目上线时的运行配置
创建doc文件夹、创建readme.md文件
终端下创建两个应用到apps
cd 到apps目录下
python ../../manage.py startapp home
python ../../manage.py startapp user
因为manage.py在根目录,所以需要../../到根目录去用该文件
配置开发环境
1 把settings.py内容复制到dev.py,原来的settings.py删除
2 #修改下面两文件
# manage.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE','luffyapi.settings.dev')
# wsgi.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE','luffyapi.settings.dev')#本地使用.dev,后面修改为.prod即可
3 修改dev.py文件内容(错误信息改成中文)
	LANGUAGE_CODE = 'zh-hans'
    TIME_ZONE = 'Asia/Shanghai'
    USE_TZ = False
4 修改启动配置
	看下图
5 把apps做成Sources Root看图2

数据库配置

创建项目依赖数据库,luffyapi
	create database luffyapi;
创建数据库用户,授予使用luffyapi数据库的权利	
	grant all privileges on luffyapi.* to'luffyapi'@'localhost' identified by '123';
	---上面命令指:创建用户luffyapi授予使用luffyapi数据库使用权,用户密码是123
刷新权限
    flush privileges;
#配置文件配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'luffy',
        'USER': 'luffy',
        'PASSWORD': 'Luffy123',
        'HOST': 'localhost',
        'PORT': 3306
    }
}
import pymysql
pymysql.install_as_MySQLdb()

django2.x版本可能会出现一些pymysql兼容问题,按报错注释、修改源码即可

User表配置

导入from django.contrib.auth.models import AbstractUser
继承user之前不要数据迁移命令,会出错,需要:
		-把所有app下的迁移文件,全删除
    	-admin,auth app下的迁移文件删除
   	    -删库(数据一定要导出来),重新迁移  (自己尝试一下)
继承AbstractUser,增加两个字段,mobilephone、icon,
	    mobilephone = models.CharField(max_length=11,unique=True)
    	icon = models.ImageField(upload_to='icon',default='media/default.png')
在settings.py中配置
	MEDIA_URL='/media/'
	MEDIA_ROOT=os.path.join(BASE_DIR,'media')
	#此时的BASE_DIR是luffyapi下的luffyapi
路由开放media文件夹,访问头像,需要导入
    from django.views.static import serve
    from django.conf import settings
    
	re_path('media/(?P<path>.*)', serve{'document_root':settings.MEDIA_ROOT}),	

luffy前台搭建

1 安装node.js,官网下载,一路下一步
	查看版本node -v
2 安装模块,npm比较慢,用淘宝的cnpm来替换npm
	npm install -g cnpm --registry=https://registry.npm.taobao.org   
3 创建vue的工程,需要一个vue脚手架
	cnpm install -g @vue/cli
4 如果有问题执行如下,重走2、3步
	npm cache clean --force
5 创建vue项目
	vue create 自定义项目名(我们用luffycity)
	选Manually
6 用pycharm打开,配置快键启动
	看下图

目录介绍

public
    -favicon.ico   # 
    -index.html    #整个项目的单页面
src
    -assets  #静态文件,js,css,img
    -components # 小组件,头部组件,尾部组件
    -router     # 路由相关
    -store      # vuex相关,状态管理器,临时存储数据的地方
    -views      # 页面组件
    -App.vue    # 根组件
    -main.js    # 配置文件(跟django的setting一样
#任何一个组件都有三部分,里面书写相关代码
	<template>
    	#html相关
	</template>
    <style>
		# css相关
	</style>

    <script>
		# js相关
    </script>

luffy后台配置

封装Response对象、异常处理

#封装Response对象
	#luffyapi\utils\response.py
		from rest_framework.response import Response
        class APIResponse(Response):
            def __init__(self, code=100, msg='成功', data=None, status=None, headerrs=None, **kwargs):
                dic = {'code': code, msg: msg}
                if data:
                    dic = dic['data'] = data
                dic.update(kwargs)
                super().__init__(data=dic, status=status, headers=headerrs)
    #视图方法中使用       
    	return APIResponse(data={"name":'lqz'},token='dsafsdfa',aa='dsafdsafasfdee')
#封装异常处理
	#luffyapi\utils\exceptions.py
        from rest_framework.views import exception_handler
        from .response import APIResponse
        from .logger import log
        def common_exception_handler(exc, context):
            log.error('view是:%s ,错误是%s'%(context['view'].__class__.__name__,str(exc)))
            #context['view']  是TextView的对象,想拿出这个对象对应的类名
            print(context['view'].__class__.__name__)
            ret=exception_handler(exc, context)  # 是Response对象,它内部有个data

            if not ret:  #drf内置处理不了,丢给django 的,我们自己来处理
                # 好多逻辑,更具体的捕获异常
                if isinstance(exc,KeyError):
                    return APIResponse(code=0, msg='key error')

                return APIResponse(code=0,msg='error',result=str(exc))
            else:
                return APIResponse(code=0,msg='error',result=ret.data)
                

封装日志

#luffyapi\utils\logger.py
	import logging
    log=logging.getLogger('django')
#luffyapi\settings\dev.py中配置
	#日志配置
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'verbose': {
                'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
            },
            'simple': {
                'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
            },
        },
        'filters': {
            'require_debug_true': {
                '()': 'django.utils.log.RequireDebugTrue',
            },
        },
        'handlers': {
            'console': {
                # 实际开发建议使用WARNING
                'level': 'DEBUG',
                'filters': ['require_debug_true'],
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'file': {
                # 实际开发建议使用ERROR
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                # 日志位置,日志文件名,日志保存目录必须手动创建,注:这里的文件路径要注意BASE_DIR代表的是小luffyapi
                'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
                # 日志文件的最大值,这里我们设置300M
                'maxBytes': 300 * 1024 * 1024,
                # 日志文件的数量,设置最大日志数量为10
                'backupCount': 100,
                # 日志格式:详细格式
                'formatter': 'verbose',
                # 文件内容编码
                'encoding': 'utf-8'
            },
        },
        # 日志对象
        'loggers': {
            'django': {
                'handlers': ['console', 'file'],
                'propagate': True, # 是否让日志信息继续冒泡给其他的日志处理系统
            },
        }
    }
# 以后使用直接导入
	from luffyapi.utils.logger import log

解决跨域问题(xss、cors、csrf)

#XSS指跨站脚本攻击,CORS指跨域资源共享、CSRF指跨站请求伪造
1 同源策略指协议,域名,端口一致为同源
2 CORS跨域资源共享,允许不同的域来自己的服务器拿数据
3 CORS请求分简单请求(simple request),非简单请求(not-so-simple request)
	#简单请求是指满足以下两大条件就是简单请求
		1 三种请求方法之一
			HEAD
			GET
			POST
		2 HTTP的头信息不超出以下几种字段
			Accept
            Accept-Language
            Content-Language
            Last-Event-ID
            Content-Type:application/x-www-form-urlencoded、multipart/form-data、text/plain#只能是这三种类型,否则就算不满足该条件
	#非简单请求是指post请求,数据格式是json, 非简单请求需要发两次,OPTIONS请求,一次POST请求
4 自己在后端解决跨域问题,开启CORS,跨域资源共享(写中间件)
	#luffyapi\utils\middle.py
        from django.utils.deprecation import MiddlewareMixin
        class MyMiddle(MiddlewareMixin):
            def process_response(self, request, response):
                response['Access-Control-Allow-Origin'] = '*'
                if request.method == "OPTIONS":
                    # 可以加*
                    response["Access-Control-Allow-Headers"] = "Content-Type"
                    response["Access-Control-Allow-Headers"] = "authorization"
                return response
	#dev.py配置
        MIDDLEWARE = [
        #自定义的跨域资源共享
        'luffyapi.utils.middle.MyMiddle',]
5 使用第三方的django-cors-headers
	#安装pip install django-core-headers
	#配置注册app 'corsheaders'
	#配置中间件
		MIDDLEWARE = [
            #第三方的解决跨域资源共享
            'corsheaders.middleware.CorsMiddleware',]
	#配置其他参数
        CORS_ORIGIN_ALLOW_ALL = True
        CORS_ALLOW_METHODS = (
            'DELETE',
            'GET',
            'OPTIONS',
            'PATCH',
            'POST',
            'PUT',
            'VIEW',
        )
        CORS_ALLOW_HEADERS = (
            'authorization',
            'content-type',
        )

前后台打通

1 前台发送jQuery封装的ajax请求,或通过promise封装axios请求
2 安装axios,cnpm install axios
3 配置在VUE前端的main.js
	#main.js
		import Vue from 'vue'
        import App from './App.vue'
        import router from './router'
        import store from './store'

        Vue.config.productionTip = false

        import axios from 'axios'

        Vue.prototype.$axios = axios


        new Vue({
          router,
          store,
          render: h => h(App)
        }).$mount('#app')
	#Home.Vue
    	<template>
        <div class="home">
            <h1>主页</h1>
        </div>
    	</template>
    	<script>

        export default {
            name: 'Home',
            created() {
                this.$axios.get('http://127.0.0.1:8000/home/home/').then(response => {
                    console.log(response.data)  //response.data才是真正后台返回的数据
                }).catch(errors => {
                    console.log(errors)
                })

            },
            components: {}
        }
    	</script>
#了解es6的箭头函数
    function (response) { console.log(response)}
    response=>{ console.log(response)}    	

xadmin的使用

1 安装pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2
2 app中注册
	#luffyapi\settings\dev.py
        INSTALLED_APPS = [
        # xadmin主体模块
        'xadmin',
        # 渲染表格模块
        'crispy_forms',
        # 为模型通过版本控制,可以回滚数据
        'reversion',]
        
3 数据库迁移
	python manage.py makemigrations
	python manage.py migrate
4 主路由替换admin
	#urls.py
        # xadmin的依赖
        import xadmin
        xadmin.autodiscover()
        # xversion模块自动注册需要版本控制的 Model
        from xadmin.plugins import xversion
        xversion.register_models()
        urlpatterns = [
            # path('admin/', admin.site.urls),
            path('xadmin/', xadmin.site.urls),
        ]
5 创建超级用户,PyCharm终端执行
	python manage.py createsuperuser

luffy前台组件搭建

头部组件

#在components新建Head.vue
    <template>
        <div class="header">
            <div class="slogan">
                <p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
            </div>
            <div class="nav">
                <ul class="left-part">
                    <li class="logo">
                        <router-link to="/">
                            <img src="../assets/img/head-logo.svg" alt="">
                        </router-link>
                    </li>
                    <li class="ele">
                        <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
                    </li>
                    <li class="ele">
                        <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">实战课</span>
                    </li>
                    <li class="ele">
                        <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
                    </li>
                </ul>

                <div class="right-part">
                    <div>
                        <span>登录</span>
                        <span class="line">|</span>
                        <span>注册</span>
                    </div>
                </div>
            </div>
        </div>

    </template>

    <script>

        export default {
            name: "Header",
            data() {
                return {
                    url_path: sessionStorage.url_path || '/',
                }
            },
            methods: {
                goPage(url_path) {
                    // 已经是当前路由就没有必要重新跳转
                    if (this.url_path !== url_path) {
                        this.$router.push(url_path);
                    }
                    sessionStorage.url_path = url_path;
                },
            },
            created() {
                sessionStorage.url_path = this.$route.path;
                this.url_path = this.$route.path;
            }
        }
    </script>

    <style scoped>
        .header {
            background-color: white;
            box-shadow: 0 0 5px 0 #aaa;
        }

        .header:after {
            content: "";
            display: block;
            clear: both;
        }

        .slogan {
            background-color: #eee;
            height: 40px;
        }

        .slogan p {
            width: 1200px;
            margin: 0 auto;
            color: #aaa;
            font-size: 13px;
            line-height: 40px;
        }

        .nav {
            background-color: white;
            user-select: none;
            width: 1200px;
            margin: 0 auto;

        }

        .nav ul {
            padding: 15px 0;
            float: left;
        }

        .nav ul:after {
            clear: both;
            content: '';
            display: block;
        }

        .nav ul li {
            float: left;
        }

        .logo {
            margin-right: 20px;
        }

        .ele {
            margin: 0 20px;
        }

        .ele span {
            display: block;
            font: 15px/36px '微软雅黑';
            border-bottom: 2px solid transparent;
            cursor: pointer;
        }

        .ele span:hover {
            border-bottom-color: orange;
        }

        .ele span.active {
            color: orange;
            border-bottom-color: orange;
        }

        .right-part {
            float: right;
        }

        .right-part .line {
            margin: 0 10px;
        }

        .right-part span {
            line-height: 68px;
            cursor: pointer;
        }
    </style>

配置全局css和setting

#在main.js中配置
    // 配置全局样式 @ 符号,代指src路径
    import '@/assets/css/global.css'
    // 配置全局自定义设置
    import settings from '@/assets/js/settings'
    Vue.prototype.$settings = settings;
    // 在所有需要与后台交互的组件中:this.$settings.base_url + '再拼接具体后台路由'

# 在assets下的css中加入global.css
    /* 声明全局样式和项目的初始化样式 */
    body, h1, h2, h3, h4, h5, h6, p, table, tr, td, ul, li, a, form, input, select, option, textarea {
        margin: 0;
        padding: 0;
        font-size: 15px;
    }

    a {
        text-decoration: none;
        color: #333;
    }

    ul {
        list-style: none;
    }

    table {
        border-collapse: collapse; /* 合并边框 */
    }


    # 在assets下的js中加入settings.js
    export default {
        base_url: 'http://127.0.0.1:8000'
    }

前台配置

#安装
    cnpm install axios
    cnpm install vue-cookies
    cnpm install element-ui
    cnpm install jquery
    cnpm install bootstrap@3
#在main.js中配置
    //axios配置
    import axios from 'axios'
    Vue.prototype.$axios = axios;
    // vue-cookies配置
    import cookies from 'vue-cookies'
    Vue.prototype.$cookies = cookies;
    // ElementUI的配置
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    Vue.use(ElementUI);
    // bootstrap配置
    import 'bootstrap'
    import 'bootstrap/dist/css/bootstrap.min.css'
#jquery配置,项目根目录下创建vue.config.js
    const webpack = require("webpack");
    module.exports = {
        configureWebpack: {
            plugins: [
                new webpack.ProvidePlugin({
                    $: "jquery",
                    jQuery: "jquery",
                    "window.jQuery": "jquery",
                    "window.$": "jquery",
                    Popper: ["popper.js", "default"]
                })
            ]
        }
    };

luffy尾部组件

#footer.vue
	<template>
        <div class="footer">
            <ul>
                <li>关于我们</li>
                <li>联系我们</li>
                <li>商务合作</li>
                <li>帮助中心</li>
                <li>意见反馈</li>
                <li>新手指南</li>
            </ul>
            <p>Copyright © luffycity.com版权所有 | 京ICP备17072161号-1</p>
        </div>
    </template>

    <script>
        export default {
            name: "Footer"
        }
    </script>

    <style scoped>
        .footer {
            width: 100%;
            height: 128px;
            background: #25292e;
            color: #fff;
        }

        .footer ul {
            margin: 0 auto 16px;
            padding-top: 38px;
            width: 810px;
        }

        .footer ul li {
            float: left;
            width: 112px;
            margin: 0 10px;
            text-align: center;
            font-size: 14px;
        }

        .footer ul::after {
            content: "";
            display: block;
            clear: both;
        }

        .footer p {
            text-align: center;
            font-size: 12px;
        }
    </style>

轮播图接口

#urls.py
####1  urls.py 
from rest_framework.routers import  SimpleRouter
router=SimpleRouter()
router.register('banner',views.BannerView,'banner')
urlpatterns = [
    # path('banner/', views.BannerView.as_view()),
    path('', include(router.urls)),
]

####2 views.py
from django.conf import settings
class BannerView(GenericViewSet,ListModelMixin):
    # 无论有多少条待展示的数据,最多就展示3条
    queryset = models.Banner.objects.filter(is_delete=False,is_show=True).order_by('display_order')[:settings.BANNER_COUNTER]
    serializer_class = serializer.BannerModelSerilaizer
    
### 3 serializer.py
from rest_framework import serializers
from . import models
class BannerModelSerilaizer(serializers.ModelSerializer):
    class Meta:
        model=models.Banner
        fields=['name','link','img']
        
### 4 models.py
from utils.models import BaseModel


class Banner(BaseModel):
    name=models.CharField(max_length=32,verbose_name='图片名字')
    img=models.ImageField(upload_to='banner',verbose_name='轮播图',help_text='图片尺寸必须是:3840*800',null=True)
    link=models.CharField(max_length=32,verbose_name='跳转连接')
    info=models.TextField(verbose_name='图片简介')
    # type=models.IntegerField(choices=)

    def __str__(self):
        return self.name
####5 utils/models.py

class BaseModel(models.Model):
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')
    is_show = models.BooleanField(default=True, verbose_name='是否展示')
    display_order = models.IntegerField()
    class Meta:
        abstract=True  # 一定不要忘了
        
### 6 settings/const.py
# 首页轮播图个数
BANNER_COUNTER=3

#### 7 settings/dev.py
from .const import *

轮播图组件

#Banner.vue
    <template>

        <div id="banner">

            <el-carousel height="400px">
                <el-carousel-item v-for="item in banner_list">
                    <!--<img src="../assets/img/banner1.png" alt="">-->
                    <router-link :to="item.link">
                        <img :src="item.img" :alt="item.name">
                    </router-link>

                </el-carousel-item>
            </el-carousel>
        </div>

    </template>

    <script>
        export default {
            name: "Banner",
            // data:function(){},
            data() {
                return {
                    banner_list: []
                }
            },
            created() {
                //当banner组件一创建,就向后台发请求,拿回轮播图数据
                this.$axios.get(this.$settings.base_url + '/home/banner/').then(response => {
                    console.log(response.data)
                    this.banner_list=response.data
                }).catch(error => {
                })
            },

        }
    </script>

    <style scoped>
        .el-carousel__item {
            height: 400px;
            min-width: 1200px;
        }

        .el-carousel__item img {
            height: 400px;
            /*margin-left: 20px;*/
            /*margin-left: calc(50% - 1920px / 2);*/
        }
    </style>
#src\router\index.js
	#路由设置
	const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/free-course',
        name: 'FreeCourse',
        component: FreeCourse
    }, {
        path: '/light-course',
        name: 'LightCourse',
        component: LightCourse
    }, {
        path: '/actual-course',
        name: 'ActualCourse',
        component: ActualCourse
    },

]

Git入门

简介
#生成.ssh命令(命令行)ssh-keygen -t rsa -C "your_email@example.com"
#查看公钥命令(命令行)cat ~/.ssh/id_rsa.pub
#git是版本控制器
	#完成协同项目开发,帮助程序员整合代码
	#合并代码冲突,会提示合并代码的开发者,让其解决
	#git分布式管理,svn集中式管理
#git工作流程
	工作区-暂存区-版本区
#远程仓库github,gitee(国内),gitlab(公司内部)
#安装,下载https://npm.taobao.org/mirrors/git-for-windows/v2.27.0.windows.1/一路下一步
#安装完成,在需要管理文件的目录右键 git bash here进入命令行
git命令
git init 文件夹名 或 git init #表示当前路径全部管理
git status #查看文件状态,红色的文件表示未被管理,绿色表示在暂存区了
git add a.txt #添加a.txt到暂存区
git add . #添加当前所有文件到暂存区
git commit -m '我新增了a.txt' #把暂存区所有的提交到本地版本区,必须要写注释
#需要添加作者信息
	git config --global user.email "joab@qq.com"
	git config --global user.name "joab"
git log #查看版本管理的日志
git reflog #查看日志,条数更少,内容更多
#忽略文件
	1 空文件夹不会被管理
	2 指定文件或文件夹不被管理,在根目录建一个.gitignore.文件,注意前后都有一个点,文件内写忽略文件,
		a.txt	#忽略a.txt
		 /dist	#忽略根路径下的dist文件夹,不被管理
        *.py   #表示忽略后缀名为py的文件,都被忽略,不止当前路径,子目录也生效
        *.log*	#表示忽略文件名中间为.log的所有文件,不止当前路径,子目录也生效
#分支操作
	git branch 分支名(如dev)	#创建分支
	git checkout dev	#切换分支
	git checkout -b dev		#创建并切换到dev
	git branch -d dev	#删除分支dev
	git merge 分支名	#合并分支,需要先切换到主分支master,再执行合并dev分支

Git远程连接

1 连接Gitee,国内的比较快
2 Gitee新建仓库,不要勾选Readme初始化仓库
3 本地新建一个文件,去连接Gitee
	mkdir test
	cd test
	git init	#管理当前目录
	git add a.txt	#添加a.txt到暂存区
	git commit -m "提交了a.txt"
	git remote add origin 你的Gitee仓库HTTPS地址,创建仓库的时候能看到,看图1(我的用https://gitee.com/lin_qiao_bao/test.git),或者是SSH地址也可以	
    git remote remove origin	删除连接仓库
	git push  origin master	#提交到Gitee仓库,第一次提交需要Gitee的用户名,密码
#已有本地文件
	cd 你的文件路径
	git remote add origin 你的Gitee仓库HTTPS地址或SSH地址,创建仓库的时候能看到,看图1(我的用https://gitee.com/lin_qiao_bao/test.git)
	git push  origin master	#提交到Gitee仓库,第一次提交需要Gitee的用户名,密码
4 git 远程操作命令
	git remote	#查看远程仓库,没绑定就看不到
	git remote add origin 你的Gitee仓库HTTPS地址,创建仓库的时候能看到,看图1(我的用https://gitee.com/lin_qiao_bao/test.git)	#跟远程仓库建立连接
	git push origin master	##提交到Gitee仓库,第一次提交需要Gitee的用户名,密码

图1

Gitee仓库创始者和开发者

1 创始者指创建仓库者
2 项目开发者,被创始者授权了的用户,可以把代码拉下来开发,还有提交代码
	git clone 需要拉代码的Gitee仓库HTTPS地址	#代码拉到本地,能够看到完整的版本和日志记录,能恢复到任意版本
	git rset --hard 版本号		#恢复到指定版本号
	git checkout .		#表示回到指针指向的版本,因为git rest --hard把指针移动了,
#新增c.txt
	1 git add c.txt		#提交到暂存区
	2 git commit -m '提交了c.txt'	#提交到本地版本区
	3 git push origin master	#提交到gitee仓库
3 重点,每次提交交代前,先拉去代码,再提交,不然有可能在你之前别人提交了过代码,会冲突

SSH链接和HTTPS链接

老刘的地址https://gitee.com/liuqingzheng/luffyapi.git
1 公司大部分用SSH连接
	-leader会给你一个git地址(项目仓库地址)
	-你从仓库拉代码下来
	-写代码,提交到leader测试,通过就上线
	-ssh配置,不需要用户名,密码
2 ssh配置,采用非对称加密
	生成一对一公钥和私钥看图1	#公钥在本地用户名目录下的.ssh下的id_rsa.pub,id_rsa私钥
#跟远程操作有关的命令
    git clone 需要拉代码的Gitee仓库HTTPS地址	#拉gitee代码
    git push origin master	#提交到gitee仓库

PyCharm操作Git

1 安装Git
2 在PyCharm中配置,setting---git---git.exe
3 git clone 看图3
4 创建本地分支,看图4
5 拉取远程仓库代码,看图5
6 提交代码到远程仓库,看图6
7 本地代码与仓库比较,看图7

图3

图4

图5

图6

图7

协同开发

#协同开发,从仓库拉取代码,提交代码可能会出现冲突
    <<<<<<< HEAD
    你的代码
    =======
    别人代码
#处理方案
	-删除自己的代码
	-删除冲突的代码
	-看情况优化代码

线上分支合并

#看到可自动合并,表示合并后不会冲突
#测试人员通过,直接合并即可


线上回滚

1 先查看要恢复的版本git log 或 git reflog复制版本号,然后切换到master主分支
2 回滚到某个版本, git reset --hard 版本号
3 强制提交代码 git push origin master -f

vue登录界面

# Login.vue
    <template>
        <div class="login">
        <span @click="close_login">X</span>
        </div>
    </template>

    <script>
        export default {
            name: "Login",
            methods:{
                close_login(){
                    //子传父组件 this.$emit,给父组件传递一个事件
                    this.$emit("close")
                },

            },

        }
    </script>

    <style scoped>
    .login{
        width: 100vw;
        height: 100vw;
        position: fixed;
        left: 0;
        top: 0;
        z-index: 666;
        background-color: rgba(0,0,0,0.3);
    }
        span{
            font-size: 30px;
            cursor: pointer;
        }
    </style>

    # Head.vue
    #template中
    <div class="right-part">
    <div>
    <span @click="pull_login">登录</span>
    <span class="line">|</span>
    <span>注册</span>
    </div>
    </div>
    </div>

    <Login v-if="is_login" @close="close"/>
    <!--is_login是True就显示,false就不显示-->
    </div>
    # js中
    pull_login(){
        this.is_login=true
    },
    close(){
        this.is_login=false
    },

登录注册模态框

#src\components\Login.vue
    <template>
        <div class="login">
            <div class="box">
                <i class="el-icon-close" @click="close_login"></i>
                <div class="content">
                    <div class="nav">
                        <span :class="{active: login_method === 'is_pwd'}"
                              @click="change_login_method('is_pwd')">密码登录</span>
                        <span :class="{active: login_method === 'is_sms'}"
                              @click="change_login_method('is_sms')">短信登录</span>
                    </div>
                    <el-form v-if="login_method === 'is_pwd'">
                        <el-input
                                placeholder="用户名/手机号/邮箱"
                                prefix-icon="el-icon-user"
                                v-model="username"
                                clearable>
                        </el-input>
                        <el-input
                                placeholder="密码"
                                prefix-icon="el-icon-key"
                                v-model="password"
                                clearable
                                show-password>
                        </el-input>
                        <el-button type="primary">登录</el-button>
                    </el-form>
                    <el-form v-if="login_method === 'is_sms'">
                        <el-input
                                placeholder="手机号"
                                prefix-icon="el-icon-phone-outline"
                                v-model="mobile"
                                clearable
                                @blur="check_mobile">
                        </el-input>
                        <el-input
                                placeholder="验证码"
                                prefix-icon="el-icon-chat-line-round"
                                v-model="sms"
                                clearable>
                            <template slot="append">
                                <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                            </template>
                        </el-input>
                        <el-button type="primary">登录</el-button>
                    </el-form>
                    <div class="foot">
                        <span @click="go_register">立即注册</span>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            name: "Login",
            data() {
                return {
                    username: '',
                    password: '',
                    mobile: '',
                    sms: '',
                    login_method: 'is_pwd',
                    sms_interval: '获取验证码',
                    is_send: false,
                }
            },
            methods: {
                close_login() {
                    this.$emit('close')
                },
                go_register() {
                    this.$emit('go')
                },
                change_login_method(method) {
                    this.login_method = method;
                },
                check_mobile() {
                    if (!this.mobile) return;
                    if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                        this.$message({
                            message: '手机号有误',
                            type: 'warning',
                            duration: 1000,
                            onClose: () => {
                                this.mobile = '';
                            }
                        });
                        return false;
                    }
                    this.is_send = true;
                },
                send_sms() {

                    if (!this.is_send) return;
                    this.is_send = false;
                    let sms_interval_time = 60;
                    this.sms_interval = "发送中...";
                    let timer = setInterval(() => {
                        if (sms_interval_time <= 1) {
                            clearInterval(timer);
                            this.sms_interval = "获取验证码";
                            this.is_send = true; // 重新回复点击发送功能的条件
                        } else {
                            sms_interval_time -= 1;
                            this.sms_interval = `${sms_interval_time}秒后再发`;
                        }
                    }, 1000);
                }
            }
        }
    </script>

    <style scoped>
        .login {
            width: 100vw;
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 10;
            background-color: rgba(0, 0, 0, 0.3);
        }

        .box {
            width: 400px;
            height: 420px;
            background-color: white;
            border-radius: 10px;
            position: relative;
            top: calc(50vh - 210px);
            left: calc(50vw - 200px);
        }

        .el-icon-close {
            position: absolute;
            font-weight: bold;
            font-size: 20px;
            top: 10px;
            right: 10px;
            cursor: pointer;
        }

        .el-icon-close:hover {
            color: darkred;
        }

        .content {
            position: absolute;
            top: 40px;
            width: 280px;
            left: 60px;
        }

        .nav {
            font-size: 20px;
            height: 38px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span {
            margin: 0 20px 0 35px;
            color: darkgrey;
            user-select: none;
            cursor: pointer;
            padding-bottom: 10px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span.active {
            color: black;
            border-bottom: 3px solid black;
            padding-bottom: 9px;
        }

        .el-input, .el-button {
            margin-top: 40px;
        }

        .el-button {
            width: 100%;
            font-size: 18px;
        }

        .foot > span {
            float: right;
            margin-top: 20px;
            color: orange;
            cursor: pointer;
        }

        .sms {
            color: orange;
            cursor: pointer;
            display: inline-block;
            width: 70px;
            text-align: center;
            user-select: none;
        }
    </style>
#src\components\Register.vue
    <template>
        <div class="register">
            <div class="box">
                <i class="el-icon-close" @click="close_register"></i>
                <div class="content">
                    <div class="nav">
                        <span class="active">新用户注册</span>
                    </div>
                    <el-form>
                        <el-input
                                placeholder="手机号"
                                prefix-icon="el-icon-phone-outline"
                                v-model="mobile"
                                clearable
                                @blur="check_mobile">
                        </el-input>
                        <el-input
                                placeholder="密码"
                                prefix-icon="el-icon-key"
                                v-model="password"
                                clearable
                                show-password>
                        </el-input>
                        <el-input
                                placeholder="验证码"
                                prefix-icon="el-icon-chat-line-round"
                                v-model="sms"
                                clearable>
                            <template slot="append">
                                <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                            </template>
                        </el-input>
                        <el-button type="primary">注册</el-button>
                    </el-form>
                    <div class="foot">
                        <span @click="go_login">立即登录</span>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            name: "Register",
            data() {
                return {
                    mobile: '',
                    password: '',
                    sms: '',
                    sms_interval: '获取验证码',
                    is_send: false,
                }
            },
            methods: {
                close_register() {
                    this.$emit('close', false)
                },
                go_login() {
                    this.$emit('go')
                },
                check_mobile() {
                    if (!this.mobile) return;
                    if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                        this.$message({
                            message: '手机号有误',
                            type: 'warning',
                            duration: 1000,
                            onClose: () => {
                                this.mobile = '';
                            }
                        });
                        return false;
                    }
                    this.is_send = true;
                },
                send_sms() {
                    if (!this.is_send) return;
                    this.is_send = false;
                    let sms_interval_time = 60;
                    this.sms_interval = "发送中...";
                    let timer = setInterval(() => {
                        if (sms_interval_time <= 1) {
                            clearInterval(timer);
                            this.sms_interval = "获取验证码";
                            this.is_send = true; // 重新回复点击发送功能的条件
                        } else {
                            sms_interval_time -= 1;
                            this.sms_interval = `${sms_interval_time}秒后再发`;
                        }
                    }, 1000);
                }
            }
        }
    </script>

    <style scoped>
        .register {
            width: 100vw;
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 10;
            background-color: rgba(0, 0, 0, 0.3);
        }

        .box {
            width: 400px;
            height: 480px;
            background-color: white;
            border-radius: 10px;
            position: relative;
            top: calc(50vh - 240px);
            left: calc(50vw - 200px);
        }

        .el-icon-close {
            position: absolute;
            font-weight: bold;
            font-size: 20px;
            top: 10px;
            right: 10px;
            cursor: pointer;
        }

        .el-icon-close:hover {
            color: darkred;
        }

        .content {
            position: absolute;
            top: 40px;
            width: 280px;
            left: 60px;
        }

        .nav {
            font-size: 20px;
            height: 38px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span {
            margin-left: 90px;
            color: darkgrey;
            user-select: none;
            cursor: pointer;
            padding-bottom: 10px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span.active {
            color: black;
            border-bottom: 3px solid black;
            padding-bottom: 9px;
        }

        .el-input, .el-button {
            margin-top: 40px;
        }

        .el-button {
            width: 100%;
            font-size: 18px;
        }

        .foot > span {
            float: right;
            margin-top: 20px;
            color: orange;
            cursor: pointer;
        }

        .sms {
            color: orange;
            cursor: pointer;
            display: inline-block;
            width: 70px;
            text-align: center;
            user-select: none;
        }
    </style>
#src\components\Head.vue
    <template>
        <div class="header">
            <div class="slogan">
                <p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
            </div>
            <div class="nav">
                <ul class="left-part">
                    <li class="logo">
                        <router-link to="/">
                            <img src="../assets/img/head-logo.svg" alt="">
                        </router-link>
                    </li>
                    <li class="ele">
                        <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
                    </li>
                    <li class="ele">
                        <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">实战课</span>
                    </li>
                    <li class="ele">
                        <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
                    </li>
                </ul>

                <div class="right-part">
                    <div v-if="!username">
                        <span @click="put_login">登录</span>
                        <span class="line">|</span>
                        <span @click="put_register">注册</span>
                    </div>
                    <div v-else>
                        <span >{{username}}</span>
                        <span class="line">|</span>
                        <span @click="logout">注销</span>
                    </div>
                </div>
                <Login v-if="is_login" @close="close_login" @go="put_register" @loginsuccess="login_success"/>
                <Register v-if="is_register" @close="close_register" @go="put_login"/>
            </div>
        </div>

    </template>

    <script>
        import Login from './Login'
        import Register from './Register'

        export default {
            name: "Header",
            data() {
                return {
                    url_path: sessionStorage.url_path || '/',
                    is_login: false,
                    is_register: false,
                    token: '',
                    username: ''
                }
            },
            methods: {
                goPage(url_path) {
                    // 传入的路由如果不是当前所在路径,就跳转
                    if (this.url_path !== url_path) {
                        this.$router.push(url_path);
                    }
                    sessionStorage.url_path = url_path;
                },
                put_login() {
                    this.is_login = true;
                    this.is_register = false;
                },
                put_register() {
                    this.is_login = false;
                    this.is_register = true;
                },
                close_login() {
                    this.is_login = false;
                },
                close_register() {
                    this.is_register = false;
                },
                login_success(){
                    this.username=this.$cookies.get('username')
                    this.token=this.$cookies.get('token')
                },
                logout(){
                    //清除cookie
                    this.$cookies.remove('token')
                    this.$cookies.remove('username')
                    //把两个变量值为空
                    this.username=''
                    this.token=''
                },
            },
            created() {
                sessionStorage.url_path = this.$route.path;
                this.url_path = this.$route.path;

                //当页面一创建,我就去cookie中取token和username
                this.username = this.$cookies.get('username')   //取到就有值,取不到就为空
                this.token = this.$cookies.get('token')   //取到就有值,取不到就为空
            },
            components: {
                Login,
                Register
            }


        }
    </script>

    <style scoped>
        .header {
            background-color: white;
            box-shadow: 0 0 5px 0 #aaa;
        }

        .header:after {
            content: "";
            display: block;
            clear: both;
        }

        .slogan {
            background-color: #eee;
            height: 40px;
        }

        .slogan p {
            width: 1200px;
            margin: 0 auto;
            color: #aaa;
            font-size: 13px;
            line-height: 40px;
        }

        .nav {
            background-color: white;
            user-select: none;
            width: 1200px;
            margin: 0 auto;

        }

        .nav ul {
            padding: 15px 0;
            float: left;
        }

        .nav ul:after {
            clear: both;
            content: '';
            display: block;
        }

        .nav ul li {
            float: left;
        }

        .logo {
            margin-right: 20px;
        }

        .ele {
            margin: 0 20px;
        }

        .ele span {
            display: block;
            font: 15px/36px '微软雅黑';
            border-bottom: 2px solid transparent;
            cursor: pointer;
        }

        .ele span:hover {
            border-bottom-color: orange;
        }

        .ele span.active {
            color: orange;
            border-bottom-color: orange;
        }

        .right-part {
            float: right;
        }

        .right-part .line {
            margin: 0 10px;
        }

        .right-part span {
            line-height: 68px;
            cursor: pointer;
        }
    </style>

登录注册接口分析

1 是多方式用户登录接口
2 手机号登录接口
3 发送验证码接口
4 注册接口
5 校检手机号是否存在接口

多种方式登录

#luffyapi\apps\user\views.py
    from luffyapi.utils.response import APIResponse
    from rest_framework.viewsets import ViewSet
    from . import serializer
    from rest_framework.decorators import action
    class LoginViewSet(ViewSet):

        @action(methods=['POST'],detail=False)
        def login(self,request,*args,**kwargs):
            user_ser = serializer.UserModelSerializer(data=request.data)
            if user_ser.is_valid():#自定义了全局异常,不需要使用raise_exception=True
                #从序列化对象user_ser.context中获取token和用户名
                token = user_ser.context['token']
                username = user_ser.context['user'].username
                return APIResponse(token=token,username=username)
            else:
                return APIResponse(code=0,msg=user_ser.errors)#序列化校检失败,返回错误信息
#luffyapi\apps\user\serializer.py
    #用户序列化器
    from rest_framework import serializers
    from . import models
    from rest_framework.exceptions import ValidationError
    class UserModelSerializer(serializers.ModelSerializer):
        username = serializers.CharField()#username为unique字段,需要重定义
        class Meta:
            model = models.User
            fields = ('username','password','id')
            extra_kwargs = {
                'id':{'read_only':True},
                'password':{'write_only':True}
            }

        #全局钩子,判断多方式登录
        def validate(self, attrs):
            #_get_user去获取用户对象
            user = self._get_user(attrs)
            #去获取签发的token
            token = self._get_token(user)
            self.context['token'] = token
            self.context['user'] = user
            return attrs

        #获取用户名
        def _get_user(self,attrs):
            username = attrs.get('username')
            password = attrs.get('password')
            import re
            #判断用户名类型
            if re.match('^1[3-9][0-9]{9}$',username):#匹配usernmae是不是手机号类型
                user = models.User.objects.filter(mobilephone=username)
            elif re.match('^.*@.*$',username):
                user = models.User.objects.filter(email=username)
            else:
                user = models.User.objects.filter(username=username)
            if user:
                ret = models.User.check_password(password=password)
                if ret:
                    return True
                else:
                    raise ValidationError('密码错误')
            else:
                raise ValidationError('用户不存在')

        #获取token
        def _get_token(self,user):
            from rest_framework_jwt.serializers import jwt_payload_handler,jwt_decode_handler
            payload = jwt_payload_handler(user)#加入user得到payload
            token = jwt_decode_handler(payload)#加入patload得到token
            return token
#luffyapi\apps\user\urls.py
    # 导入路由对象
    from rest_framework.routers import SimpleRouter
    from django.urls import path, include

    from . import views

    # 实例化路由对象
    router = SimpleRouter()
    # 注册路由
    router.register('', views.LoginViewSet,'login')#不要用as_view(),需要加上方向解析,不然不会报错
    urlpatterns = [
        # 加入路由
        path('', include(router.urls))

    ]

Cookies修改页面登录状态、前台注销

1 重点,Cookies操作
	this.$cookies.set('key',value,过期时间)	#设置cookies,还有过期时间
	this.$cookies.get('key')	#获取cookies
	this.$cookies.remove(;key)	#注销cookies
2 #src\components\Login.vue 
<template>
    <div class="header">
        <div class="slogan">
            <p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
        </div>
        <div class="nav">
            <ul class="left-part">
                <li class="logo">
                    <router-link to="/">
                        <img src="../assets/img/head-logo.svg" alt="">
                    </router-link>
                </li>
                <li class="ele">
                    <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
                </li>
                <li class="ele">
                    <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">实战课</span>
                </li>
                <li class="ele">
                    <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
                </li>
            </ul>

            <div class="right-part">
                <div v-if="!username">
                    <span @click="put_login">登录</span>
                    <span class="line">|</span>
                    <span @click="put_register">注册</span>
                </div>
                <div v-else>
                    <span >{{username}}</span>
                    <span class="line">|</span>
                    <span @click="logout">注销</span>
                </div>
            </div>
            <Login v-if="is_login" @close="close_login" @go="put_register" @loginsuccess="login_success"/>
            <Register v-if="is_register" @close="close_register" @go="put_login"/>
        </div>
    </div>

</template>

<script>
    import Login from './Login'
    import Register from './Register'

    export default {
        name: "Header",
        data() {
            return {
                url_path: sessionStorage.url_path || '/',
                is_login: false,
                is_register: false,
                token: '',
                username: ''
            }
        },
        methods: {
            goPage(url_path) {
                // 传入的路由如果不是当前所在路径,就跳转
                if (this.url_path !== url_path) {
                    this.$router.push(url_path);
                }
                sessionStorage.url_path = url_path;
            },
            put_login() {
                this.is_login = true;
                this.is_register = false;
            },
            put_register() {
                this.is_login = false;
                this.is_register = true;
            },
            close_login() {
                this.is_login = false;
            },
            close_register() {
                this.is_register = false;
            },
            login_success(){
                this.username=this.$cookies.get('username')
                this.token=this.$cookies.get('token')
            },
            logout(){
                //清除cookie
                this.$cookies.remove('token')
                this.$cookies.remove('username')
                //把两个变量值为空
                this.username=''
                this.token=''
            },
        },
        created() {
            sessionStorage.url_path = this.$route.path;
            this.url_path = this.$route.path;

            //当页面一创建,我就去cookie中取token和username
            this.username = this.$cookies.get('username')   //取到就有值,取不到就为空
            this.token = this.$cookies.get('token')   //取到就有值,取不到就为空
        },
        components: {
            Login,
            Register
        }


    }
</script>

<style scoped>
    .header {
        background-color: white;
        box-shadow: 0 0 5px 0 #aaa;
    }

    .header:after {
        content: "";
        display: block;
        clear: both;
    }

    .slogan {
        background-color: #eee;
        height: 40px;
    }

    .slogan p {
        width: 1200px;
        margin: 0 auto;
        color: #aaa;
        font-size: 13px;
        line-height: 40px;
    }

    .nav {
        background-color: white;
        user-select: none;
        width: 1200px;
        margin: 0 auto;

    }

    .nav ul {
        padding: 15px 0;
        float: left;
    }

    .nav ul:after {
        clear: both;
        content: '';
        display: block;
    }

    .nav ul li {
        float: left;
    }

    .logo {
        margin-right: 20px;
    }

    .ele {
        margin: 0 20px;
    }

    .ele span {
        display: block;
        font: 15px/36px '微软雅黑';
        border-bottom: 2px solid transparent;
        cursor: pointer;
    }

    .ele span:hover {
        border-bottom-color: orange;
    }

    .ele span.active {
        color: orange;
        border-bottom-color: orange;
    }

    .right-part {
        float: right;
    }

    .right-part .line {
        margin: 0 10px;
    }

    .right-part span {
        line-height: 68px;
        cursor: pointer;
    }
</style>

手机号是否存在

#luffyapi\apps\user\views.py
    #多方式用户登录
    from luffyapi.utils.response import APIResponse
    from rest_framework.viewsets import ViewSet
    from . import serializer
    from . import models
    from rest_framework.decorators import action
    class LoginViewSet(ViewSet,):

        @action(methods=['POST'],detail=False)
        def login(self,request,*args,**kwargs):
            user_ser = serializer.UserModelSerializer(data=request.data)
            if user_ser.is_valid():#自定义了全局异常,不需要使用raise_exception=True
                #从序列化对象user_ser.context中获取token和用户名
                token = user_ser.context['token']
                username = user_ser.context['user'].username
                return APIResponse(token=token,username=username)
            else:
                return APIResponse(code=0,msg=user_ser.errors)#序列化校检失败,返回错误信息
		#判断手机号是否存在
        def check_mobilephone(self,request,*args,**kwargs):
            import re
            mobilephone = request.query_params.get('mobilephone')
            if not re.match('^[1][3-9][0-9]{9}$',mobilephone):
                return APIResponse(code=0,msg='手机号不合法')
            try:
                models.User.objects.get(mobilephone=mobilephone)
                return APIResponse(code=1)
            except:
                return APIResponse(code=0, msg='手机号不存在')

申请腾讯云短信服务

1 必需申请一个公众号地址https://mp.weixin.qq.com/
	1 进去之后点右上角立即注册,类型订阅号就行,其他类型需要域名比较复杂,然后按提示操作即可
2 到腾讯云登录https://cloud.tencent.com/,第一次使用需要实名认证,然后搜索短信,点击免费领取
3 创建签名,创建正文模板,看图1
4 创建应用,记住SDK AppID,App Key后面要用到

图1

图2

5 扣代码,用的是短信2.0 https://cloud.tencent.com/document/product/382/11672
6 可以康康帮助文档,看图1 
	API指很多web接口,基于APIView来写
    SDK指软件开发工具包,别人基于api接口,用不同语言封装的工具包,我们可以直接调用方法完成某种事,不同语言需要不同的SDK

实操腾讯云短信接口

1 配置SDK pip install qcloudsms_py

2 #luffyapi\libs\tx_sms\settings.py

    # 短信应用 SDK AppID
    appid = 1400403539  # SDK AppID 以1400开头
    # 短信应用 SDK AppKey
    appkey = "ca57467043d91ce7dfc090e9cd913acb"
    # 需要发送短信的手机号码
    phone_numbers = ["21212313123", "12345678902", "12345678903"]
    # 短信模板ID,需要在短信控制台中申请
    template_id = 669037  # NOTE: 这里的模板 ID`7839`只是示例,真实的模板 ID 需要在短信控制台中申请
    # 签名
    sms_sign = "Joab搞IT"  # NOTE: 签名参数使用的是`签名内容`,而不是`签名ID`。这里的签名"腾讯云"只是示例,真实的签名需要在短信控制台中申请
    
#luffyapi\libs\tx_sms\send.py

    from qcloudsms_py import SmsSingleSender
    from luffyapi.utils.logger import log
    from . import settings


    # 生成4位随机验证码
    def get_code():
        import random
        str_code = ''
        for i in range(4):
            str_code = str(random.randint(0, 9))  # int需要转成str
        return str_code


    # 发送验证码
    def send_str_code(phone, str_code):
        sender = SmsSingleSender(settings.appid, settings.appkey)
        params = [str_code, '3']  # 3指短信过期时间3分钟
        try:
            result = sender.send_with_param(86, phone, settings.template_id, params, sign=settings.sms_sign, extend="",
                                            ext="")
            if result.get('result') == 0:
                return True
            else:
                return False
        except Exception as e:
            log.error(f'手机号{phone}短信发送失败,错误为{str(e)}')
            
#luffyapi\libs\tx_sms\__init__.py

    from .send import get_code,send_str_code
    
#luffyapi\apps\user\views.py

    # 发送短信接口
    @action(methods=['GET'],detail=False)
    def send(self,request,*args,**kwargs):
        """
        发送验证码接口
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        #先判断是不是手机号
        import re
        from luffyapi.libs.tx_sms import get_code, send_str_code#因为tx_sms的init导入了get_code,send_str_code所以可以不用.send直接导到这两个方法
        from django.core.cache import cache#导入django缓存
        from django.conf import settings
        mobilephone = request.query_params.get('mobilephone')
        if not re.match('^1[3-9][0-9]{9}$',mobilephone):
            return APIResponse(code=0,msg='手机号不合法')#code=0表示不合法,code=1是0k
        code = get_code()
        result = send_str_code(mobilephone,code)
        #验证码存到django缓存中
        cache.set(settings.PHONE_CACHE_KEY%mobilephone,code,180)#过期时间180秒,3分钟
        if result:
            return APIResponse(code=1,msg='验证码发送成功')
        else:
            return APIResponse(code=0,msg='验证码发送失败')

短信接口频率限制

#luffyapi\utils\throttings.py

    from rest_framework.throttling import SimpleRateThrottle
    class SMSThrotting(SimpleRateThrottle):
        scope = 'sms'
        def get_cache_key(self, request, view):
            print('00')
            mobilephone = request.query_params.get('mobilephone')
            return self.cache_format%{'scope':self.scope,'ident':mobilephone}

#luffyapi\apps\user\views.py
    #短信频率限制
    from luffyapi.utils.throttings import SMSThrotting
    class SendSmsView(ViewSet):
        throttle_classes = [SMSThrotting]
        # 发送短信接口
        @action(methods=['GET'],detail=False)
        def send(self,request,*args,**kwargs):
            print('0')
            """
            发送验证码接口
            :param request:
            :param args:
            :param kwargs:
            :return:
            """
            #先判断是不是手机号
            import re
            from luffyapi.libs.tx_sms import get_code, send_str_code#因为tx_sms的init导入了get_code,send_str_code所以可以不用.send直接导到这两个方法
            from django.core.cache import cache#导入django缓存
            from django.conf import settings
            mobilephone = request.query_params.get('mobilephone')
            if not re.match('^1[3-9][0-9]{9}$',mobilephone):
                print('1')
                return APIResponse(code=0,msg='手机号不合法')#code=0表示不合法,code=1是0k
            code = get_code()
            result = send_str_code(mobilephone,code)
            #验证码存到django缓存中
            cache.set(settings.PHONE_CACHE_KEY%mobilephone,code,180)#过期时间180秒,3分钟
            print('2')
            if result:
                return APIResponse(code=1,msg='验证码发送成功')
            else:
                return APIResponse(code=0,msg='验证码发送失败')
            
#luffyapi\settings\const.py

	# 手机验证码缓存的key值
	PHONE_CACHE_KEY='sms_cache_%s'
    
#luffyapi\settings\dev.py配置短信发送频率的key

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'luffyapi.utils.exceptions.common_exception_handler',
        # 短信发送频率限制的key
        'DEFAULT_THROTTLE_RATES': {'sms': '1/m'  }# key要跟类中的scop对应
    }

验证码登录接口

#luffyapi\apps\user\views.py,LoginViewSet视图内

        #验证码登录接口
        @action(methods=['POST'],detail=False)
        def code_login(self,request,*args,**kwargs):
            ser = serializer.CodeUserSSerializer(data=request.data)
            if ser.is_valid():
                token = ser.context.get('token')
                username = ser.context.get('user').username
                return APIResponse(username=username,token=token)
            else:
                return APIResponse(code=0, msg=ser.errors)
                
#luffyapi\apps\user\serializer.py

	#验证码序列化器
    class CodeUserSSerializer(serializers.ModelSerializer):
        code = serializers.CharField()
        class Meta:
            model = models.User
            fields = ('mobilephone','code')

        #全局钩子,验证码登录成功签发token
        def validate(self, attrs):
            #_get_user去获取用户对象
            user = self._get_user(attrs)
            #去获取签发的token
            token = self._get_token(user)
            self.context['token'] = token
            self.context['user'] = user
            return attrs

        #获取用户名
        def _get_user(self,attrs):
            from django.core.cache import cache
            from django.conf import settings
            import re
            mobilephone = attrs.get('mobilephone')
            code = attrs.get('code')
            #取出原来的code
            cache_code = cache.get(settings.PHONE_CACHE_KEY%mobilephone)
            if code == '0000':#万能验证码#if code == cache_code:
                #验证码用过一次就更新为空
                cache.set(settings.PHONE_CACHE_KEY%mobilephone,'')
                user = models.User.objects.filter(mobilephone=mobilephone).first()
                #验证成功返回用户
                return user
            else:
                raise ValidationError('验证码错误,请重新输入')

        #获取token
        def _get_token(self,user):
            from rest_framework_jwt.serializers import jwt_payload_handler,jwt_decode_handler
            payload = jwt_payload_handler(user)#加入user得到payload
            token = jwt_decode_handler(payload)#加入patload得到token
            return token

前台发送验证码

#src\components\Login.vue
    <template>
        <div class="login">
            <div class="box">
                <i class="el-icon-close" @click="close_login"></i>
                <div class="content">
                    <div class="nav">
                        <span :class="{active: login_method === 'is_pwd'}"
                              @click="change_login_method('is_pwd')">密码登录</span>
                        <span :class="{active: login_method === 'is_sms'}"
                              @click="change_login_method('is_sms')">短信登录</span>
                    </div>
                    <el-form v-if="login_method === 'is_pwd'">
                        <el-input
                                placeholder="用户名/手机号/邮箱"
                                prefix-icon="el-icon-user"
                                v-model="username"
                                clearable>
                        </el-input>
                        <el-input
                                placeholder="密码"
                                prefix-icon="el-icon-key"
                                v-model="password"
                                clearable
                                show-password>
                        </el-input>
                        <el-button type="primary" @click="login_password">登录</el-button>
                    </el-form>
                    <el-form v-if="login_method === 'is_sms'">
                        <el-input
                                placeholder="手机号"
                                prefix-icon="el-icon-phone-outline"
                                v-model="mobile"
                                clearable
                                @blur="check_mobile">
                        </el-input>
                        <el-input
                                placeholder="验证码"
                                prefix-icon="el-icon-chat-line-round"
                                v-model="sms"
                                clearable>
                            <template slot="append">
                                <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                            </template>
                        </el-input>
                        <el-button type="primary" @click="code_login">登录</el-button>
                    </el-form>
                    <div class="foot">
                    </div>
                        <span @click="go_register">立即注册</span>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            name: "Login",
            data() {
                return {
                    username: '',
                    password: '',
                    mobile: '',
                    sms: '',
                    login_method: 'is_pwd',
                    sms_interval: '获取验证码',
                    is_send: false,
                }
            },
            methods: {
                close_login() {
                    this.$emit('close')
                },
                go_register() {
                    this.$emit('go')
                },
                change_login_method(method) {
                    this.login_method = method;
                },
                check_mobile() {
                    if (!this.mobile) return;
                    //字符串.match(/正则表达式/)
                    if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                        this.$message({
                            message: '手机号有误',
                            type: 'warning',
                            duration: 1000,
                            onClose: () => {
                                // this.mobile = '';
                            }
                        });
                        return false;
                    }
                    //发送axios请求
                    // this.$axios.get(this.$settings.base_url+'/user/check_telephone/telephone='+this.mobile})
                    this.$axios.get(this.$settings.base_url + '/user/check_telephone/', {params: {telephone: this.mobile}}).then(response => {
                        if (response.data.code) {
                            //手机号存在,允许发送验证码
                            this.is_send = true;
                        } else {
                            this.$message({
                                message: '手机号不存在',
                                type: 'warning',
                                duration: 1000,
                                onClose: () => {
                                    // this.mobile = '';
                                }
                            });
                        }
                    }).catch(error => {
                        console.log(error)
                    })

                },
                send_sms() {

                    if (!this.is_send) return;
                    this.is_send = false;
                    let sms_interval_time = 60;
                    this.sms_interval = "发送中...";

                    this.$axios.get(this.$settings.base_url + '/user/send/', {params: {'telephone': this.mobile}})
                        .then(response => {
                            if (response.data.code) {
                                this.$message({
                                    message: '发送验证码成功',
                                    type: 'success',
                                    duration: 1000,

                                });
                            }
                        })


                    // setInterval(()=>{},100)
                    //定时器:每隔一秒种,把数字减一,当减到小于1,按钮又能点了,显示获取验证码
                    let timer = setInterval(() => {
                        if (sms_interval_time <= 1) {
                            clearInterval(timer);  //如果小于等于1,把定时器清除
                            this.sms_interval = "获取验证码";
                            this.is_send = true; // 重新回复点击发送功能的条件
                        } else {
                            sms_interval_time -= 1;
                            this.sms_interval = `${sms_interval_time}秒后再发`;
                        }
                    }, 1000);
                },

                login_password() {
                    if (this.username && this.password) {
                        //发送请求
                        this.$axios.post(this.$settings.base_url + '/user/login/', {
                            username: this.username,
                            password: this.password


                        }).then(response => {
                            console.log(response.data)
                            //把用户信息保存到cookie中
                            // this.$cookies.set('key','value','过期时间,按s计')
                            this.$cookies.set('token', response.data.token, '7d')
                            this.$cookies.set('username', response.data.username, '7d')
                            //关闭登录窗口(子传父)
                            this.$emit('close')
                            //给父组件,Head传递一个事件,让它从cookie中取出token和username
                            this.$emit('loginsuccess')
                        }).catch(errors => {
                        })
                    } else {
                        this.$message({
                            message: '用户名或密码必须填哦',
                            type: 'warning',

                        });
                    }
                },
                code_login() {

                    if (this.mobile && this.sms) {
                        //发送请求
                        this.$axios.post(this.$settings.base_url + '/user/code_login/', {
                            telephone: this.mobile,
                            code: this.sms

                        }).then(response => {
                            console.log(response.data)
                            //把用户信息保存到cookie中
                            // this.$cookies.set('key','value','过期时间,按s计')
                            this.$cookies.set('token', response.data.token, '7d')
                            this.$cookies.set('username', response.data.username, '7d')
                            //关闭登录窗口(子传父)
                            this.$emit('close')
                            //给父组件,Head传递一个事件,让它从cookie中取出token和username
                            this.$emit('loginsuccess')
                        }).catch(errors => {
                        })
                    } else {
                        this.$message({
                            message: '手机号或验证码必填',
                            type: 'warning',

                        });
                    }

                },
            }
        }
    </script>

    <style scoped>
        .login {
            width: 100vw;
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 10;
            background-color: rgba(0, 0, 0, 0.3);
        }

        .box {
            width: 400px;
            height: 420px;
            background-color: white;
            border-radius: 10px;
            position: relative;
            top: calc(50vh - 210px);
            left: calc(50vw - 200px);
        }

        .el-icon-close {
            position: absolute;
            font-weight: bold;
            font-size: 20px;
            top: 10px;
            right: 10px;
            cursor: pointer;
        }

        .el-icon-close:hover {
            color: darkred;
        }

        .content {
            position: absolute;
            top: 40px;
            width: 280px;
            left: 60px;
        }

        .nav {
            font-size: 20px;
            height: 38px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span {
            margin: 0 20px 0 35px;
            color: darkgrey;
            user-select: none;
            cursor: pointer;
            padding-bottom: 10px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span.active {
            color: black;
            border-bottom: 3px solid black;
            padding-bottom: 9px;
        }

        .el-input, .el-button {
            margin-top: 40px;
        }

        .el-button {
            width: 100%;
            font-size: 18px;
        }

        .foot > span {
            float: right;
            margin-top: 20px;
            color: orange;
            cursor: pointer;
        }

        .sms {
            color: orange;
            cursor: pointer;
            display: inline-block;
            width: 70px;
            text-align: center;
            user-select: none;
        }
    </style>

后台注册接口

# luffyapi\apps\user\urls.py

    # 导入路由对象
    from rest_framework.routers import SimpleRouter
    from django.urls import path, include

    from . import views

    # 实例化路由对象
    router = SimpleRouter()
    # 注册路由
    router.register('', views.LoginViewSet,'login')#不要用as_view(),需要加上反向解析,不然不会报错
    router.register('', views.SendSmsView,'send')#不要用as_view(),需要加上反向解析,不然不会报错
    router.register('register', views.RegisterGenericViewSet,'register')#用户注册接口
    urlpatterns = [
        # 加入路由
        path('', include(router.urls))
    ]

#luffyapi\apps\user\views.py

    #注册接口
    from rest_framework.viewsets import GenericViewSet
    from rest_framework.mixins import CreateModelMixin
    class RegisterGenericViewSet(GenericViewSet,CreateModelMixin):
        queryset = models.User.objects.all()
        serializer_class = serializer.RegisterModelSerializer
        def create(self,request,*args,**kwargs):
            response = super().create(request,*args,**kwargs)
            username = response.data.get('username')
            return APIResponse(code=1,msg='注册成功',username=username)

# luffyapi\apps\user\serializer.py

    #注册序列化器
    from django.core.cache import cache
    from django.conf import settings
    class RegisterModelSerializer(serializers.ModelSerializer):
        code = serializers.CharField(max_length=4,min_length=4,write_only=True)
        class Meta:
            model = models.User
            fields = ('username', 'telephone', 'code', 'password')
            extra_kwargs = {
                'password': {'write_only': True},
                'username': {'read_obly': True},
            }

        def validate(self, attrs):
            telephone = attrs.get('telephone')
            code = attrs.get('code')
            cache_code = cache.get(settings.PHONE_CACHE_KEY % telephone)
            if code == cache_code:
                import re
                if re.match('^[1][3-9][0-9]{9}$',telephone):
                    attrs['username'] = telephone
                    attrs.pop('code')
                    return attrs
                else:
                    raise ValidationError('手机不合法')
            else:
                raise ValidationError('验证码有误')

        #重新create方法
        def create(self, validated_data):
            user = models.User.objects.create_user(**validated_data)
            return user

前台注册接口

#src\components\Register.vue
    <template>
        <div class="register">
            <div class="box">
                <i class="el-icon-close" @click="close_register"></i>
                <div class="content">
                    <div class="nav">
                        <span class="active">新用户注册</span>
                    </div>
                    <el-form>
                        <el-input
                                placeholder="手机号"
                                prefix-icon="el-icon-phone-outline"
                                v-model="mobile"
                                clearable
                                @blur="check_mobile">
                        </el-input>
                        <el-input
                                placeholder="密码"
                                prefix-icon="el-icon-key"
                                v-model="password"
                                clearable
                                show-password>
                        </el-input>
                        <el-input
                                placeholder="验证码"
                                prefix-icon="el-icon-chat-line-round"
                                v-model="sms"
                                clearable>
                            <template slot="append">
                                <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                            </template>
                        </el-input>
                        <el-button type="primary" @click="register">注册</el-button>
                    </el-form>
                    <div class="foot">
                        <span @click="go_login">立即登录</span>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            name: "Register",
            data() {
                return {
                    mobile: '',
                    password: '',
                    sms: '',
                    sms_interval: '获取验证码',
                    is_send: false,
                }
            },
            methods: {
                close_register() {
                    this.$emit('close', false)
                },
                go_login() {
                    this.$emit('go')
                },
                check_mobile() {
                    if (!this.mobile) return;
                    //字符串.match(/正则表达式/)
                    if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                        this.$message({
                            message: '手机号有误',
                            type: 'warning',
                            duration: 1000,
                            onClose: () => {
                                this.mobile = '';
                            }
                        });
                        return false;
                    }
                    this.$axios.get(this.$settings.base_url + '/user/check_telephone/', {params: {telephone: this.mobile}}).then(response => {
                        if (response.data.code) {
                            this.$message({
                                message: '您已经注册过了,快去登录把',
                                type: 'warning',
                                duration: 1000,
                                onClose: () => {
                                    this.go_login()
                                }
                            });

                        } else {
                            this.is_send = true;
                            this.$message({
                                message: '该用户没有注册过,欢迎注册我们的平台',
                                type: 'success',
                                duration: 1000,
                            });
                        }
                    }).catch(error => {
                        console.log(error)
                    })

                },
                send_sms() {

                    if (!this.is_send) return;
                    this.is_send = false;
                    let sms_interval_time = 60;
                    this.sms_interval = "发送中...";

                    this.$axios.get(this.$settings.base_url + '/user/send/', {params: {'telephone': this.mobile}})
                        .then(response => {
                            if (response.data.code) {
                                this.$message({
                                    message: '发送验证码成功',
                                    type: 'success',
                                    duration: 1000,

                                });
                            }
                        })


                    // setInterval(()=>{},100)
                    //定时器:每隔一秒种,把数字减一,当减到小于1,按钮又能点了,显示获取验证码
                    let timer = setInterval(() => {
                        if (sms_interval_time <= 1) {
                            clearInterval(timer);  //如果小于等于1,把定时器清除
                            this.sms_interval = "获取验证码";
                            this.is_send = true; // 重新回复点击发送功能的条件
                        } else {
                            sms_interval_time -= 1;
                            this.sms_interval = `${sms_interval_time}秒后再发`;
                        }
                    }, 1000);
                },
                register() {
                    if (this.mobile && this.sms && this.password) {
                        this.$axios.post(this.$settings.base_url + '/user/register/', {
                            telephone: this.mobile,
                            code: this.sms,
                            password: this.password
                        }).then(response => {
                            if (response.data.code) {
                                //注册成功,来个提示,跳转到登录
                                this.$message({
                                    message: '注册成功',
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.go_login()
                                    }
                                });
                            } else {
                                this.$message({
                                    message: '未知错误',
                                    type: 'error',
                                    duration: 1000,
                                    onClose: () => {
                                        this.mobile = ''
                                        this.sms = ''
                                        this.password = ''
                                    }
                                });
                            }
                        })
                    } else {
                        this.$message({
                            message: '你有没填的信息',
                            type: 'error',
                            duration: 1000,
                        });
                    }
                },
            }
        }
    </script>

    <style scoped>
        .register {
            width: 100vw;
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 10;
            background-color: rgba(0, 0, 0, 0.3);
        }

        .box {
            width: 400px;
            height: 480px;
            background-color: white;
            border-radius: 10px;
            position: relative;
            top: calc(50vh - 240px);
            left: calc(50vw - 200px);
        }

        .el-icon-close {
            position: absolute;
            font-weight: bold;
            font-size: 20px;
            top: 10px;
            right: 10px;
            cursor: pointer;
        }

        .el-icon-close:hover {
            color: darkred;
        }

        .content {
            position: absolute;
            top: 40px;
            width: 280px;
            left: 60px;
        }

        .nav {
            font-size: 20px;
            height: 38px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span {
            margin-left: 90px;
            color: darkgrey;
            user-select: none;
            cursor: pointer;
            padding-bottom: 10px;
            border-bottom: 2px solid darkgrey;
        }

        .nav > span.active {
            color: black;
            border-bottom: 3px solid black;
            padding-bottom: 9px;
        }

        .el-input, .el-button {
            margin-top: 40px;
        }

        .el-button {
            width: 100%;
            font-size: 18px;
        }

        .foot > span {
            float: right;
            margin-top: 20px;
            color: orange;
            cursor: pointer;
        }

        .sms {
            color: orange;
            cursor: pointer;
            display: inline-block;
            width: 70px;
            text-align: center;
            user-select: none;
        }
    </style>

Redis使用

Redis使用

安装

Python操作Redis普通连接

1 pip install redis
#简单使用
    from redis import Redis
    #获取redis连接
    conn = Redis(host='127.0.0.1',port=6379)
    #key取值
    ret = conn.get('name')

    print(ret)#b'alex'

Python操作Redis连接池

#redis_pool\redis_pool.py

    import redis
    #连接池对象,最大连接数100
    POOL = redis.ConnectionPool(host='127.0.0.1',port=6379,max_connections=100)

#redis_pool\redis_pool.py  

    import redis
    from redis_pool import POOL
    #执行这句话就是从连接池拿出一个连接
    r = redis.Redis(connection_pool=POOL)

    ret = r.get('name')

    print(ret)#b'alex'

Redis数据类型

string(字符串)
list(列表)
set(集合)
zset(有序集合)
hash(哈希)
String(字符串)操作
string在内存中按照一个name一个value来存储,看图1

#加*表示重点
set(name, value, ex=None, px=None, nx=False, xx=False)*
#设置值,不存在则创建,存在则修改,
参数:
	ex过期时间秒
    px过期时间毫秒
    nx为True时,key不存在时,才会执行,key存在则不执行操作
    xx为True时,key不存在时,不会执行操作,key存在才会执行
    
setnx(name, value)
#设置值,key不存在,才会执行,存在不会执行操作

setex(name, value, time)
#设置值,参数time过期时间数字秒,或timedelta对象

psetex(name, time_ms, value)
#设置值,参数time_ms过期时间数字毫秒,或timedelta对象

mset(*args,**kwargs)*
#批量设置值,如
	mset(k1='v1',k2='v2')
    mset({'k1':'v1','k2':'v2'})

get(key)*    
#获取值

mget(keys,*args)*
#批量获取,如
	mget('k1','k2')
    mget(['k1','k2'])

getset(name, value)*
#设置值并获取原来的值

getrange(key, start, end)
#获取子序列,根据字节获取,非字符,参数:
	start开始位置的索引(前闭后闭)#汉字占3个字节
    end结束位置的的索引(前闭后闭)

setrange(name, offset, value)
#修改字符串内容,从指定索引向后修改,新值比原值长则向后添加,参数:
	0ffset开始修改字符串的索引,汉字占3个字节
    value指要设置的指

setbit(name, offset, value)
#对key对应的值的二进制(010101001)进行操作,参数:
	offset开始位的索引,需要将值转成二进制(1字节等于8位二进制)索引
    value值只能是0或1
    
getbit(name, offset)
# 获取key对应值开始索引的二进制的值0或1

bitcount(key, start=None, end=None)
#获取key对应值的二进制的值中的1的个数,参数:
	strat二进制起始位置
    end二进制结束位置
   
bitop(operation, dest, *keys)
#获取多个值,并将值做位运算,将最后的值保存至新的key对应的值,参数:
	operation可以是AND(并)、OR(或)、NOT(非)、XOR(异或)
	dest新的key名
    *keys要查找的key
	如:
    conn.bitop('AND','name_1','name1','name2','name3')
    #获取key,'name1','name2','name3'对应的值,做位运算(并集),然后将结果保存到name_1对应的值中

strlen(name)
#返回key对应值的字节长度(汉字三个字节)

incr(self, name, amount=1)#incrby(self, name, amount=1)*
#自增key对应的值,当key不存在时,则创建key对应值是amount的值,否则则自增,参数:
	amount自增数,必须是整数

incrbyfloat(self, name, amount=1.0)
#自增key对应的值,key不存在时,则创建key=amount,否则自增,参数:
	amount自增数,必须是浮点型

decr(self, name, amount=1)*
#自减key对应的值,key不存在时,则创建key=amount,否则则自减,参数:
	amount自减数,必须是整数
    
append(key, value)*
#在key对应的值后面追加内容,参数:
	value要追加的字符串

图1

Hash(哈希)操作
#Hash在内存中的存储格式,value值必须是字符串类型,看图1

#加*表示重点
hset(name, key, value)*
#name对应的hash中设置一个键值对,不存在创建,存在则修改,参数:
	name指redis存储hash的name
    key指name对应的hash的key
    value指name对应的hash的value
    
hmset(name, mapping)*
#在name对应的hash中批量设置键值对,参数:
	mapping是字典,比如{'k1':'v1','k2','v2'}
    
hget(name,key)*
#在name对应的hash中获取根据key获取value值

hmget(name, keys, *args)*
#在name对应的hash中获取多个key对应的值。参数:
	keys要获取key的集合,如['k1','k2','k3']
    *args要获取的key,如k1,k2,k3
    实例:
        hmget('name',['k1','k2','k3'])
         hmget('name',k1,k2,k3)

hgetall(name)
#获取name对应的hash的所有键值

hlen(name)
#获取name对应的hash的键值对的个数

hkeys(name)
#获取name对应的hash的所有的key的值

hvals(name)
#获取name对应的hash的所有的value的值

hexists(name, key)
#检查name对应的hash是否存在key

hdel(name,*keys)
#将name对应的hash指定的key的键值对删除

hincrby(name, key, amount=1)*
#自增name对应的hash中指定的key的值,不存在则创建key=amount,参数:
	amount自增数,必须是整数
    
    
hincrbyfloat(name, key, amount=1.0)
#自增name对应的hash中指定key的值,不存在则创建key=amount,参数:
	amount自增数,必须是浮点数
    
    
hscan(name, cursor=0, match=None, count=None)
#增量式迭代获取,对于数据大的非常有用,hscan可以实现分片式获取数据,并非一次性将数据全部获取,导致内存被撑爆,参数:
	cursor游标,基于游标分批获取数据
    match匹配指定key,默认None,表示所有的key
    count每次分片最少获取个数,默认None表示采用redis默认分片个数
    
hscan_iter(name, match=None, count=None)
#利用yield封装hscan创建生成器,实现分批去redis中获取数据,参数:
	match匹配指定key,默认Nnoe,表示所有的key
    count每次分片最少获取个数,默认None表示采用redis的默认分片个数
    实例:for item in r.hscan_iter('xx'):
        	print item    
            
# 区分hgetall和hscan_iter            

List(列表)操作
#List在内存中按照一个name对应一个List来存储,看图1

#加*表示重点
lpush(name,values)*
#在name对应的list中添加元素,每个新的元素都添加到列表的最左边,如:
	r.lpush('oo', 11,22,33)
    结果为: 33,22,11
    # 扩展:
        rpush(name, values) 表示从右向左操作

lpushx(name,value)
#在name对应的list中添加元素,只有name存在时,值添加到list最左边
	扩展:rpushx(name, value) 表示从右向左操作
    
llen(name)*
#name对应的list元素的个数

linsert(name, where, refvalue, value))
#在name对应的list的某一个值前面或后面插入一个值,参数:
	where可以式BEFORE或AFTER(小写也可以)
    refvalue标杆值,在它前后插入数据,如果存在多个标杆值,以找到的第一个为准
    value要插入的值
    
r.lset(name, index, value)
#对name对应的list的某一个索引位置重新赋值,参数:
	index指需要重新赋值的索引位置
    value要设置的值
    
r.lrem(name, value, num)
#在name对应的list中删除指定的值,参数:
	value要删除的值
    num:
    	num=0表示删除该list中所有指定值
        num=2表示从前到后删除两个
        num=-2表示从后到前删除两个
        
lpop(name)*
#在name对应的list左侧获取第一个元素并在list中移除,返回值则是该元素
	扩展:rpop(name) 表示从右向左操作
    
lindex(name, index)
#在name对应的list中根据索引获取list元素

lrange(name, start, end)*
#在name对应的list分片获取数据,参数:
	start开始的索引位置
    end结束的索引位置
    
ltrim(name, start, end)
#在name对应的list中移除没有在start-end索引之间的值,参数:
	start开始的索引位置
    end结束的索引位置
    
rpoplpush(src, dst)
#从一个列表取出最右边的元素,提示添加到另一个list的最左边,参数:
	src要获取数据的list的name
    dst要添加数据的list的name
    
blpop(keys, timeout)*
#将多个list排列,按照从左到右去pop对应list的元素,参数:
	keys是个集合,要pop元素的集合
    timeout超时时间,当元素所有list的元素获取玩之后,阻塞等待list内数据局的时间秒,0表示医院阻塞,
    扩展:r.brpop(keys, timeout),从右向左获取数据,应用场景:爬虫实现简单分布式:多个url放到列表里,往里不停放URL,程序循环取值,但是只能一台机器运行取值,可以把url放到redis中,多台机器从redis中取值,爬取数据,实现简单分布式

brpoplpush(src, dst, timeout=0)    
#从一个列表的右侧移除一个元素,并将其添加到另一个list的左侧,参数:
	src取出并要移除元素的list的name
    dst要插入元素的list的name
    timeout当src对应的list中没有数据时,阻塞等待其有数据的超时时间秒,0表示医院阻塞
 
自定义增量迭代
# 由于redis类库中没有提供对列表元素的增量迭代,如果想要循环name对应的列表的所有元素,那么就需要:
    # 1、获取name对应的所有列表
    # 2、循环列表
# 但是,如果列表非常大,那么就有可能在第一步时就将程序的内容撑爆,所有有必要自定义一个增量迭代的功能:
import redis
conn=redis.Redis(host='127.0.0.1',port=6379)
# conn.lpush('test',*[1,2,3,4,45,5,6,7,7,8,43,5,6,768,89,9,65,4,23,54,6757,8,68])
# conn.flushall()
def scan_list(name,count=2):
    index=0
    while True:
        data_list=conn.lrange(name,index,count+index-1)
        if not data_list:
            return
        index+=count
        for item in data_list:
            yield item
print(conn.lrange('test',0,100))
for item in scan_list('test',5):
    print('---')
    print(item)

Set(集合)操作
其他操作
delete(*names)
#删除redis中任意数据类型

exists(name)
#检查redis的name是否存在

keys(pattern='*')
#根据模型获取redis的name,其他参数:
	KEYS * 匹配数据库中所有 key 。
    KEYS h?llo 匹配 hello , hallo 和 hxllo 等。
    KEYS h*llo 匹配 hllo 和 heeeeello 等。
    KEYS h[ae]llo 匹配 hello 和 hallo ,不匹配 hillo 
	
expire(name ,time)
#为某个redis的某个name设置超时时间

rename(src, dst)
#对redis的name重命名

move(name, db)
#将redis的某个值移动到指定的db下

randomkey()
#随机获取一个redis的name,不删除

type(name)
#获取nmae对应值的类型

scan(cursor=0, match=None, count=None)
scan_iter(match=None, count=None)
#同字符串操作,用于增量迭代获取key

管道

如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。#redis默认在执行每次请求都会创建(连接申请连接池)和断开(归还连接池)一次性操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作(要么全部成功,要么全部失败)。

#test.py
    import redis

    pool = redis.ConnectionPool(host='10.211.55.4', port=6379)

    r = redis.Redis(connection_pool=pool)

    # pipe = r.pipeline(transaction=False)
    pipe = r.pipeline(transaction=True)
    pipe.multi()
    pipe.set('name', 'alex')
    pipe.set('role', 'sb')

    pipe.execute()

Django使用Redis

#方式一,通用方式
    #utils\redis_pool.py
    
		import redis
        #POOL连接池,max_connections=100指最大连接数是100
        POOL = redis.ConnectionPool(host='127.0.0.1',port=6379,max_connections=100)
        
	#app01\views.py
    
        import redis
        from utils.redis_pool import POOL
        from django.shortcuts import render, HttpResponse
        def index(request):
            conn = redis.Redis(connection_pool=POOL)
            conn.set('hobby','sleep')
            return HttpResponse('设置成功')

        def order(request):
            conn = redis.Redis(connection_pool=POOL)
            ret = conn.get('hobby')
            print(ret)
            return HttpResponse('获取成功')
        
#方式二,安装django-redis模块
	pip install django-redis
    
    #settings.py配置
    
        CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "CONNECTION_POOL_KWARGS": {"max_connections": 100}
                # "PASSWORD": "123",
            }
        }
    }
	#views.py
    from django_redis import get_redis_connection
    conn = get_redis_connection('default')
    print(conn.hgetall('xxx'))

接口缓存

#luffyapi\apps\home\views.py,BannerView类内    
    def banner_list(self,request,*args,**kwargs):
        banner_list = cache.get('banner_list')
        if not banner_list:
            #缓存没有去数据拿
            response = super().list(request,*args,**kwargs)
            #加到缓存
            cache.set('banner_list',response.data,60*60*24)#banner_list一天过期
        return Response(data=banner_list)	

Celery(异步任务框架)

#了解
    Celery 官网:http://www.celeryproject.org/
    Celery 官方文档英文版:http://docs.celeryproject.org/en/latest/index.html
    Celery 官方文档中文版:http://docs.jinkan.org/docs/celery/

    介绍: Celery是一个简单、灵活、可靠处理大量消息的分布式系统,专注于实时处理的异步入任务队列,同时支持任务调度   

    Celery is a project with minimal funding, so we don’t support Microsoft Windows. Please don’t open any issues related to that platform.

Celery使用

#可以执行异步、延时、定时任务

#安装 pip install celery

基本机构

#t_redis_pool\celery_1\celery_task.py

    from celery import Celery
    broker = 'redis://127.0.0.1:6379/1'#brokey任务队列
    backend = 'redis://127.0.0.1:6379/2'#结构存储,执行完的结果存在这

    app = Celery(__name__,broker=broker,backend=backend)

    #添加任务,使用装饰器@app.task
    @app.task
    def add(x,y):
        print(x,y)
        return x*y

#t_redis_pool\celery_1\celery_add.py

    from celery_task import add
    ret = add.delay(3,8)#向add函数添加一个任务

#t_redis_pool\celery_1\result1.py

    from celery_task import app
    from celery.result import AsyncResult

    id = '3e397fd7-e0c1-4c5c-999c-2655a96793bb'
    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_task,包里面必须有个celery.py
#celery_task\celery.py
    from celery import Celery

    broker = 'redis://127.0.0.1:6379/1'#broker任务队列
    backend = 'redis://127.0.0.1:6379/2'#结构存储,执行完的结果在这

    app = Celery(__name__,broker=broker,backend=backend,include=['celery_task.task1','celery_task.task2'])

#celery_task\task1.py

    from .celery import app
    @app.task
    def mutile(x,y):
        print(x,y)
        return x*y
    
#celery_task\task2.py

    from .celery import app

    @app.task
    def add(x, y):
        print(x, y)
        return x + y
    
#celery_task\test.py提交任务

    from celery_task.task1 import mutile
    from celery_task.task2 import add

    ret = add.delay(6,9)
    print(ret)
    
    ret = mutile(9,8)#上面的ret不用注释,可以提交多个
    print(ret)


    #提交延时任务
    from datetime import datetime, timedelta

    #需要utc时间
    eta = datetime.utcnow() + timedelta(seconds=10)
    ret = add.apply_async(args=(240,50),eta=eta)

    print(ret)
    
#查看任务结果

	from celery_task import app
    from celery.result import AsyncResult
    id = '3e397fd7-e0c1-4c5c-999c-2655a96793bb'
    if __name__ == '__main__':
        async = AsyncResult(id=id, app=app)
        if async.successful():
            result = async.get()
            print(result)
        elif async.failed():
            print('任务失败')
        elif async.status == 'PENDING':
            print('任务等待中被执行')
        elif async.status == 'RETRY':
            print('任务异常后正在重试')
        elif async.status == 'STARTED':
            print('任务已经开始被执行')    
    
#执行定时任务
#celery_task\celery.py

    from celery import Celery

    broker = 'redis://127.0.0.1:6379/1'  # broker任务队列
    backend = 'redis://127.0.0.1:6379/2'  # 结构存储,执行完的结果存在这
    app = Celery(__name__, broker=broker, backend=backend, include=['celery_task.task1', 'celery_task.task2'])
    # 执行定时任务
    # 时区
    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': {
            'task': 'celery_task.task1.add',
            # 'schedule': timedelta(seconds=3),
            'schedule': crontab(hour=8, day_of_week=1),  # 每周一早八点
            'args': (300, 150),
        }
    }
#pycharm终端执行

	#启动worker,等待任务
	-celery worker -A celery_task -l info -P eventlet
    #启动beat,提交任务,如果报错删除产生的文件
	-celery beat -A celery_task -l info

课程表结构分析、优化

#  ForeignKey的字段:
	-related_name 反向操作时,使用的字段名,用于代替原反向查询时的'表名_set'。
    -related_query_name :反向查询操作时,使用的连接前缀,用于替换表名。
    
################1   course/models.py
from luffyapi.utils.models import BaseModel
# 实际路飞课程相关表,以免费课为例
class CourseCategory(BaseModel):
    """分类
    python,linux,go, 网络安全
    跟课程是一对多的关系

    """
    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="课程状态")
    price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价", default=0)

    # 优化字段
    students = models.IntegerField(verbose_name="学习人数", default=0)
    sections = models.IntegerField(verbose_name="总课时数量", default=0)
    pub_sections = models.IntegerField(verbose_name="课时更新数量", default=0)

    # 关联字段
    teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授课老师",db_constraint=False)
    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 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



class CourseChapter(BaseModel):
    """章节
    章节跟课程是一(课程)对多(章节多)
    """
    course = models.ForeignKey("Course", related_name='coursechapters', on_delete=models.CASCADE, verbose_name="课程名称",db_constraint=False)
    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="课程章节",db_constraint=False)
    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)
    
    
################2 utils/models/BaseModel
from django.db import models
# 后期课程表,轮播图表,都会用到这些字段

class BaseModel(models.Model):
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')
    is_show = models.BooleanField(default=True, verbose_name='是否展示')
    # 修改成这样
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time  = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')
    orders = models.IntegerField()
    class Meta:
        abstract=True  # 一定不要忘了


创建应用python ../../manage.py startapp course



################3 数据迁移
python manage.py makemigrations
python manage.py migrate

课程测试数据准备


-- 老师表
-- 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, '2019-07-14 13:44:19.661327', '2019-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, '2019-07-14 13:45:25.092902', '2019-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, '2019-07-14 13:46:21.997846', '2019-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, '2019-07-14 13:40:58.690413', '2019-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, '2019-07-14 13:41:08.249735', '2019-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, '2019-07-14 13:54:33.095201', '2019-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, '2019-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, '2019-07-14 13:56:05.051103', '2019-07-14 13:56:05.051142', 'Python项目实战', 'courses/mjj_python.png', 0, '', 1, '2019-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, '2019-07-14 13:57:21.190053', '2019-07-14 13:57:21.190095', 'Linux系统基础5周入门精讲', 'courses/lyy_linux.png', 0, '', 0, '2019-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, '2019-07-14 13:58:34.867005', '2019-07-14 14:00:58.276541', 1, '计算机原理', '', '2019-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, '2019-07-14 13:58:48.051543', '2019-07-14 14:01:22.024206', 2, '环境搭建', '', '2019-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, '2019-07-14 13:59:09.878183', '2019-07-14 14:01:40.048608', 1, '项目创建', '', '2019-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, '2019-07-14 13:59:37.448626', '2019-07-14 14:01:58.709652', 1, 'Linux环境创建', '', '2019-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, '2019-07-14 14:02:33.779098', '2019-07-14 14:02:33.779135', '计算机原理上', 1, 2, NULL, NULL, '2019-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, '2019-07-14 14:02:56.657134', '2019-07-14 14:02:56.657173', '计算机原理下', 2, 2, NULL, NULL, '2019-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, '2019-07-14 14:03:20.493324', '2019-07-14 14:03:52.329394', '环境搭建上', 1, 2, NULL, NULL, '2019-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, '2019-07-14 14:03:36.472742', '2019-07-14 14:03:36.472779', '环境搭建下', 2, 2, NULL, NULL, '2019-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, '2019-07-14 14:04:19.338153', '2019-07-14 14:04:19.338192', 'web项目的创建', 1, 2, NULL, NULL, '2019-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, '2019-07-14 14:04:52.895855', '2019-07-14 14:04:52.895890', 'Linux的环境搭建', 1, 2, NULL, NULL, '2019-07-14 14:04:52.895942', 1, 4);

课程主页页面

# 不要忘了注册路由

# FreeCourse.vue
<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">筛&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;选:</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/Head"
    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>

课程分类群查接口

# 路由
router = SimpleRouter()
router.register('categories', views.CourseCategoryView, 'categories')
router.register('free', views.CouresView, 'free')
urlpatterns = [
    path('', include(router.urls)),
]

# 视图views.py
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from . import models
from . import serializer
class CourseCategoryView(GenericViewSet,ListModelMixin):
    queryset = models.CourseCategory.objects.filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = serializer.CourseCategorySerializer

# 序列化类
from rest_framework import serializers
from . import models
class CourseCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model=models.CourseCategory
        fields=['id','name']

课程群查接口

# 路由
router = SimpleRouter()
router.register('categories', views.CourseCategoryView, 'categories')
router.register('free', views.CouresView, 'free')
urlpatterns = [
    path('', include(router.urls)),
]

# 视图 views.py
from .paginations import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter,SearchFilter
from .filters import MyFilter
class CouresView(GenericViewSet,ListModelMixin,RetrieveModelMixin):
    queryset = models.Course.objects.filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = serializer.CourseModelSerializer
    pagination_class = PageNumberPagination
    filter_backends=[DjangoFilterBackend,OrderingFilter]
    ordering_fields=['id', 'price', 'students']

    filter_fields=['course_category','students']
    
 ###serializer
from rest_framework import serializers
from . import models


class CourseCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CourseCategory
        fields = ['id', 'name']


class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Teacher
        fields = ('name', 'role_name', 'title', 'signature', 'image', 'brief')


class CourseModelSerializer(serializers.ModelSerializer):
    # 子序列化的方式
    teacher = TeacherSerializer()

    class Meta:
        model = models.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',
        ]
 # models.py
class Course(BaseModel):
	...
    @property
    def course_type_name(self):
        return self.get_course_type_display()
    @property
    def level_name(self):
        return self.get_level_display()
    @property
    def status_name(self):
        return self.get_status_display()

    @property
    def section_list(self):
        ll=[]
        # 根据课程取出所有章节(正向查询,字段名.all())
        course_chapter_list=self.coursechapters.all()
        for course_chapter in course_chapter_list:
            # 通过章节对象,取到章节下所有的课时(反向查询)
            # course_chapter.表名小写_set.all() 现在变成了course_chapter.coursesections.all()
            course_sections_list=course_chapter.coursesections.all()
            for course_section in course_sections_list:
                ll.append({
                    'name': course_section.name,
                    'section_link': course_section.section_link,
                    'duration': course_section.duration,
                    'free_trail': course_section.free_trail,
                })
                if len(ll)>=4:
                    return ll

        return ll


    
class Teacher(BaseModel):
	...
    def role_name(self):
        # 返回角色的中文
        return self.get_role_display()

搜索组件和过滤

'''
排序:
按id正序倒叙排序,按price正序倒叙排列
使用:http://127.0.0.1:8000/course/free/?ordering=-id
配置类:
    filter_backends=[OrderingFilter]
配置字段:
    ordering_fields=['id','price']
    
    
内置过滤:
使用:http://127.0.0.1:8000/course/free/?search=39
按照price过滤(表自有的字段直接过滤)
配置类:
    filter_backends=[SearchFilter]
配置字段:
    search_fields=['price']
    
扩展:django-filter
安装:
支持自由字段的过滤还支持外键字段的过滤
http://127.0.0.1:8000/course/free/?course_category=1   # 过滤分类为1 (python的所有课程)
配置类:
    filter_backends=[DjangoFilterBackend]
配置字段:
    filter_fields=['course_category']


'''

自定义过滤类

# filters.py
# 自定义过滤规则
from rest_framework.filters import BaseFilterBackend

class MyFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        # 真正的过滤规则
        # params=request.GET.get('teacher')
        # queryset.filter('''''')
        return queryset[:1]
 
# 使用:在视图类中配置
filter_backends=[DjangoFilterBackend,OrderingFilter,MyFilter]

区间过滤

#使用django-filter实现过滤
#luffyapi\apps\course\filters.py

    from django_filters import FilterSet,filters
    from rest_framework.filters import BaseFilterBackend

    from . import models
    #区间过滤
    class CourseFilterSet(FilterSet):
        min_price = filters.NumberFilter(field_name='price',lookup_expr='gt')
        max_price = filters.NumberFilter(field_name='price',lookup_expr='lt')
        class Meta:
            model = models.Course
            fields = ('course_category')

    #自定义规则过滤
    class MyFilter(BaseFilterBackend):
        def filter_queryset(self, request, queryset, view):
            return queryset[:1]

#luffyapi\apps\course\views.py,视图中配置filter_backends=[DjangoFilterBackend],filter_class = CourseFilterSet

    #课程群查接口
    # from .paginations import PageNumberPagination
    from django_filters.rest_framework import DjangoFilterBackend
    from rest_framework.filters import OrderingFilter,SearchFilter
    from .filters import MyFilter
    #导入区间过滤
    from .filters import CourseFilterSet
    class CouresView(GenericViewSet,ListModelMixin,RetrieveModelMixin):
        queryset = models.Course.objects.filter(is_delete=False,is_show=True).order_by('orders')
        serializer_class = serializer.CourseModelSerializer
        # pagination_class = PageNumberPagination

        filter_backends=[DjangoFilterBackend,OrderingFilter]
        ordering_fields=['id', 'price', 'students']


        filter_fields=['course_category','students']


前端主页详情页

<template>
    <div class="course">
        <Header></Header>
        <div class="main">
            <!-- 筛选条件 -->
            <div class="condition">
                <ul class="cate-list">
                    <li class="title">课程分类:</li>
                    <li :class="filter.course_category==0?'this':''" @click="filter.course_category=0">全部</li>
                    <li :class="filter.course_category==category.id?'this':''" v-for="category in category_list"
                        @click="filter.course_category=category.id" :key="category.name">{{category.name}}
                    </li>
                </ul>

                <div class="ordering">
                    <ul>
                        <li class="title">筛&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;选:</li>
                        <li class="default" :class="(filter.ordering=='id' || filter.ordering=='-id')?'this':''"
                            @click="filter.ordering='-id'">默认
                        </li>
                        <li class="hot" :class="(filter.ordering=='students' || filter.ordering=='-students')?'this':''"
                            @click="filter.ordering=(filter.ordering=='-students'?'students':'-students')">人气
                        </li>
                        <li class="price"
                            :class="filter.ordering=='price'?'price_up this':(filter.ordering=='-price'?'price_down this':'')"
                            @click="filter.ordering=(filter.ordering=='-price'?'price':'-price')">价格
                        </li>
                    </ul>
                    <p class="condition-result">共{{course_total}}个课程</p>
                </div>

            </div>
            <!-- 课程列表 -->
            <div class="course-list">
                <div class="course-item" v-for="course in course_list" :key="course.name">
                    <div class="course-image">
                        <img :src="course.course_img" alt="">
                    </div>
                    <div class="course-info">
                        <h3>
                            <router-link :to="'/free/detail/'+course.id">{{course.name}}</router-link>
                            <span><img src="@/assets/img/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3>
                        <p class="teather-info">
                            {{course.teacher.name}} {{course.teacher.title}} {{course.teacher.signature}}
                            <span v-if="course.sections>course.pub_sections">共{{course.sections}}课时/已更新{{course.pub_sections}}课时</span>
                            <span v-else>共{{course.sections}}课时/更新完成</span>
                        </p>
                        <ul class="section-list">
                            <li v-for="(section, key) in course.section_list" :key="section.name"><span
                                    class="section-title">0{{key+1}}  |  {{section.name}}</span>
                                <span class="free" v-if="section.free_trail">免费</span></li>
                        </ul>
                        <div class="pay-box">
                            <div v-if="course.discount_type">
                                <span class="discount-type">{{course.discount_type}}</span>
                                <span class="discount-price">¥{{course.real_price}}元</span>
                                <span class="original-price">原价:{{course.price}}元</span>
                            </div>
                            <span v-else class="discount-price">¥{{course.price}}元</span>
                            <span class="buy-now">立即购买</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="course_pagination block">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page.sync="filter.page"
                        :page-sizes="[2, 3, 5, 10]"
                        :page-size="filter.page_size"
                        layout="sizes, prev, pager, next"
                        :total="course_total">
                </el-pagination>
            </div>
        </div>
        <Footer></Footer>
    </div>
</template>

<script>
    import Header from "@/components/Head"
    import Footer from "@/components/Footer"

    export default {
        name: "Course",
        data() {
            return {
                category_list: [], // 课程分类列表
                course_list: [],   // 课程列表
                course_total: 0,   // 当前课程的总数量
                filter: {
                    course_category: 0, // 当前用户选择的课程分类,刚进入页面默认为全部,值为0
                    ordering: "-id",    // 数据的排序方式,默认值是-id,表示对于id进行降序排列
                    page_size: 2,       // 单页数据量
                    page: 1,
                }
            }
        },
        created() {
            this.get_category();
            this.get_course();
        },
        components: {
            Header,
            Footer,
        },
        watch: {
            //当你监听的数据发生变化,就会执行函数
            "filter.course_category": function () {
                this.filter.page = 1;
                this.get_course();
            },
            "filter.ordering": function () {
                this.get_course();
            },
            "filter.page_size": function () {
                this.get_course();
            },
            "filter.page": function () {
                this.get_course();
            }
        },
        methods: {

            handleSizeChange(val) {
                // 每页数据量发生变化时执行的方法
                this.filter.page = 1;
                this.filter.page_size = val;
            },
            handleCurrentChange(val) {
                // 页码发生变化时执行的方法
                this.filter.page = val;
            },
            get_category() {
                // 获取课程分类信息
                this.$axios.get(`${this.$settings.base_url}/course/categories/`).then(response => {
                    this.category_list = response.data;
                }).catch(() => {
                    this.$message({
                        message: "获取课程分类信息有误,请联系客服工作人员",
                    })
                })
            },
            get_course() {
                // 排序
                let filters = {
                    ordering: this.filter.ordering, // 排序
                };
                // 判决是否进行分类课程的展示
                if (this.filter.course_category > 0) {
                    filters.course_category = this.filter.course_category;
                }

                // 设置单页数据量
                if (this.filter.page_size > 0) {
                    filters.page_size = this.filter.page_size;
                } else {
                    filters.page_size = 5;
                }

                // 设置当前页码
                if (this.filter.page > 1) {
                    filters.page = this.filter.page;
                } else {
                    filters.page = 1;
                }


                // 获取课程列表信息
                this.$axios.get(`${this.$settings.base_url}/course/free/`, {
                    params: filters
                }).then(response => {
                    // console.log(response.data);
                    this.course_list = response.data.results;
                    this.course_total = response.data.count;
                    // console.log(this.course_list);
                }).catch(() => {
                    this.$message({
                        message: "获取课程信息有误,请联系客服工作人员"
                    })
                })
            }
        }
    }
</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 .ordering .price_up::before {
        border-bottom-color: #ffc210;
    }

    .course .ordering .price_down::after {
        border-top-color: #ffc210;
    }

    .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 {
        max-width: 100%;
        max-height: 210px;
    }

    .course .course-item .course-info {
        float: left;
        width: 596px;
    }

    .course-item .course-info h3 a {
        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 .section-list::after {
        content: "";
        display: block;
        clear: both;
    }

    .course-item .section-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 .section-list li .section-title {
        /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        display: inline-block;
        max-width: 200px;
    }

    .course-item .section-list li:hover {
        background-image: url("/src/assets/img/play-icon-yellow.svg");
        color: #ffc210;
    }

    .course-item .section-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 .section-list li:hover .free {
        color: #ffc210;
        border-color: #ffc210;
    }

    .course-item {
        position: relative;
    }

    .course-item .pay-box {
        position: absolute;
        bottom: 20px;
        width: 600px;
    }

    .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;
        position: absolute;
        right: 0;
        bottom: 5px;
    }

    .course-item .pay-box .buy-now:hover {
        color: #fff;
        background: #ffc210;
        border: 1px solid #ffc210;
    }

    .course .course_pagination {
        margin-bottom: 60px;
        text-align: center;
    }
</style>

前端课程详情页

#新建vue,src\views\FreeCourseDetail.vue

#配置路由,src\router\index.js

		{
            path: '/free/detail/:pk',
            name: 'FreeCourseDetail',
            component: FreeCourseDetail
        },
    
#安装 vue-video播放器,cnpm install vue-video-player,在main.js配置#src\main.js

	        // vue-video播放器
            require('video.js/dist/video-js.css');
            require('vue-video-player/src/custom-theme.css');
            import VideoPlayer from 'vue-video-player'
            Vue.use(VideoPlayer);
            
#src\views\FreeCourseDetail.vue

    <template>
        <div class="detail">
            <Header/>
            <div class="main">
                <div class="course-info">
                    <div class="wrap-left">
                        <videoPlayer class="video-player vjs-custom-skin"
                                     ref="videoPlayer"
                                     :playsinline="true"
                                     :options="playerOptions"
                                     @play="onPlayerPlay($event)"
                                     @pause="onPlayerPause($event)">
                        </videoPlayer>
                    </div>
                    <div class="wrap-right">
                        <h3 class="course-name">{{course_info.name}}</h3>
                        <p class="data">{{course_info.students}}人在学&nbsp;&nbsp;&nbsp;&nbsp;课程总时长:{{course_info.sections}}课时/{{course_info.pub_sections}}小时&nbsp;&nbsp;&nbsp;&nbsp;难度:{{course_info.level_name}}</p>
                        <div class="sale-time">
                            <p class="sale-type">价格 <span class="original_price">¥{{course_info.price}}</span></p>
                            <p class="expire"></p>
                        </div>
                        <div class="buy">
                            <div class="buy-btn">
                                <button class="buy-now">立即购买</button>
                                <button class="free">免费试学</button>
                            </div>
                            <!--<div class="add-cart" @click="add_cart(course_info.id)">-->
                                                            <!--<img src="@/assets/img/cart-yellow.svg" alt="">加入购物车-->
                            <!--</div>-->
                        </div>
                    </div>
                </div>
                <div class="course-tab">
                    <ul class="tab-list">
                        <li :class="tabIndex==1?'active':''" @click="tabIndex=1">详情介绍</li>
                        <li :class="tabIndex==2?'active':''" @click="tabIndex=2">课程章节 <span :class="tabIndex!=2?'free':''">(试学)</span>
                        </li>
                        <li :class="tabIndex==3?'active':''" @click="tabIndex=3">用户评论</li>
                        <li :class="tabIndex==4?'active':''" @click="tabIndex=4">常见问题</li>
                    </ul>
                </div>
                <div class="course-content">
                    <div class="course-tab-list">
                        <div class="tab-item" v-if="tabIndex==1">
                            <div class="course-brief" v-html="course_info.brief_text"></div>
                        </div>
                        <div class="tab-item" v-if="tabIndex==2">
                            <div class="tab-item-title">
                                <p class="chapter">课程章节</p>
                                <p class="chapter-length">共{{course_chapters.length}}章 {{course_info.sections}}个课时</p>
                            </div>
                            <div class="chapter-item" v-for="chapter in course_chapters" :key="chapter.name">
                                <p class="chapter-title"><img src="@/assets/img/enum.svg" alt="">第{{chapter.chapter}}章·{{chapter.name}}
                                </p>
                                <ul class="section-list">
                                    <li class="section-item" v-for="section in chapter.coursesections" :key="section.name">
                                        <p class="name"><span class="index">{{chapter.chapter}}-{{section.orders}}</span>
                                            {{section.name}}<span class="free" v-if="section.free_trail">免费</span></p>
                                        <p class="time">{{section.duration}} <img src="@/assets/img/chapter-player.svg"></p>
                                        <button class="try" v-if="section.free_trail">立即试学</button>
                                        <button class="try" v-else>立即购买</button>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="tab-item" v-if="tabIndex==3">
                            用户评论
                        </div>
                        <div class="tab-item" v-if="tabIndex==4">
                            常见问题
                        </div>
                    </div>
                    <div class="course-side">
                        <div class="teacher-info">
                            <h4 class="side-title"><span>授课老师</span></h4>
                            <div class="teacher-content">
                                <div class="cont1">
                                    <img :src="course_info.teacher.image">
                                    <div class="name">
                                        <p class="teacher-name">{{course_info.teacher.name}}
                                            {{course_info.teacher.title}}</p>
                                        <p class="teacher-title">{{course_info.teacher.signature}}</p>
                                    </div>
                                </div>
                                <p class="narrative">{{course_info.teacher.brief}}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <Footer/>
        </div>
    </template>

    <script>
        import Header from "@/components/Head"
        import Footer from "@/components/Footer"

        // 加载组件
        import {videoPlayer} from 'vue-video-player';

        export default {
            name: "Detail",
            data() {
                return {
                    tabIndex: 2,   // 当前选项卡显示的下标
                    course_id: 0, // 当前课程信息的ID
                    course_info: {
                        teacher: {},
                    }, // 课程信息
                    course_chapters: [], // 课程的章节课时列表
                    playerOptions: {
                        aspectRatio: '16:9', // 将播放器置于流畅模式,并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字(例如"16:9"或"4:3")
                        sources: [{ // 播放资源和资源格式
                            type: "video/mp4",
                            src: "http://qe5smxg12.bkt.clouddn.com/3%20%E9%A6%96%E9%A1%B5%E8%BD%AE%E6%92%AD%E5%9B%BE%E5%BC%82%E6%AD%A5%E6%9B%B4%E6%96%B0.mp4" //你的视频地址(必填)
                        }],
                    }
                }
            },
            created() {
                this.get_course_id();
                this.get_course_data();
                this.get_chapter();
            },
            methods: {
                onPlayerPlay() {
                    // 当视频播放时,执行的方法
                    console.log('视频开始播放')
                    //加广告
                },
                onPlayerPause() {
                    // 当视频暂停播放时,执行的方法
                    console.log('视频暂停,可以打开广告了')
                    //盖张图片
                },
                get_course_id() {
                    // 获取地址栏上面的课程ID
                    this.course_id = this.$route.params.pk || this.$route.query.pk;
                    if (this.course_id < 1) {
                        let _this = this;
                        _this.$alert("对不起,当前视频不存在!", "警告", {
                            callback() {
                                _this.$router.go(-1);
                            }
                        });
                    }
                },
                get_course_data() {
                    // ajax请求课程信息
                    this.$axios.get(`${this.$settings.base_url}/course/free/${this.course_id}/`).then(response => {
                        // window.console.log(response.data);
                        this.course_info = response.data;
                        console.log(this.course_info)
                    }).catch(() => {
                        this.$message({
                            message: "对不起,访问页面出错!请联系客服工作人员!"
                        });
                    })
                },

                get_chapter() {
                    // 获取当前课程对应的章节课时信息
                    // http://127.0.0.1:8000/course/chapters/?course=(pk)
                    this.$axios.get(`${this.$settings.base_url}/course/chapters/`, {
                        params: {
                            "course": this.course_id,
                        }
                    }).then(response => {
                        this.course_chapters = response.data;
                    }).catch(error => {
                        window.console.log(error.response);
                    })
                },
            },
            components: {
                Header,
                Footer,
                videoPlayer, // 注册组件
            }
        }
    </script>

    <style scoped>
        .main {
            background: #fff;
            padding-top: 30px;
        }

        .course-info {
            width: 1200px;
            margin: 0 auto;
            overflow: hidden;
        }

        .wrap-left {
            float: left;
            width: 690px;
            height: 388px;
            background-color: #000;
        }

        .wrap-right {
            float: left;
            position: relative;
            height: 388px;
        }

        .course-name {
            font-size: 20px;
            color: #333;
            padding: 10px 23px;
            letter-spacing: .45px;
        }

        .data {
            padding-left: 23px;
            padding-right: 23px;
            padding-bottom: 16px;
            font-size: 14px;
            color: #9b9b9b;
        }

        .sale-time {
            width: 464px;
            background: #fa6240;
            font-size: 14px;
            color: #4a4a4a;
            padding: 10px 23px;
            overflow: hidden;
        }

        .sale-type {
            font-size: 16px;
            color: #fff;
            letter-spacing: .36px;
            float: left;
        }

        .sale-time .expire {
            font-size: 14px;
            color: #fff;
            float: right;
        }

        .sale-time .expire .second {
            width: 24px;
            display: inline-block;
            background: #fafafa;
            color: #5e5e5e;
            padding: 6px 0;
            text-align: center;
        }

        .course-price {
            background: #fff;
            font-size: 14px;
            color: #4a4a4a;
            padding: 5px 23px;
        }

        .discount {
            font-size: 26px;
            color: #fa6240;
            margin-left: 10px;
            display: inline-block;
            margin-bottom: -5px;
        }

        .original {
            font-size: 14px;
            color: #9b9b9b;
            margin-left: 10px;
            text-decoration: line-through;
        }

        .buy {
            width: 464px;
            padding: 0px 23px;
            position: absolute;
            left: 0;
            bottom: 20px;
            overflow: hidden;
        }

        .buy .buy-btn {
            float: left;
        }

        .buy .buy-now {
            width: 125px;
            height: 40px;
            border: 0;
            background: #ffc210;
            border-radius: 4px;
            color: #fff;
            cursor: pointer;
            margin-right: 15px;
            outline: none;
        }

        .buy .free {
            width: 125px;
            height: 40px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 15px;
            background: #fff;
            color: #ffc210;
            border: 1px solid #ffc210;
        }

        .add-cart {
            float: right;
            font-size: 14px;
            color: #ffc210;
            text-align: center;
            cursor: pointer;
            margin-top: 10px;
        }

        .add-cart img {
            width: 20px;
            height: 18px;
            margin-right: 7px;
            vertical-align: middle;
        }

        .course-tab {
            width: 100%;
            background: #fff;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px 0 #f0f0f0;

        }

        .course-tab .tab-list {
            width: 1200px;
            margin: auto;
            color: #4a4a4a;
            overflow: hidden;
        }

        .tab-list li {
            float: left;
            margin-right: 15px;
            padding: 26px 20px 16px;
            font-size: 17px;
            cursor: pointer;
        }

        .tab-list .active {
            color: #ffc210;
            border-bottom: 2px solid #ffc210;
        }

        .tab-list .free {
            color: #fb7c55;
        }

        .course-content {
            width: 1200px;
            margin: 0 auto;
            background: #FAFAFA;
            overflow: hidden;
            padding-bottom: 40px;
        }

        .course-tab-list {
            width: 880px;
            height: auto;
            padding: 20px;
            background: #fff;
            float: left;
            box-sizing: border-box;
            overflow: hidden;
            position: relative;
            box-shadow: 0 2px 4px 0 #f0f0f0;
        }

        .tab-item {
            width: 880px;
            background: #fff;
            padding-bottom: 20px;
            box-shadow: 0 2px 4px 0 #f0f0f0;
        }

        .tab-item-title {
            justify-content: space-between;
            padding: 25px 20px 11px;
            border-radius: 4px;
            margin-bottom: 20px;
            border-bottom: 1px solid #333;
            border-bottom-color: rgba(51, 51, 51, .05);
            overflow: hidden;
        }

        .chapter {
            font-size: 17px;
            color: #4a4a4a;
            float: left;
        }

        .chapter-length {
            float: right;
            font-size: 14px;
            color: #9b9b9b;
            letter-spacing: .19px;
        }

        .chapter-title {
            font-size: 16px;
            color: #4a4a4a;
            letter-spacing: .26px;
            padding: 12px;
            background: #eee;
            border-radius: 2px;
            display: -ms-flexbox;
            display: flex;
            -ms-flex-align: center;
            align-items: center;
        }

        .chapter-title img {
            width: 18px;
            height: 18px;
            margin-right: 7px;
            vertical-align: middle;
        }

        .section-list {
            padding: 0 20px;
        }

        .section-list .section-item {
            padding: 15px 20px 15px 36px;
            cursor: pointer;
            justify-content: space-between;
            position: relative;
            overflow: hidden;
        }

        .section-item .name {
            font-size: 14px;
            color: #666;
            float: left;
        }

        .section-item .index {
            margin-right: 5px;
        }

        .section-item .free {
            font-size: 12px;
            color: #fff;
            letter-spacing: .19px;
            background: #ffc210;
            border-radius: 100px;
            padding: 1px 9px;
            margin-left: 10px;
        }

        .section-item .time {
            font-size: 14px;
            color: #666;
            letter-spacing: .23px;
            opacity: 1;
            transition: all .15s ease-in-out;
            float: right;
        }

        .section-item .time img {
            width: 18px;
            height: 18px;
            margin-left: 15px;
            vertical-align: text-bottom;
        }

        .section-item .try {
            width: 86px;
            height: 28px;
            background: #ffc210;
            border-radius: 4px;
            font-size: 14px;
            color: #fff;
            position: absolute;
            right: 20px;
            top: 10px;
            opacity: 0;
            transition: all .2s ease-in-out;
            cursor: pointer;
            outline: none;
            border: none;
        }

        .section-item:hover {
            background: #fcf7ef;
            box-shadow: 0 0 0 0 #f3f3f3;
        }

        .section-item:hover .name {
            color: #333;
        }

        .section-item:hover .try {
            opacity: 1;
        }

        .course-side {
            width: 300px;
            height: auto;
            margin-left: 20px;
            float: right;
        }

        .teacher-info {
            background: #fff;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px 0 #f0f0f0;
        }

        .side-title {
            font-weight: normal;
            font-size: 17px;
            color: #4a4a4a;
            padding: 18px 14px;
            border-bottom: 1px solid #333;
            border-bottom-color: rgba(51, 51, 51, .05);
        }

        .side-title span {
            display: inline-block;
            border-left: 2px solid #ffc210;
            padding-left: 12px;
        }

        .teacher-content {
            padding: 30px 20px;
            box-sizing: border-box;
        }

        .teacher-content .cont1 {
            margin-bottom: 12px;
            overflow: hidden;
        }

        .teacher-content .cont1 img {
            width: 54px;
            height: 54px;
            margin-right: 12px;
            float: left;
        }

        .teacher-content .cont1 .name {
            float: right;
        }

        .teacher-content .cont1 .teacher-name {
            width: 188px;
            font-size: 16px;
            color: #4a4a4a;
            padding-bottom: 4px;
        }

        .teacher-content .cont1 .teacher-title {
            width: 188px;
            font-size: 13px;
            color: #9b9b9b;
            white-space: nowrap;
        }

        .teacher-content .narrative {
            font-size: 14px;
            color: #666;
            line-height: 24px;
        }
    </style>

章节分类接口

#luffyapi\apps\course\views.py

    class CourseChapterView(GenericViewSet, ListModelMixin):
        queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True)
        serializer_class = serializer.CourseChapterSerializer

        # 可以按照课程id来查
        filter_backends = [DjangoFilterBackend]
        filter_fields = ['course']
 
#luffyapi\apps\course\serializer.py

    class CourseSectionSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.CourseSection
            fields = ['name','orders','duration','free_trail','section_link','section_type_name']


    #课程章节序列化器
    class CourseChapterSerializer(serializers.ModelSerializer):
        # 子序列化的方式
        coursesections=CourseSectionSerializer(many=True)
        class Meta:
            model=models.CourseChapter
            fields=['name','summary','chapter','coursesections']
            
#luffyapi\apps\course\urls.py
    router.register('chapters', views.CourseChapterView, 'coursechapter')

七牛云视频托管

#进入位置注册,实名认证
	https://www.qiniu.com/

#登录然后到管理控制台创建对象储存

#新建空间,上传文件,获得文件链接http://qe6j0hynu.bkt.clouddn.com/99f0eeb961b8cfae9cf8b017666c9bec.mp4

后台搜索接口

#luffyapi\apps\course\views.py

    class CouresSearchView(GenericViewSet,ListModelMixin):
        queryset = models.Course.objects.filter(is_delete=False,is_show=True)
        serializer_class = serializer.CourseModelSerializer
        # pagination_class = PageNumberPagination

        filter_backends=[SearchFilter]
        search_fields=['name']

#luffyapi\apps\course\urls.py

    router.register('search', views.CouresSearchView, 'search')

前台搜索页面

# 0 在Head.vue中相应的配置


# 1  vue带给另一个页面值
    -路由:path: '/free/detail/:pk',this.$route.params.pk  从路径中取值
	-search?word=dsa  去this.$route.query.word   从?后面的取
    
    
# 2 样式
<template>
    <div class="search-course course">
        <Header/>
        <h1>总共搜索到 {{course_total}}课程</h1>
        <!-- 课程列表 -->
        <div class="main">
            <div v-if="course_list.length > 0" class="course-list">
                <div class="course-item" v-for="course in course_list" :key="course.name">
                    <div class="course-image">
                        <img :src="course.course_img" alt="">
                    </div>
                    <div class="course-info">
                        <h3>
                            <router-link :to="'/free/detail/'+course.id">{{course.name}}</router-link>
                            <span><img src="@/assets/img/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3>
                        <p class="teather-info">
                            {{course.teacher.name}} {{course.teacher.title}} {{course.teacher.signature}}
                            <span v-if="course.sections>course.pub_sections">共{{course.sections}}课时/已更新{{course.pub_sections}}课时</span>
                            <span v-else>共{{course.sections}}课时/更新完成</span>
                        </p>
                        <ul class="section-list">
                            <li v-for="(section, key) in course.section_list" :key="section.name"><span
                                    class="section-title">0{{key+1}}  |  {{section.name}}</span>
                                <span class="free" v-if="section.free_trail">免费</span></li>
                        </ul>
                        <div class="pay-box">
                            <div v-if="course.discount_type">
                                <span class="discount-type">{{course.discount_type}}</span>
                                <span class="discount-price">¥{{course.real_price}}元</span>
                                <span class="original-price">原价:{{course.price}}元</span>
                            </div>
                            <span v-else class="discount-price">¥{{course.price}}元</span>
                            <span class="buy-now">立即购买</span>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else style="text-align: center; line-height: 60px">
                没有搜索结果
            </div>
            <div class="course_pagination block">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page.sync="filter.page"
                        :page-sizes="[2, 3, 5, 10]"
                        :page-size="filter.page_size"
                        layout="sizes, prev, pager, next"
                        :total="course_total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
    import Header from '../components/Head'

    export default {
        name: "SearchCourse",
        components: {
            Header,
        },
        data() {
            return {
                course_list: [],
                course_total: 0,
                filter: {
                    page_size: 10,
                    page: 1,
                    search: '',
                }
            }
        },
        created() {
            this.get_course()
        },
        watch: {
            '$route.query' () {
                this.get_course()
            }
        },
        methods: {
            handleSizeChange(val) {
                // 每页数据量发生变化时执行的方法
                this.filter.page = 1;
                this.filter.page_size = val;
            },
            handleCurrentChange(val) {
                // 页码发生变化时执行的方法
                this.filter.page = val;
            },
            get_course() {
                // 获取搜索的关键字
                this.filter.search = this.$route.query.word || this.$route.query.wd;

                // 获取课程列表信息
                this.$axios.get(`${this.$settings.base_url}/course/search/`, {
                    params: this.filter
                }).then(response => {
                    // 如果后台不分页,数据在response.data中;如果后台分页,数据在response.data.results中
                    this.course_list = response.data.results;
                    this.course_total = response.data.count;
                }).catch(() => {
                    this.$message({
                        message: "获取课程信息有误,请联系客服工作人员"
                    })
                })
            }
        }
    }
</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 .ordering .price_up::before {
        border-bottom-color: #ffc210;
    }

    .course .ordering .price_down::after {
        border-top-color: #ffc210;
    }

    .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 {
        max-width: 100%;
        max-height: 210px;
    }

    .course .course-item .course-info {
        float: left;
        width: 596px;
    }

    .course-item .course-info h3 a {
        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 .section-list::after {
        content: "";
        display: block;
        clear: both;
    }

    .course-item .section-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 .section-list li .section-title {
        /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        display: inline-block;
        max-width: 200px;
    }

    .course-item .section-list li:hover {
        background-image: url("/src/assets/img/play-icon-yellow.svg");
        color: #ffc210;
    }

    .course-item .section-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 .section-list li:hover .free {
        color: #ffc210;
        border-color: #ffc210;
    }

    .course-item {
        position: relative;
    }

    .course-item .pay-box {
        position: absolute;
        bottom: 20px;
        width: 600px;
    }

    .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;
        position: absolute;
        right: 0;
        bottom: 5px;
    }

    .course-item .pay-box .buy-now:hover {
        color: #fff;
        background: #ffc210;
        border: 1px solid #ffc210;
    }

    .course .course_pagination {
        margin-bottom: 60px;
        text-align: center;
    }
</style>    

支付宝开放平台(支付接口)

#进入沙箱环境,看图1,https://openhome.alipay.com/platform/appDaily.htm?tab=info

#下载软件,生成公钥,秘钥,看图2,https://opendocs.alipay.com/open/291/106097/
#生成的公钥,私钥文件在这C:\Users\Steady\Documents\支付宝开放平台开发助手\RSA密钥

#取出公钥,配置到支付宝平台,他会生成一个支付宝公钥,看图3

图1

图2

图3

后端使用支付接口

#安装pip install python-alipay-sdk

#新建一个包,本地测试用,scripts\alipay_test.py

    from alipay import AliPay


    # app_private_key_string = open("/path/to/your/private/key.pem").read()
    # alipay_public_key_string = open("/path/to/alipay/public/key.pem").read()
    #自己的私钥
    app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
    MIIEowIBAAKCAQEAzH4gLah2+9reKHo9s/edqgytBn9tPzHBDNBca2OeUzWRsR0rJTa/3oQICddGttdwjrA8lV3rK0ByDGYKM3WZRuqDwdkRU17aav21sTw42JmeVPMxFzNczoN6N0IL8WcLwRhOeUUoOkrKkmeJFdZAkP2UuoRqh9qXCjDBlZUayEVMH3gRWdlvCdQnEqkJJTi94yHUgvVATQnU3FVLYLgMqCJCFHVabvEBRjBBZ6VzqOZic2WevlC2pjlZt/u1TWsCRIV4xHwbAtcfIW66WMV9q4tyN/9WTG437n7iokMbRZkBTQWFdh9wvSNgl/fCSBsmJPrtuj924xfLu/dvwBml9wIDAQABAoIBAAbiH/cpeofTwDKgmr8aEKaOsqxLUcQUyqjBwrqiqcunO/Y4QyGHjEHTM+oQ4wJ4kgNbj05/0NCt5KjiLmm5BaXLcw/tXJXv1W5Qh/MlUcyIrzmwzfA3/GG/Lzf48yn3DAA97zZJy6baqaLv9T9U7Ot0fbMhjexwwTDIn1uHn1UqYJOGAuGCB/a0GpK1n3Bk4Uut5LxEAa3F/Jyyx0YZaBcKwbp3Q7oVhhrYqFluDLoLzRRDRVMWSjfAd+IRK8KnnnBtd7hUydh9+lmnZ0JIE2OhFTEqhoNnShP1AxQkjfJVNj8LFm5N/hzgk6Uxu4WjqUvn0Cdl4CoI2mzhTSc5ZgECgYEA6X90QHWINcAntgBA4fcOAn5HmA6wP6xCiag+kXBPBx8oAsuRYeBywnw/8cJQ/XH1fz3hah3hFmly+5ckeAEF7WpyUISCEmhJr1sc4IAwBMX8KDYQUluvx2PfA/ZWpS+r9Xb1hz+2WRUWs1gACOjkMuHA0POhEYU8hhP08YyXI4ECgYEA4DMYMX+28UDYn6Dj15HuMQA3uNaXZwHVLLg4nYWRYlIa4hKygzFHN40KoZCgkg4H92TSs4pui87qJw9Pt2Z2ISW/lg3JCotBNkIN+Tcfm0fptecLItEztRjFlLtI0w1vperL0X0mbtKswtx4r3b7qFiu2VP18kIehqxzhN72pXcCgYAL1CEXgty7nFhmp+yhhdp31d3aniPfleJpBtTkmUPnoHRub9GVm8E0iQbUQHvJ2xQMth3NOmZEtGLWy/lU+vhJ5rKT0aKlPBM/huYXmWbVVxJHFzYMdgiZmT2a/ce15oxXiwc1Ks0aBi94NmUKDoJA8Z7K9wyZzp4aTLiD5BNkAQKBgQCh70XCOuUATD4qziLDSXwpmGam8xhYJlK7AjSiUh84TOVt9ONLLwSpcw4CtFvGIqxOXFxzocFG6iTmIYEKjs80EffXgg17uClZ70v4fYAuwDpmUIMSmtgmLcZILx3ikwnZZUXiAesIkNKHzIa+9cm/Ro7EGojCek9iJp0pk4HC8QKBgB8bAb7xqL6zCJQxRyDjfNUNiNicvuMLHWPJT55/sVNJixuxzB/+fOfZk+uSXaeI9lcgtb29SPQkUUeU+3ch0jnrnmt0juLT37HNYipbpAP4WkXMjL9fl7hnGlsUHluYHGuk+B0sNU8OQRhTKSEejejeErfCsfYO+s43ViXrg8Fb
    -----END RSA PRIVATE KEY-----
    """
    #支付宝公钥
    alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAghJr50XjmyFrDu7t9rJhafOSgq5y/RANJ1IqferzYpzn9RJkV02nqe2gxXiXD52Ec4CRxYrQ43ghEEGcQtbWVg5u2PNVR8PFi/HVCW8fqwSYYIXQbhVN2doWS/cO8d6FdCg7+ni/XN9LYCk1SBJGLNrz1Mxz8LjLRNt7F34qa+DezaqG0jXt7wtk6Vd6amqVSvIMB80dJhdItc2WIOR/ml4rObiF/VHDhbe5dpD8iN8aCMQocVWDJq1Oe4Ihy9nUoXRWCKW3RM2Jfv/FIAHImHRT8CY12XnwjPcN/jUuQw9qB3ZDY2xBh0wbIVT6SQ802l6JWExBcb7gzAzgK5uQDQIDAQAB
    -----END PUBLIC KEY-----
    """

    alipay = AliPay(
        appid="2021000116660237",#沙箱应用appid
        app_notify_url='http://127.0.0.1:8000/home/',  # the default notify path
        app_private_key_string=app_private_key_string,
        # alipay public key, do not use your own public key!
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2", # RSA or RSA2
        debug=True  # False by default
    )


    alipay_url='https://openapi.alipaydev.com/gateway.do?'
    order_string = alipay.api_alipay_trade_page_pay    (
        out_trade_no="20161112www4334",#交易订单号,每次不能一样
        total_amount=9999,#订单价格
        subject='韩红版充气娃娃',#商品名称
        return_url="https://www.luffycity.com/free-course",#支付成功返回商户的url
        notify_url="https://www.luffycity.com/free-course",#需要拿到返回结果的url
    )
    print(alipay_url+order_string)#打印出支付的地址
    
 #支付地址效果图,看图1   

图1

支付宝二次封装

#luffyapi\libs\ali_pay\settings.py

    import os
    #支付宝沙箱应用appid
    APPID = 2021000116660237
    #自己生成的私钥
    APP_PRIVATE_KEY_STRING = open(os.path.join(os.path.dirname(__file__),'pem','private_key.pem')).read()
    #沙箱公钥
    ALIPAY_PUBLIC_KEY_STRING = open(os.path.join(os.path.dirname(__file__),'pem','al_public_key.pem')).read()
    #秘钥长度
    SIGN_TYPE='RSA2'
    DEBUG=True
    GATEWAY='https://openapi.alipaydev.com/gateway.do?' if DEBUG else 'https://openapi.alipay.com/gateway.do?'
    
#luffyapi\libs\ali_pay\pay.py

	from alipay import AliPay
	from . import settings
    alipay = AliPay(
        appid=settings.APPID,
        app_notify_url=None,  #支付结果回调地址
        app_private_key_string=settings.APP_PRIVATE_KEY_STRING,#生成的私钥
        alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,#沙箱公钥
        sign_type=settings.SIGN_TYPE, # RSA or RSA2#秘钥长度
        debug=settings.DEBUG  # False by default
    )
    gateway=settings.GATEWAY#网关
    
#luffyapi\libs\ali_pay\__init__.py
	
    from .pay import alipay,gateway

订单模块表创建

#新建一个app python ../../manage.py startapp order ,创建表

from django.db import models
from django.db import models
from user.models import User
from course.models import Course
# 订单表
class Order(models.Model):
    """订单模型"""
    status_choices = (
        (0, '未支付'),
        (1, '已支付'),
        (2, '已取消'),
        (3, '超时取消'),
    )
    pay_choices = (
        (1, '支付宝'),
        (2, '微信支付'),
    )
    subject = models.CharField(max_length=150, verbose_name="订单标题")
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总价", default=0)
    out_trade_no = models.CharField(max_length=64, verbose_name="订单号", unique=True)
    trade_no = models.CharField(max_length=64, null=True, verbose_name="流水号")  # 支付宝生成回来的
    order_status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="订单状态")
    pay_type = models.SmallIntegerField(choices=pay_choices, default=1, verbose_name="支付方式")
    pay_time = models.DateTimeField(null=True, verbose_name="支付时间")
    # 一个用户可以下多个订单,一个订单只属于一个用户,一对多的关系,关联字段写在多个一方,写在order方
    user = models.ForeignKey(User, related_name='order_user', on_delete=models.DO_NOTHING, db_constraint=False, verbose_name="下单用户")
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')
    class Meta:
        db_table = "luffy_order"
        verbose_name = "订单记录"
        verbose_name_plural = "订单记录"

    def __str__(self):
        return "%s - ¥%s" % (self.subject, self.total_amount)

    @property
    def courses(self):
        data_list = []
        for item in self.order_courses.all():
            data_list.append({
                "id": item.id,
                "course_name": item.course.name,
                "real_price": item.real_price,
            })
        return data_list

# 订单详情表
# 订单和详情是一对多,关联字段写在多个的一方,写在订单详情表中
class OrderDetail(models.Model):
    """订单详情"""
    order = models.ForeignKey(Order, related_name='order_courses', on_delete=models.CASCADE, db_constraint=False, verbose_name="订单")
    course = models.ForeignKey(Course, related_name='course_orders', on_delete=models.SET_NULL, db_constraint=False, verbose_name="课程",null=True)
    price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价")
    real_price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程实价")

    class Meta:
        db_table = "luffy_order_detail"
        verbose_name = "订单详情"
        verbose_name_plural = "订单详情"

    def __str__(self):
        try:
            return "%s的订单:%s" % (self.course.name, self.order.out_trade_no)
        except:
            return super().__str__()

支付接口

#支付接口分析
	1 生成订单,生成支付连接,返回支付连接
    	order表和orderdetail表插入数据,重写create方法
        生成订单号uuid
        登录后才能做,使用jwt认证
        当前用户是下单用户,存到order表中
        效验价格
	2 支付宝异步回调的post接口,用于验证签名,修改订单状态
    3 支付宝get回调前端,vue组件收到,立马向后端发一个get请求
    
    
#实际操作,规定前端数据格式
	-{course:[1,2,3],total_amount:100,subject:xx商品,pay_type:1,}
    
#luffyapi\apps\order\views.py

    from rest_framework.viewsets import GenericViewSet
    from rest_framework.mixins import CreateModelMixin
    from rest_framework_jwt.authentication import JSONWebTokenAuthentication
    from rest_framework.permissions import IsAuthenticated
    from . import models,serializer
    from rest_framework.response import Response
    class PayView(GenericViewSet, CreateModelMixin):
        authentication_classes = [JSONWebTokenAuthentication, ]
        permission_classes = [IsAuthenticated, ]
        queryset = models.Order.objects.all()
        serializer_class = serializer.OrderSerializer

        # 重写create方法
        def create(self, request, *args, **kwargs):
            serializer = self.get_serializer(data=request.data, context={'request': request})
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            return Response(serializer.context.get('pay_url'))

        
#luffyapi\apps\order\serializer.py      

    from rest_framework import serializers
    from . import models
    from apps import Course
    from rest_framework.exceptions import ValidationError
    class OrderSerializer(serializers.ModelSerializer):
        # 前端传什么数据过来{course:[1,2,3],total_amount:100,subject:xx商品,pay_type:1,}
        # user字段需要,但是不是传的,使用了jwt


        # 需要把course:[1,2,3] 处理成 course:[obj1,obj2,obj3]

        # 课时:[1,4,6,]===>课时:[obj1,obj4,obj6,]
        # course=serializers.CharField()
        course=serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(), write_only=True, many=True)

        class Meta:
            model = models.Order
            fields = ['total_amount','subject','pay_type','course']
            extra_kwargs={
                'total_amount':{'required':True},
                'pay_type': {'required': True},
            }


        def _check_price(self,attrs):
            total_amount=attrs.get('total_amount')
            course_list=attrs.get('course')
            total_price=0
            for course in course_list:
                total_price+=course.price
            if total_price!=total_amount:
                raise ValidationError('价格不合法')
            return total_amount

        def _gen_out_trade_no(self):
            import uuid
            return str(uuid.uuid4()).replace('-','')

        def _get_user(self):
            # 需要request对象(需要视图通过context把reuqest对象传入。重写create方法)
            request=self.context.get('request')
            return request.user

        def _gen_pay_url(self,out_trade_no,total_amout,subject):
            # total_amout是Decimal类型,识别不了,需要转换成float类型
            from luffyapi.libs.ali_pay import alipay,gateway
            from django.conf import settings
            order_string = alipay.api_alipay_trade_page_pay    (
                out_trade_no=out_trade_no,
                total_amount=float(total_amout),
                subject=subject,
                return_url=settings.RETURN_URL,  # get回调,前台地址
                notify_url=settings.NOTIFY_URL   # post回调,后台地址
            )
            return gateway+order_string

        def _before_create(self,attrs,user,pay_url,out_trade_no):
            attrs['user']=user
            attrs['out_trade_no']=out_trade_no

            self.context['pay_url']=pay_url
        def validate(self, attrs):
            '''
            # 1)订单总价校验
            # 2)生成订单号
            # 3)支付用户:request.user
            # 4)支付链接生成
            # 5)入库(两个表)的信息准备
            '''
            # 1)订单总价校验
            total_amout = self._check_price(attrs)
            # 2)生成订单号
            out_trade_no=self._gen_out_trade_no()
            # 3)支付用户:request.user
            user=self._get_user()
            # 4)支付链接生成
            pay_url=self._gen_pay_url(out_trade_no,total_amout,attrs.get('subject'))
            # 5)入库(两个表)的信息准备
            self._before_create(attrs,user,pay_url,out_trade_no)
            return attrs
        def create(self, validated_data):
            course_list=validated_data.pop('course')
            order=models.Order.objects.create(**validated_data)
            for course in course_list:
                models.OrderDetail.objects.create(order=order,course=course,price=course.price,real_price=course.price)

            return order
        
#luffyapi\apps\order\urls.py

	rom django.urls import path,re_path,include
    from . import views

    from rest_framework.routers import  SimpleRouter

    router = SimpleRouter()
    router.register('pay', views.PayView, 'pay')
    urlpatterns = [
        path('', include(router.urls)),
    ]

前后台回调端口配置

#luffyapi\settings\dev.py
    # 上线后要换成公网地址
    # 后台基URL
    BASE_URL = 'http://127.0.0.1:8000'
    # 前台基URL
    LUFFY_URL = 'http://127.0.0.1:8080'
    # 支付宝同步异步回调接口配置
    # 后台异步回调接口
    NOTIFY_URL = BASE_URL + "/order/success/"
    # 前台同步回调接口,没有 / 结尾
    RETURN_URL = LUFFY_URL + "/pay/success"

前台生成订单并跳转

#src\views\FreeCourse.vue,template内修改下面这句

	<span class="buy-now" @click="buy_now(course)">立即购买</span>

#src\views\FreeCourse.vue,script的methods内添加buy_now方法
	            buy_now(course) {
                let token = this.$cookies.get('token')
                if (!token) {
                    this.$message({
                        message: "您还没有登录,请先登录",
                    })
                    return false
                }
                this.$axios({
                        method: 'post',
                        url: this.$settings.base_url + '/order/pay/',
                        data: {
                            "total_amount": course.price,
                            "subject": course.name,
                            "pay_type": 1,
                            "course": [
                                course.id,
                            ]
                        },
                        headers: {Authorization: 'jwt ' + token}
                    }
                ).then(response => {
                    console.log(response.data)
                    let pay_url = response.data
                    //前端发送get请求
                    open(pay_url, '_self')
                }).catch(error => {
                })

            },

前台支付成功页面

#src\views\PaySuccess.vue

    <template>
        <div class="pay-success">
            <!--如果是单独的页面,就没必要展示导航栏(带有登录的用户)-->
            <Header/>
            <div class="main">
                <div class="title">
                    <div class="success-tips">
                        <p class="tips">您已成功购买 1 门课程!</p>
                    </div>
                </div>
                <div class="order-info">
                    <p class="info"><b>订单号:</b><span>{{ result.out_trade_no }}</span></p>
                    <p class="info"><b>交易号:</b><span>{{ result.trade_no }}</span></p>
                    <p class="info"><b>付款时间:</b><span><span>{{ result.timestamp }}</span></span></p>
                </div>
                <div class="study">
                    <span>立即学习</span>
                </div>
            </div>
        </div>
    </template>

    <script>
        import Header from "@/components/Head"

        export default {
            name: "Success",
            data() {
                return {
                    result: {},
                };
            },
            created() {
                // url后拼接的参数:?及后面的所有参数 => ?a=1&b=2
                // console.log(location.search);

                // 解析支付宝回调的url参数
                let params = location.search.substring(1);  // 去除? => a=1&b=2
                let items = params.length ? params.split('&') : [];  // ['a=1', 'b=2']
                //逐个将每一项添加到args对象中
                for (let i = 0; i < items.length; i++) {  // 第一次循环a=1,第二次b=2
                    let k_v = items[i].split('=');  // ['a', '1']
                    //解码操作,因为查询字符串经过编码的
                    if (k_v.length >= 2) {
                        // url编码反解
                        let k = decodeURIComponent(k_v[0]);
                        this.result[k] = decodeURIComponent(k_v[1]);
                        // 没有url编码反解
                        // this.result[k_v[0]] = k_v[1];
                    }

                }
                // 解析后的结果
                // console.log(this.result);


                // 把地址栏上面的支付结果,再get请求转发给后端
                this.$axios({
                    url: this.$settings.base_url + '/order/success/' + location.search,
                    method: 'get',
                }).then(response => {
                    console.log(response.data);
                }).catch(() => {
                    console.log('支付结果同步失败');
                })
            },
            components: {
                Header,
            }
        }
    </script>

    <style scoped>
        .main {
            padding: 60px 0;
            margin: 0 auto;
            width: 1200px;
            background: #fff;
        }

        .main .title {
            display: flex;
            -ms-flex-align: center;
            align-items: center;
            padding: 25px 40px;
            border-bottom: 1px solid #f2f2f2;
        }

        .main .title .success-tips {
            box-sizing: border-box;
        }

        .title img {
            vertical-align: middle;
            width: 60px;
            height: 60px;
            margin-right: 40px;
        }

        .title .success-tips {
            box-sizing: border-box;
        }

        .title .tips {
            font-size: 26px;
            color: #000;
        }


        .info span {
            color: #ec6730;
        }

        .order-info {
            padding: 25px 48px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f2f2f2;
        }

        .order-info p {
            display: -ms-flexbox;
            display: flex;
            margin-bottom: 10px;
            font-size: 16px;
        }

        .order-info p b {
            font-weight: 400;
            color: #9d9d9d;
            white-space: nowrap;
        }

        .study {
            padding: 25px 40px;
        }

        .study span {
            display: block;
            width: 140px;
            height: 42px;
            text-align: center;
            line-height: 42px;
            cursor: pointer;
            background: #ffc210;
            border-radius: 6px;
            font-size: 16px;
            color: #fff;
        }
    </style>

#src\router\index.js,配置路由
	
	    {
            path: '/pay/success',
            name: 'PaySuccess',
            component: PaySuccess
    	},

支付宝回调到前端参数

charset=utf-8&
out_trade_no=17fcf8cac17c442bbbc114df6004afff&
method=alipay.trade.page.pay.return&
total_amount=99.00&
sign=WfK2beWFKvVaTHXpREi8HqZtFRH3JbeIvkliReYvfuhAsqaxHguARKtW6jUqUdZinm7ZSaYE1NrBRQa3%2BLquMk6uMnxE0i%2FTXIu4%2FmNTCEqSUlG8fTRPwC2%2BuU4nN1Ym0eM4puzAc2TUnEJnXCGKP9UxMifN3cjqR5BP%2B3RRngZSS4IQeogjurpfdiIolLzed%2FHTWbc4HqvWlWn9JuLmFGTtKHvRRKFr1hqq8Pj%2Fe3Al8kieDN9Q7JhEdC6F5ROo9rLlmUJtevkjI22oRScrfJl5hb%2BeYosxNg3WktmYKlF5vsKeZKKnLayAvKGoySLvaWk90x0LijHzzf2%2F8a9s3w%3D%3D&
trade_no=2020072922001480160500851368&
auth_app_id=2016092000554611&
version=1.0&
app_id=2016092000554611&
sign_type=RSA2&
seller_id=2088102176466324&
timestamp=2020-07-29%2015%3A06%3A44

同步异步回调接口

#luffyapi\apps\order\views.py

	#支付宝回调后端、前端get效验订单状态
    from rest_framework.views import APIView
    class SuccessView(APIView):
        def get(self,request,*args,**kwargs):
            out_trade_no=request.query_params.get('out_trade_no')
            order=models.Order.objects.filter(out_trade_no=out_trade_no).first()
            if order.order_status==1:
                return Response(True)
            else:
                return Response(False)

        def post(self,request,*args,**kwargs):
            '''
            支付宝回调接口
            '''
            from luffyapi.libs.ali_pay import alipay
            from luffyapi.utils.logger import log
            data = request.data
            out_trade_no=data.get('out_trade_no',None)
            gmt_payment=data.get('gmt_payment',None)
            signature = data.pop("sign")
            # 验证签名
            success = alipay.verify(data, signature)
            if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                models.Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1,pay_time=gmt_payment)
                log.info('%s订单支付成功'%out_trade_no)
                return Response('success')
            else:
                log.info('%s订单有问题' % out_trade_no)
                return Response('error')

#luffyapi\apps\order\urls.py,加上路由          
 
        path('success',views.SuccessView.as_view()),
            

上线操作

posted @ 2020-07-31 18:43  Joab-0429  阅读(184)  评论(0编辑  收藏  举报