这里写目录标题
- 一.昨日回顾
- 二.今日内容
- 1 路飞前台配置
- (1)重构项目目录
- (2)文件修订:目录中非配置文件的多余文件可以移除
-
- (3)前台配置
- ①全局样式,配置文件
- ②axios
- ③vue-cookies
- ④element-ui页面组件框架
- ⑤bootstrap页面组件框架
- 2 user表配置
-
- 3 封装全局response对象和全局异常
-
- 4.配置日志,记录日志
-
- 5.跨域问题及解决
- django 使用django-cors-headers 解决跨域问题
- 6.前后端打通
- 7.扩展
一.昨日回顾
1 软件开发规范
2 pip换源
-1.文件管理器文件路径地址栏敲: %APPDATA% 回车,快速进入C:\Users\电脑用户\AppData\Roaming 文件夹中
-2.新建pip文件夹并在文件夹中新建pip.ini配置文件
-3.新增pip.ini配置文件内容
3 虚拟环境(以后再写新项目,直接用虚拟环境,尽量一个项目一个虚拟环境)
-1 配置
-windows下
-pip3 install virtualenv
-pip3 install virtualenvwrapper-win
-环境变量:WORKON_HOME: D:\Virtualenvs
-Linux,mac
-pip3 install virtualenv
-pip3 install virtualenvwrapper
VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
source /usr/local/bin/virtualenvwrapper.sh
source ~/.bash_profile
-2.命令
mkvirtualenv -p python3.6 虚拟环境名称
4 路飞后台
-django-admin命令创建项目
-目录调整
luffyapi
-manage.py
-scripts
-logs
-luffyapi
-urls.py
-settings
-dev.py
-pro.py
-libs
-utils
-wsgi.py
-apps
-user
-course
-home
-调整完能运行
-django启动是依据settings.py启动,配置文件路径配置正确
-wsgi.py 后期上线要改
-把项目根路径加入环境变量(导入模块,基于小luffyapi文件夹导入)
-把apps文件夹加入到环境变量(在配置文件中,注册app时候,直接写名字即可)
-pycharm中导入报错(实质没错),把加入环境变量的文件夹作为了source root
5 数据库配置
-创建数据库用户,授予luffy这个库的所有权限,创建luffy用户,密码是Luffy123?
grant all privileges on luffy.* to 'luffy'@'%' identified by 'Luffy123?';
grant all privileges on luffy.* to 'luffy'@'localhost' identified by 'Luffy123?';
flush privileges;
-在django配置文件中
import os
user=os.environ.get('db_user','root')
password=os.environ.get('db_password','123')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'luffy',
'USER': user,
'PASSWORD': password,
'HOST': 'localhost',
'PORT': 3306
}
}
import pymysql
pymysql.install_as_MySQLdb()
-使用环境变量配置数据库的用户名和密码
import os
user=os.environ.get('db_user')
password=os.environ.get('db_password')
6 前端创建项目
-vue create luffycity
-配置运行
二.今日内容
1 路飞前台配置
1 node_models 文件夹内放了一堆当前项目的依赖(可以直接删掉:传git,给别人)
2 如果项目中没有这个文件夹
cnpm install (== pip3 install -r req.txt)安装项目依赖
3 目录介绍
luffycity
-node_modules
-public
-index.html
-favicon.ico
-src
main.js
components
views
assets
store
router
App.vue
babel.config.js
package.json
package-lock.json
.gitignore
.editorconfig
README.md
(1)重构项目目录
"""
├── luffycity
├── public/ # 项目共有资源
├── favicon.ico # 站点图标
└── index.html # 主页
├── src/ # 项目主应用,开发时的代码保存
├── assets/ # 前台静态资源总目录
├── css/ # 自定义css样式
└── global.css # 自定义全局样式
├── js/ # 自定义js样式
└── settings.js # 自定义配置文件
└── img/ # 前台图片资源
├── components/ # 小组件目录
├── views/ # 页面组件目录
├── App.vue # 根组件
├── main.js # 入口脚本文件
├── router
└── index.js # 路由脚本文件
store
└── index.js # 仓库脚本文件
├── vue.config.js # 项目配置文件
└── *.* # 其他配置文件
"""
(2)文件修订:目录中非配置文件的多余文件可以移除
<template>
<div id="app">
<router-view/>
</div>
</template>
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/home',
redirect: '/',
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
<template>
<div class="home">
</div>
</template>
<script>
export default {
name: 'home',
components: {
},
}
</script>
router的使用
1 在要跳转的位置加(等同于原来的a标签)
<router-link to="/">首页</router-link>
2 router文件夹 index.js
(3)前台配置
①全局样式,配置文件
'''===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:
}
ul {
list-style: none;
}
table {
border-collapse: collapse; /* 合并边框 */
}
'''===assets/js/settings.js==='''
export default {
base_url: 'http://127.0.0.1:8000'
}
'''===main.js==='''
// 配置全局样式
import '@/assets/css/global.css'
// 配置全局自定义设置
import settings from '@/assets/js/settings'
Vue.prototype.$settings = settings;
// 在所有需要与后台交互的组件中:this.$settings.base_url + '再拼接具体后台路由'
②axios
>: cnpm install axios
import axios from 'axios'
Vue.prototype.$axios = axios;
③vue-cookies
>: cnpm install vue-cookies
import cookies from 'vue-cookies'
Vue.prototype.$cookies = cookies;
④element-ui页面组件框架
>: cnpm install element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
⑤bootstrap页面组件框架
>: cnpm install jquery
>: cnpm install bootstrap@3
const webpack = require("webpack");
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"window.$": "jquery",
Popper: ["popper.js", "default"]
})
]
}
};
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
2 user表配置
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)
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',
]
AUTH_USER_MODEL = 'user.User'
配置media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
"""
├── luffyapi
└── luffyapi/
└── media/
└── icon
└── default.png
"""
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})
]
from django.urls import path, include
from utils.router import router
urlpatterns = [
path('', include(router.urls)),
]
"""
1)去向大luffyapi所在目录的终端
2)安装pillow模块
pip install pillow
3)数据库迁移
python manage.py makemigrations
python manage.py migrate
"""
3 封装全局response对象和全局异常
封装项目异常处理
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 get_logger
logger=get_logger('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
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
}
二次封装Response模块
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)
4.配置日志,记录日志
封装logger
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': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'file': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
'maxBytes': 300 * 1024 * 1024,
'backupCount': 10,
'formatter': 'verbose',
'encoding': 'utf-8'
},
},
'loggers': {
'django': {
'handlers': ['console', 'file'],
'propagate': True,
},
}
}
utils/logging.py
import logging
def get_logger(name):
logger = logging.getLogger(name)
return logger
日志的使用
1 原来在ATM中使用
def get_logger(name):
'''log日志
'''
logging.config.dictConfig(setting.LOGGING_DIC)
logger = logging.getLogger(name)
return logger
2 djaong中使用
import logging
logger = logging.getLogger('django')
5.跨域问题及解决
请求的url地址,必须与浏览器上的url地址处于同域上,也就是域名,端口,协议相同.
…
比如:我在本地上的域名是127.0.0.1:8000,请求另外一个域名:127.0.0.1:8001一段数据
…
浏览器上就会报错,这就是同源策略的保护,如果浏览器对javascript没有同源策略的保护,那么一些重要的机密网站将会很危险
1 同源策略:浏览器的安全策略,不允许向不同的域发送请求获取数据
http://127.0.0.1:8080/
http://127.0.0.1:8000/
这两个不是同一个域(地址,端口不一样,就不是一个域),发送请求,能发出去,数据也回来了
但是被浏览器的同源策略阻止了
2 前后端分离后,会存在跨域
-前端项目和后端项目跑在不同的端口上
3 解决跨域问题
-第一种:前端解决(通过代理解决)
-第二种:自己解决(自己写代码解决)
-第三种:借助第三方模块( django-cors-headers)
django 使用django-cors-headers 解决跨域问题
-1.下载
pip install django-cors-headers
-2.添加到setting的app中
INSTALLED_APPS = (
...
'corsheaders',
...
)
-3.配置中间件:
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
-4.修改配置文件:
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'http://127.0.0.1:8080',
)
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
6.前后端打通
<template>
<div id="app">
<h1>路飞开始开发了</h1>
<div class="container-fluid">
<div class="row">
<div class="col-md-7">左边</div>
<div class="col-md-5">右边</div>
</div>
</div>
<router-view/>
</div>
</template>
<script>
export default {
data () {
return {
name: ''
}
},
mounted () {
this.$axios.get(this.$settings.base_url + '/user/test/').then(res => {
console.log(res.data)
})
}
}
</script>
7.扩展
1 python获取环境变量的几种方式(django项目中配置文件,数据库用户和密码通过环境变量获取)
2 cookie,localstorage,sessionstorage区别(https://www.cnblogs.com/pengc/p/8714475.html)
3 pyechars的使用(研究一下)
4 2.2.2需要改源码的原因,你使用了pymysql来操作mysql数据库
-如果使用mysqlclient操作mysql,就不需要改源码了,并且也不需要下面2行代码了
import pymysql
pymysql.install_as_MySQLdb()
-mysqlclient安装麻烦,解决起来:http://liuqingzheng.top/python/%E5%85%B6%E4%BB%96/01-%E5%90%84%E4%B8%BB%E6%B5%81Linux%E7%B3%BB%E7%BB%9F%E8%A7%A3%E5%86%B3pip%E5%AE%89%E8%A3%85mysqlclient%E6%8A%A5%E9%94%99/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)