luffy后台准备
后台:Django项目创建
环境
""" 为luffy项目创建一个虚拟环境 >: mkvirtualenv luffy """ """ 按照基础环境依赖 >: pip install django==2.0.7 >: pip install djangorestframework >: pip install pymysql """
创建项目
""" 前提:在目标目录新建luffy文件夹 >: cd 建立的luffy文件夹 >: django-admin startproject luffyapi 开发:用pycharm打开项目,并选择提前备好的虚拟环境 """
重构项目目录
""" ├── luffyapi ├── logs/ # 项目运行时/开发时日志目录 - 包 ├── manage.py # 脚本文件 ├── luffyapi/ # 项目主应用,开发时的代码保存 - 包 ├── apps/ # 开发者的代码保存目录,以模块[子应用]为目录保存 - 包 ├── libs/ # 第三方类库的保存目录[第三方组件、模块] - 包 ├── settings/ # 配置目录 - 包 ├── dev.py # 项目开发时的本地配置 └── prod.py # 项目上线时的运行配置 ├── urls.py # 总路由 └── utils/ # 多个模块[子应用]的公共函数类库[自己开发的组件] └── scripts/ # 保存项目运营时的脚本文件 - 文件夹 """
配置开发环境
""" 1.修改 wsgi.py 与 manage.py 两个文件: # manage.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev') # wsgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.prod') # manage_prod.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.prod') 2.将settings.py删除或改名,内容拷贝到settings/dev.py中 3.修改dev.py文件内容 LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_TZ = False 4.修改启动配置:见插图 5.在任何一个__init__.py文件中测试默认配置文件是否是dev.py文件 from django.conf import settings print(settings) """
环境变量
dev.py
# 环境变量操作:小luffyapiBASE_DIR与apps文件夹都要添加到环境变量 import sys sys.path.insert(0, BASE_DIR) APPS_DIR = os.path.join(BASE_DIR, 'apps') sys.path.insert(1, APPS_DIR)
在写项目直接导入utils文件夹也不’’错误提示’’
封装logger
dev.py
# 真实项目上线后,日志文件打印级别不能过低,因为一次日志记录就是一次文件io操作 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': 10, # 日志格式:详细格式 'formatter': 'verbose', # 文件内容编码 'encoding': 'utf-8' }, }, # 日志对象 'loggers': { 'django': { 'handlers': ['console', 'file'], 'propagate': True, # 是否让日志信息继续冒泡给其他的日志处理系统 }, } }
utils/logging.py
import logging logger = logging.getLogger('django')
封装项目异常处理
utils/exception.py
from rest_framework.views import exception_handler as drf_exception_handler from rest_framework.views import Response from rest_framework import status from utils.logging import logger import logging logging.getLogger('django') def exception_handler(exc, context): response = drf_exception_handler(exc, context) if response is None: # 记录服务器异常 logger.critical('%s' % exc) response = Response({'detail': '服务器异常,请重试...'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response
settings.py
REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'utils.exception.exception_handler', }
二次封装Response模块
utils/response.py
from rest_framework.response import Response class APIResponse(Response): def __init__(self, status=0, msg='ok', http_status=None, headers=None, exception=False, **kwargs): data = { 'status': status, 'msg': msg, } if kwargs: data.update(kwargs) super().__init__(data=data, status=http_status, headers=headers, exception=exception)
路由组件配置
utils/router.py
from rest_framework.routers import Route, DynamicRoute, SimpleRouter as DRFSimpleRouter class SimpleRouter(DRFSimpleRouter): routes = [ # List route. /资源s/ Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', # 群查 'post': 'create', # 单增、群增 'put': 'multiple_update', # 群整改 'patch': 'multiple_partial_update', # 群局改 'delete': 'multiple_destroy', # 群删 }, name='{basename}-list', detail=False, initkwargs={'suffix': 'List'} ), # Dynamically generated list routes. Generated using # @action(detail=False) decorator on methods of the viewset. DynamicRoute( url=r'^{prefix}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=False, initkwargs={} ), # Detail route. /资源s/(pk)/ Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', # 单查 'put': 'update', # 单整改 'patch': 'partial_update', # 单局改 'delete': 'destroy' # 单删 }, name='{basename}-detail', detail=True, initkwargs={'suffix': 'Instance'} ), # Dynamically generated detail routes. Generated using # @action(detail=True) decorator on methods of the viewset. DynamicRoute( url=r'^{prefix}/{lookup}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=True, initkwargs={} ), ] # 对外提供十大接口的router对象 router = SimpleRouter() # eg: router.register('users', UserModelViewSet, basename='user') """ /users/ 'get': 'list', # 群查 'post': 'create', # 单增、群增 'put': 'multiple_update', # 群整改 'patch': 'multiple_partial_update', # 群局改 'delete': 'multiple_destroy', # 群删 /users/(pk)/ 'get': 'retrieve', # 单查 'put': 'update', # 单整改 'patch': 'partial_update', # 单局改 'delete': 'destroy' # 单删 """
数据库配置
创建数据库
""" 1.管理员连接数据库 >: mysql -uroot -proot 2.创建数据库 >: create database luffy default charset=utf8; 3.查看用户 >: select user,host,password from mysql.user; # 5.7往后的版本 >: select user,host,authentication_string from mysql.user; """
为指定数据库配置指定账户
""" 设置权限账号密码 # 授权账号命令:grant 权限(create, update) on 库.表 to '账号'@'host' identified by '密码' 1.配置任意ip都可以连入数据库的账户 >: grant all privileges on luffy.* to 'luffy'@'%' identified by 'Luffy123?'; 2.由于数据库版本的问题,可能本地还连接不上,就给本地用户单独配置 >: grant all privileges on luffy.* to 'luffy'@'localhost' identified by 'Luffy123?'; 3.刷新一下权限 >: flush privileges; 只能操作luffy数据库的账户 账号:luffy 密码:Luffy123? """
配置文件配置
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'luffy', 'USER': 'luffy', 'PASSWORD': 'Luffy123?', 'HOST': 'localhost', 'PORT': 3306 } } import pymysql pymysql.install_as_MySQLdb()
Django 2.x 一些版本pymysql兼容问题
Django不采用2.0.7版本很可能出现以下问题,需要修改源代码
user模块User表
创建user模块
前提:在 luffy 虚拟环境下 1.终端从项目根目录进入apps目录 >: cd luffyapi & cd apps 2.创建app >: python ../../manage.py startapp user
创建User表对应的model:user/models.py
from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): mobile = models.CharField(max_length=11, unique=True) # 需要pillow包的支持 icon = models.ImageField(upload_to='icon', default='icon/default.png') class Meta: db_table = 'luffy_user' verbose_name = '用户表' verbose_name_plural = verbose_name def __str__(self): return self.username
注册user模块,配置User表:dev.py
INSTALLED_APPS = [ # ... 'user', ] # 自定义User表 AUTH_USER_MODEL = 'user.User'
配置media
media配置:dev.py
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
media目录配置
""" ├── luffyapi └── luffyapi/ └── media/ └── icon └── default.png """
主路由:luffyapi/urls.py
from django.contrib import admin from django.urls import path, re_path, include from django.views.static import serve from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('user/', include('user.urls')), re_path('^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}) ]
子路由:user/urls.py
from django.urls import path, include from utils.router import router # 注册ViewSet的路由 # router.register() urlpatterns = [ path('', include(router.urls)), ]
数据库迁移
""" 1)去向大luffyapi所在目录的终端 2)安装pillow模块 pip install pillow 3)数据库迁移 python manage.py makemigrations python manage.py migrate """
后台主页模块设计
home模块
创建home模块
前提:在 luffy 虚拟环境下 1.终端从项目根目录进入apps目录 >: cd luffyapi & cd apps 2.创建app >: python ../../manage.py startapp home
路由分发
主路由:luffyapi/urls.py
from django.urls import path, re_path, include urlpatterns = [ # ... path('home/', include('home.urls')), # ... ]
子路由:home/urls.py
from django.urls import path, re_path urlpatterns = [ ]
Banner数据表model设计
utils/model.py
from django.db import models class BaseModel(models.Model): created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') updated_time = models.DateTimeField(auto_now=True, verbose_name='最后更新时间') is_delete = models.BooleanField(default=False, verbose_name='是否删除') is_show = models.BooleanField(default=True, verbose_name='是否上架') orders = models.IntegerField(verbose_name='优先级') class Meta: abstract = True
home/models.py
from django.db import models from utils.model import BaseModel class Banner(BaseModel): title = models.CharField(max_length=16, unique=True, verbose_name='名称') image = models.ImageField(upload_to='banner', verbose_name='图片') link = models.CharField(max_length=64, verbose_name='跳转链接') info = models.TextField(verbose_name='详情') # 也可以用详情表,宽高出处 class Meta: db_table = 'luffy_banner' verbose_name_plural = '轮播图表' def __str__(self): return self.title
数据迁移:在大luffyapi路径下的终端
>: python manage.py makemigrations
>: python manage.py migrate
注册home模块:dev.py
INSTALLED_APPS = [ # ... 'rest_framework', 'home', ]
设计Banner数据接口
home/serializers.py
from rest_framework import serializers from . import models class BannerSerializer(serializers.ModelSerializer): class Meta: model = models.Banner fields = ['title', 'image', 'link']
home/views.py
from rest_framework.viewsets import ModelViewSet from rest_framework import mixins from . import models, serializers class BannerViewSet(ModelViewSet, mixins.ListModelMixin): queryset = models.Banner.objects.filter(is_delete=False, is_show=True).all() serializer_class = serializers.BannerSerializer
home/urls.py
from django.urls import path, include from utils.router import router from . import views # 注册ViewSet的路由 router.register('banners', views.BannerViewSet, 'banner') urlpatterns = [ path('', include(router.urls)), ]
接口
http://localhost:8000/home/banners/
xadmin后台管理
安装:luffy虚拟环境下
>: pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2
注册app:dev.py
INSTALLED_APPS = [ # ... # xadmin主体模块 'xadmin', # 渲染表格模块 'crispy_forms', # 为模型通过版本控制,可以回滚数据 'reversion', ]
xadmin:需要自己的数据库模型类,完成数据库迁移
python manage.py makemigrations
python manage.py migrate
设置主路由替换掉admin:主urls.py
# xadmin的依赖 import xadmin xadmin.autodiscover() # xversion模块自动注册需要版本控制的 Model from xadmin.plugins import xversion xversion.register_models() urlpatterns = [ # ... path(r'xadmin/', xadmin.site.urls), ]
创建超级用户:大luffyapi路径终端
# 在项目根目录下的终端 python manage.py createsuperuser # 账号密码设置:admin | Admin123
完成xadmin全局配置:新建home/adminx.py
# home/adminx.py # xadmin全局配置 import xadmin from xadmin import views class GlobalSettings(object): """xadmin的全局配置""" site_title = "路飞学城" # 设置站点标题 site_footer = "路飞学城有限公司" # 设置站点的页脚 menu_style = "accordion" # 设置菜单折叠 xadmin.site.register(views.CommAdminView, GlobalSettings)
在adminx.py中注册model:home/adminx.py
from . import models # 注册 xadmin.site.register(models.Banner)
分离的前后台交互
后台处理跨域
安装插件
>: pip install django-cors-headers
插件参考地址:https://github.com/ottoyiu/django-cors-headers/
项目配置:dev.py
# 注册app INSTALLED_APPS = [ ... 'corsheaders', ] # 添加中间件 MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] # 允许跨域源 CORS_ORIGIN_ALLOW_ALL = True # 允许的请求头 CORS_ALLOW_HEADERS = ( "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", # 额外允许的请求头 'token', )
前台请求Banner数据
修订Banner.vue
<template> <div class="banner"> <!-- <el-carousel height="400px">--> <!-- <el-carousel-item v-for="item in 4" :key="item">--> <!-- <img src="../assets/img/banner1.png" alt="">--> <!-- </el-carousel-item>--> <!-- </el-carousel>--> <el-carousel height="400px"> <el-carousel-item v-for="banner in banner_list" :key="banner.title"> <router-link :to="banner.link"> <img :src="banner.image" alt=""> </router-link> </el-carousel-item> </el-carousel> </div> </template> <script> export default { name: "Banner", data() { return { banner_list: [] } }, // 在created钩子中 created() { this.$axios({ url: this.$settings.base_url + '/home/banners/', headers: { // 测试前台给后台提交请求头 // authorization: 'jwt abc.def.xyz', // token: 'jwt abc.def.xyz', } }).then(response => { console.log(response.data); this.banner_list = response.data; }).catch(error => { console.log(">>>", error); }) } } </script> <style scoped> .el-carousel__item { height: 400px; min-width: 1200px; } .el-carousel__item img { height: 400px; margin-left: calc(50% - 1920px / 2); } </style>
自定义常量配置文件:settings/const.py
# 自定义的常量配置文件,在settings中 from 该文件 import *,将名字全部丢给settings BANNER_COUNT = 4
加载自定义配置名称空间:settings/dev.py
# 加载自定义配置名称空间 from .const import *
在轮播图接口中应用:banner/views.py
class BannerViewSet(ModelViewSet, mixins.ListModelMixin): queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('-orders')[:settings.BANNER_COUNT] serializer_class = serializers.BannerSerializer