day-87路飞学城
pip全局永久换源(虚拟环境也适用)
1、文件管理器文件路径地址栏敲:%APPDATA% 回车,快速进入 C:\Users\电脑用户\AppData\Roaming 文件夹中 2、新建 pip 文件夹并在文件夹中新建 pip.ini 配置文件 3、新增 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
虚拟环境搭建
#安装模块(安装在python3中) pip3 install virtualenv pip3 install virtualenvwrapper-win # 配置 1.在D盘新建一个文件夹 2.配置环境变量:控制面板 => 系统和安全 => 系统 => 高级系统设置 => 环境变量 => 系统变量 => 点击新建 => 填入变量名与值 变量名:WORKON_HOME 变量值:新文件夹(存放虚拟环境)的绝对路径 #WORKON_HOME: D:\Virtualenvs 3.同步配置信息: 去向Python3的安装目录 => Scripts文件夹 => virtualenvwrapper.bat => 双击 #使用 在终端工作的命令 1.选取默认Python环境创建虚拟环境: -- mkvirtualenv 虚拟环境名称 基于某Python环境创建虚拟环境: -- mkvirtualenv -p python2.7 虚拟环境名称 -- mkvirtualenv -p python3.6 虚拟环境名称 2、查看已有的虚拟环境 -- workon 3、使用某个虚拟环境 -- workon 虚拟环境名称 4、进入|退出 该虚拟环境的Python环境 -- python | exit() 5、为虚拟环境安装模块 -- pip或pip3 install 模块名 6、退出当前虚拟环境 -- deactivate 7、删除虚拟环境(删除当前虚拟环境要先退出) -- rmvirtualenv 虚拟环境名称
python使用虚拟环境
后台项目搭建
1.虚拟环境配置模块 >: pip install django >: pip install djangorestframework >: pip install PymySQL 2.创建项目 前提:在目标目录新建luffy文件夹 创建: >: cd 建立的luffy文件夹 >: django-admin startproject luffyapi 开发:用pycharm打开项目,并选择提前备好的虚拟环境 3.重构项目目录 ├── luffyapi ├── logs/ # 项目运行时/开发时日志目录(文件夹) ├── manage.py # 脚本文件 ├── luffyapi/ # 项目主应用,开发时的代码保存(包) │ ├── apps/ # 开发者的代码保存目录,以模块[子应用]为目录保存(包) │ ├── libs/ # 第三方类库的保存目录[第三方组件、模块](包) │ ├── settings/ # 配置目录(包) │ ├── dev.py # 项目开发时的本地配置 │ ├── prod.py # 项目上线时的运行配置 │ ├── urls.py # 总路由 │ ├── utils/ # 多个模块[子应用]的公共函数类库[自己开发的组件] └── scripts/ # 保存项目运营时的脚本文件 - 文件夹 4.配置开发环境 a.将settings.py文件内容移植到settings文件夹中的dev.py,并移除settings.py b.修改wsgi.py、manage.py配置文件指向: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev') c.修改dev.py文件内容: #注册drf INSTALLED_APPS = [ 'rest_framework', ] # BASE_DIR添加到环境变量 import sys sys.path.insert(0, BASE_DIR) # 国际化 LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' #配置日志:
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': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'file': {
# 实际开发建议使用WARNING或ERROR
'level': 'WARNING',
'class': 'logging.handlers.RotatingFileHandler',
# 日志位置,日志文件名,日志保存目录必须手动创建,注:这里的文件路径要注意BASE_DIR
'filename': os.path.join(os.path.dirname(BASE_DIR), "logs/luffy.log"),
# 日志文件的最大值,这里我们设置300M
'maxBytes': 300 * 1024 * 1024,
# 日志文件的数量,设置最大日志数量为10
'backupCount': 10,
# 日志格式:详细格式
'formatter': 'verbose',
'encoding':'utf-8'
},
},
# 日志对象
'loggers': {
'django': {
'handlers': ['console', 'file'],
'propagate': True, # 是否让日志信息继续冒泡给其他的日志处理系统
},
}
}
5.修改启动配置(同上4b) 6.在script文件加中建测试文件t_proj.py测试默认配置文件是否是dev.py文件 import os, django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev') django.setup() from django.conf import settings print(settings) from utils.logging import logger logger.error('测试error') 7.utils/logging.py: 配置logger完成自定义错误信息往文件或控制台打印 import logging logger = logging.getLogger('django') 8.utils/response.py: 二次封装Response类: from rest_framework.response import Response class APIResponse(Response): def __init__(self, data_status, msg, results=None, headers=None, status=None, **kwargs): data = { 'status': data_status, 'msg': msg, } if results: data['results'] = results data.update(kwargs) super().__init__(data=data, headers=headers, status=status) 9.utils/exception.py: 异常处理 from rest_framework.views import exception_handler as drf_exception_handler from rest_framework import status from rest_framework.response import Response from .logging import logger def exception_handler(exc, context): response = drf_exception_handler(exc, context) if response is None: view = context['view'] logger.error('%s:%s' % (view, exc)) response = Response({'detail': '服务器内部错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response settings/dev.py: 异常处理配置settings配置 REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'utils.exception.exception_handler' } 10.媒体目录 # dev.py中 # 访问要上传文件的url地址前缀 MEDIA_URL = "/media/" #项目中存储上传文件的根目录 MEDIA_ROOT = os.path.join(BASE_DIR, "media") # 创建文件 在luffyapi/luffyapi中创建media目录(谁是项目根目录就在那个文件夹下创建) # 配置路由 from django.urls import re_path from django.views.static import serve from django.conf import settings urlpatterns = [ re_path(r'media/(?P<path>.*)', serve, {"document_root": settings.MEDIA_ROOT}), ]
数据库配置
1.管理员连接数据库 2.创建数据库 >: create database luffy default charset=utf8; 3.单独给新数据库设置权限账号密码 # 拥有公网或局域网,其他主机连mysql >: grant all privileges on luffy.* to 'luffy'@'%' identified by 'luffy'; #要是本机连mysql连不上,再增加localhost域,本机就可以登录了 >: grant all privileges on luffy.* to 'luffy'@'localhost' identified by 'luffy'; #设置完有权限限制的账号后一定要刷新权限 >: flush privileges; 4.退出管理员,用账号 luffy 密码 luffy 登入开发 5.settings/dev.py配置 DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "HOST": "127.0.0.1", "PORT": 3306, "USER": "luffy", "PASSWORD": "luffy", "NAME": "luffy", } } 6.luffypai/__init__.py import pymysql pymysql.install_as_MySQLdb() 7.运行会出现Django与pymysql版本兼容问题:见两张插图
新建user应用
1.终端前往luffyapi/apps所在目录 >:cd luffyapi\apps 2,创建user组件 >: python ../../manage.py startapp user 3.settings/dev.py中先把apps添加环境变量,在注册user sys.path.insert(1, os.path.join(BASE_DIR, 'apps')) INSTALLED_APPS = [ 'user' ] 4.分发路由 #主路由urls.py from django.urls import include urlpatterns = [ path('user/', include('user.urls')), ] #子路由 from django.urls import path, re_path from . import views urlpatterns = [ ] 5.自定义user表:user/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): mobile = models.CharField(verbose_name="手机号码", max_length=15, unique=True) avatar = models.ImageField(upload_to='avatar', verbose_name='用户头像', null=True, blank=True, help_text="头像图片的大小规格:256x256,或者对应的比例的图片") class Meta: db_table = 'luffy_user' verbose_name = '用户' verbose_name_plural = verbose_name def __str__(self): return self.username 6.修改auth认证的user表:settings/dev.py # 这里是固定写法:模块.继承AbstractUser的自定义User表 AUTH_USER_MODEL = 'user.User' 7.ImageField字段需要支持:安装 Pillow >: pip install Pillow 8.新建管理员用户: >: python manage.py createsuperuser 9.数据库迁移 >: python manage.py makemigrations >: python manage.py migrate
前台
1.安装node环境 1.傻瓜式安装node: https://nodejs.org/zh-cn/ 2.安装cnpm: npm install -g cnpm --registry=https://registry.npm.taobao.org 3.安装vue/cli 3.x: cnpm install -g @vue/cli 4.如果报错处理后重新走2、3步:npm cache clean --force 2.创建项目 前提:在目标目录新建luffy文件夹 >: cd 建立的luffy文件夹 >: vue create luffycity 3.重构项目目录 ├── luffycity ├── public/ # 项目共有资源 │ ├── favicon.ico # 站点图标 │ ├── index.html # 主页 ├── src/ # 项目主应用,开发时的代码保存 │ ├── assets/ # 前台静态资源总目录 │ │ ├── css/ # 自定义css样式 │ │ │ ├── global.css # 自定义全局样式 │ │ ├── js/ # 自定义js样式 │ │ ├── img/ # 前台图片资源 │ ├── components/ # 小组件目录 │ ├── views/ # 页面组件目录 │ ├── App.vue # 根路由 │ ├── main.js # 入口脚本文件 │ ├── router.js # 路由脚本文件 │ ├── settings.js # 自定义配置文件 │ ├── store.js # 仓库基本文件 └── vue.config.js # 全局配置文件 4.更换顶部图标 favicon.ico 5.配置全局css: assets/css/global.css html, body { margin: 0; } main.js import '@/assets/css/global.css' 6.配置文件:settings.js export default { BASE_HTTP: 'http://localhost:8000' } main.js import settings from '@/settings.js' Vue.prototype.$settings = settings; 7.组件方法中访问 created () { console.log(this.$settings.BASE_HTTP + '/users/') } 8.文件改造 删除文件 HelloWorld.vue About.vue Home.vue <template> <div class="home"> <h1>主页</h1> <hr> <el-row> <el-button>默认按钮</el-button> <el-button type="primary">主要按钮</el-button> <el-button type="success">成功按钮</el-button> <el-button type="info">信息按钮</el-button> <el-button type="warning">警告按钮</el-button> <el-button type="danger">危险按钮</el-button> </el-row> </div> </template> <script> export default { name: 'home', created() { console.log(this.$settings.BASE_HTTP + '/users/') } } </script> App.vue <template> <div id="app"> <router-view/> </div> </template> main.js import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' Vue.config.productionTip = false; // 配置全局css import '@/assets/css/global.css' // 配置全局settings import settings from '@/settings.js' Vue.prototype.$settings = settings; new Vue({ router, store, render: h => h(App) }).$mount('#app'); route.js import Vue from 'vue' import Router from 'vue-router' import Home from './views/Home.vue' Vue.use(Router); export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: Home } ] }) 9.配置element-ui 安装 >: cnpm install element-ui --save main.js配置 import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI);
前台主页
## 前端主页 1.App.vue - 根组件 <template> <div id="app"> <router-view/> </div> </template> <script> export default { name: 'App' } </script> 2.Home.vue - 页面组件 <template> <div class="home"> <Header></Header> <Banner></Banner> <Footer></Footer> </div> </template> <script> import Header from "@/components/Header" import Banner from "@/components/Banner" import Footer from "@/components/Footer" export default { name: "Home", data() { return {} }, methods: {}, components: { Header, Footer, Banner, } } </script> <style scoped> </style> 3.Header.vue - 小组件 <template> <div class="header-box"> <div class="header"> <div class="content"> <div class="logo full-left"> <router-link to="/"><img @click="jump('/')" src="@/assets/img/logo.svg" alt=""></router-link> </div> <ul class="nav full-left"> <li><span @click="jump('/course')" :class="this_nav=='/course'?'this':''">免费课</span></li> <li><span @click="jump('/light-course')" :class="this_nav=='/light-course'?'this':''">轻课</span></li> <li><span>学位课</span></li> <li><span>题库</span></li> <li><span>老男孩教育</span></li> </ul> <div class="login-bar full-right"> <div class="shop-cart full-left"> <img src="@/assets/img/cart.svg" alt=""> <span><router-link to="/cart">购物车</router-link></span> </div> <div class="login-box full-left"> <span>登录</span> | <span>注册</span> </div> </div> </div> </div> </div> </template> <script> export default { name: "Header", data() { return { this_nav: "", } }, created() { this.this_nav = localStorage.this_nav; }, methods: { jump(location) { localStorage.this_nav = location; // vue-router除了提供router-link标签跳转页面以外,还提供了 js跳转的方式 this.$router.push(location); } } } </script> <style scoped> .header-box { height: 80px; } .header { width: 100%; height: 80px; box-shadow: 0 0.5px 0.5px 0 #c9c9c9; position: fixed; top: 0; left: 0; right: 0; margin: auto; z-index: 99; background: #fff; } .header .content { max-width: 1200px; width: 100%; margin: 0 auto; } .header .content .logo { height: 80px; line-height: 80px; margin-right: 50px; cursor: pointer; /* 设置光标的形状为爪子 */ } .header .content .logo img { vertical-align: middle; } .header .nav li { float: left; height: 80px; line-height: 80px; margin-right: 30px; font-size: 16px; color: #4a4a4a; cursor: pointer; } .header .nav li span { padding-bottom: 16px; padding-left: 5px; padding-right: 5px; } .header .nav li span a { display: inline-block; } .header .nav li .this { color: #4a4a4a; border-bottom: 4px solid #ffc210; } .header .nav li:hover span { color: #000; } .header .login-bar { height: 80px; } .header .login-bar .shop-cart { margin-right: 20px; border-radius: 17px; background: #f7f7f7; cursor: pointer; font-size: 14px; height: 28px; width: 88px; margin-top: 30px; line-height: 32px; text-align: center; } .header .login-bar .shop-cart:hover { background: #f0f0f0; } .header .login-bar .shop-cart img { width: 15px; margin-right: 4px; margin-left: 6px; } .header .login-bar .shop-cart span { margin-right: 6px; } .header .login-bar .login-box { margin-top: 33px; } .header .login-bar .login-box span { color: #4a4a4a; cursor: pointer; } .header .login-bar .login-box span:hover { color: #000000; } /* 工具的全局样式 */ .full-left { float: left !important; } .full-right { float: right !important; } /*[class*=" el-icon-"], [class^=el-icon-] { font-size: 50px; }*/ .el-carousel__arrow { width: 120px; height: 120px; } .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner { background: #ffc210; border-color: #ffc210; border: none; } .el-checkbox__inner:hover { border-color: #9b9b9b; } .el-checkbox__inner { width: 16px; height: 16px; border: 1px solid #9b9b9b; border-radius: 0; } .el-checkbox__inner::after { height: 9px; width: 5px; } </style> 4.Banner.vue - 小组件 <template> <el-carousel height="520px" :interval="3000" arrow="always"> <el-carousel-item> <img src="@/assets/img/banner1.png" alt=""> </el-carousel-item> <el-carousel-item> <img src="@/assets/img/banner2.png" alt=""> </el-carousel-item> <el-carousel-item> <img src="@/assets/img/banner3.png" alt=""> </el-carousel-item> </el-carousel> </template> <!----> <script> export default { name: "Banner", } </script> <style scoped> .el-carousel__item h3 { color: #475669; font-size: 18px; opacity: 0.75; line-height: 300px; margin: 0; } .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } img { text-align: center; height: 520px; } </style> 5.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> 6.global.css - 全局样式 /* 声明全局样式和项目的初始化样式 */ body, h1, h2, h3, h4, 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, li { list-style: none; } table { border-collapse: collapse; /* 合并边框 */ } 7.图片资源见 资料 文件夹
新建home应用
1.apps目录下 >: python ../../manage.py startapp home 2.注册app INSTALLED_APPS = [ 'home' ] 3.注册子路由 # 主路由:urls.py from django.urls import include urlpatterns = [ path('home/', include('home.urls')), ] # 子路由:home/urls.py from django.urls import path, re_path urlpatterns = [ ]
home轮播图数据库
1.模型类:home/models.py from django.db import models class Banner(models.Model): """轮播图""" # upload_to 存储子目录,真实存放地址会使用配置中的MADIE_ROOT+upload_to image = models.ImageField(upload_to='banner', verbose_name='轮播图', null=True, blank=True) name = models.CharField(max_length=150, verbose_name='轮播图名称') note = models.CharField(max_length=150, verbose_name='备注信息') link = models.CharField(max_length=150, verbose_name='轮播图广告地址') orders = models.IntegerField(verbose_name='显示顺序') is_show=models.BooleanField(verbose_name="是否上架", default=False) is_delete=models.BooleanField(verbose_name="逻辑删除", default=False) class Meta: db_table = 'luffy_banner' verbose_name = '轮播图' verbose_name_plural = verbose_name def __str__(self): return self.name 2.数据迁移:外层luffyapi路径下的终端 >: python manage.py makemigrations >: python manage.py migrate 3.创建序列化类:home/serializers.py from rest_framework import serializers from .models import Banner class BannerModelSerializer(serializers.ModelSerializer): """轮播图序列化器""" class Meta: model = Banner # 序列化的目的就是反馈给外界,所以指定的字段就行,其他字段用于orm数据的筛选 fields = ["image", "link"] 4.视图模块:home/views.py from rest_framework.generics import ListAPIView from .models import Banner from luffyapi.settings import constant from .serializers import BannerModelSerializer class BannerListAPIView(ListAPIView): queryset = Banner.objects.filter(is_show=True, is_delete=False).order_by("-orders")[:constant.BANNER_LENGTH] serializer_class = BannerModelSerializer 5.主路由:urls.py urlpatterns = [ path('home/', include("home.urls")), ] #子路由:home/urls.py urlpatterns = [ path("banners/", views.BannerListAPIView.as_view()), ]
分离的前后台交互
前台处理ajax 1.安装axios cnpm install axios --save 2.src/main.js配置 import axios from 'axios' Vue.prototype.$axios = axios; 3.axios发生ajax请求 created() { this.$axios({ url:this.$settings.BASE_HTTP+'/home/banners/', method:'get', }).then(response => { window.console.log(response) }) } 后台处理跨域 1.安装:pip install django-cors-headers模块 2.在settings.py中配置 INSTALLED_APPS = [ 'corsheaders' ] 3.添加中间件 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ] 4.允许跨域源 CORS_ORIGIN_ALLOW_ALL = False 5.配置指定跨域域名 CORS_ORIGIN_WHITELIST = [ 'http://example.com' ]