一、luffy后台配置之封装logger
1.1 导入日志配置文件
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 ,
} ,
}
}
1.2 utils下新建common_logger.py
import logging
logger = logging. getLogger( 'django' )
1.3 日志功能测试
urls.py
from django. contrib import admin
from django. urls import path
from home import views
urlpatterns = [
path( 'admin/' , admin. site. urls) ,
path( 'test/' , views. test) ,
]
views.py
from django. shortcuts import render, HttpResponse
from utils. common_logger import logger
def test ( request) :
logger. warning( '日志警告测试' )
return HttpResponse( '日志测试' )
1.4 导入模块错误解决
1.5 测试成功
二、luffy后台配置之封装全局异常
2.1 安装并注册django_rest_framework
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'rest_framework' ,
'home' ,
]
2.2 utils下新建exceptions.py
from rest_framework. views import exception_handler as drf_exception_handler
from rest_framework. response import Response
from utils. common_logger import logger
def exception_handler ( exc, context) :
request = context. get( 'request' )
try :
user_id = request. useruser. pk
if not user_id:
user_id = '匿名用户'
except :
user_id = '匿名用户'
view = context. get( 'view' )
logger. error( '用户:【%s】, 使用:【%s】 请求, 请求了:【%s】地址,视图函数是:【%s】,访问时发生了错误,错误类型是:【%s】' % (
user_id, request. method, request. get_full_path( ) , str ( view) , str ( exc)
) )
info = drf_exception_handler( exc, context)
if info:
info = Response( data= { 'code' : 503 , 'msg' : info. data. get( 'detail' , '服务器内部发生错误,请联系管理员' ) } )
else :
info = Response( data= { 'code' : 501 , 'msg' : str ( exc) } )
return info
2.3 配置文件中添加以下内容
REST_FRAMEWORK = {
'EXCEPTION_HANDLER' : 'utils.exceptions.exception_handler' ,
}
2.4 全局异常测试
urls.py
from django. contrib import admin
from django. urls import path
from home import views
urlpatterns = [
path( 'admin/' , admin. site. urls) ,
path( 'test/' , views. test) ,
path( 'testview/' , views. TestView. as_view( ) ) ,
]
views.py
from django. shortcuts import render, HttpResponse
from rest_framework. views import APIView
from utils. common_logger import logger
from rest_framework. response import Response
def test ( request) :
logger. warning( '日志警告测试' )
return HttpResponse( '日志测试' )
class TestView ( APIView) :
def get ( self, request) :
l1 = [ 6 , 7 , 8 ]
print ( l1[ 6 ] )
return Response( 'okk' )
2.5 测试成功
三、luffy后台配置之二次封装response
3.1 utils下新建response.py
from rest_framework. response import Response
class APIResponse ( Response) :
def __init__ ( self, code= 200 , msg= '响应成功' , status= None , headers= None , ** kwargs) :
data = { 'code' : code, 'msg' : msg}
if kwargs:
data. update( kwargs)
super ( ) . __init__( data= data, status= status, headers= headers)
3.2 验证测试
views.py
from utils. response import APIResponse
class TestView ( APIView) :
def get ( self, request) :
return APIResponse( result= '13da6bfa355964dn66dab9345fd' )
四、luffy数据库配置
4.1 使用root用户连接数据库
mysql - uroot - p
4.2 创建luffy项目数据库
create database luffy default charset= utf8mb4;
show databases;
4.3 创建luffy项目用户并授权
设置权限账号密码
1. 配置任意ip都可以连入数据库的账户
> : grant all privileges on luffy. * to 'luffy_api' @'%' identified by '*****' ;
2. 由于数据库版本的问题,可能本地还连接不上,就给本地用户单独配置
> : grant all privileges on luffy. * to 'luffy_api' @'localhost' identified by '*****' ;
3. 刷新一下权限
> : flush privileges;
4.4 查看创建成功的用户
select user, host from mysql. user;
4.5 使用创建的用户登录
mysql - uluffy_api - p
4.7 在配置文件中修改数据库配置
DATABASES = {
'default' : {
'ENGINE' : 'django.db.backends.mysql' ,
'NAME' : 'luffy' ,
'USER' : 'luffy_api' ,
'PASSWORD' : '****** ' ,
'HOST' : '127.0.0.1' ,
'PORT' : 3306 ,
}
}
4.8 为避免密码泄露风险,做出以下配置
import os
user = os. environ. get( 'USER' , 'luffy_api' )
password = os. environ. get( 'PWD' , '******' )
DATABASES = {
'default' : {
'ENGINE' : 'django.db.backends.mysql' ,
'NAME' : 'luffy' ,
'USER' : user,
'PASSWORD' : password,
'HOST' : '127.0.0.1' ,
'PORT' : 3306 ,
}
}
4.9 安装mysqlclient
import pymysql
pymysql. install_as_MySQLdb( )
https: // liuqingzheng. top/ python/ Python并发编程/ 24 - 协程之gevent模块/
五、luffy User表配置
5.1 创建一个用户app
python . . / . . / manage. py startapp user
5.2 在user下的models.py中继承Auth表扩写字段
from django. db import models
from django. contrib. auth. models import AbstractUser
class UserInfo ( AbstractUser) :
mobile = models. CharField( max_length= 32 , 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
5.3 在配置文件中添加配置并注册app
AUTH_USER_MODEL= 'user.UserInfo'
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'rest_framework' ,
'home' ,
'user' ,
]
5.4 安装pillow模块
pip install pillow
5.5 执行数据库迁移命令
python manage. py makemigrations
python manage. py migrate
6.1 在配置文件中添加以下内容
MEDIA_URL = '/media/'
MEDIA_ROOT = os. path. join( BASE_DIR, 'media' )
6.3 在urls.py中配置路由
from django. contrib import admin
from django. urls import path
from home import views
from django. views. static import serve
from django. conf import settings
urlpatterns = [
path( 'admin/' , admin. site. urls) ,
path( 'test/' , views. test) ,
path( 'testview/' , views. TestView. as_view( ) ) ,
path( 'media/<path:path>' , serve, kwargs= { 'document_root' : settings. MEDIA_ROOT} ) ,
]
6.4 本地访问测试
七、luffy前台项目创建和配置
7.1 创建Vue项目
vue create luffy_city
File- - - - - - > open - - - - - - - - > luffy_city- - - - - - - - - - - > ok
7.2 运行vue项目
7.3 修改vue相关配置
# App.vue中只保留
<template>
<div id="app">
<router-view/>
</div>
</template>
# HomeView.vue
<template>
<div class="home">
<h1>首页</h1>
</div>
</template>
<script>
export default {
name: 'HomeView',
}
</script>
# router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
7.4 安装配置axios
cnpm install axios
import axios from 'axios'
Vue. prototype. $axios= axios
this. $axios. get( )
7.5 安装配置elementui
cnpm i element- ui - S
import ElementUI from 'element-ui' ;
import 'element-ui/lib/theme-chalk/index.css' ;
Vue. use( ElementUI) ;
(template,script,style)
7.6 引入bootstrap,jQuery样式
1 安装
cnpm install jquery - S
cnpm install bootstrap@3 - S
2 配置:main. js
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
3 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" ]
} )
]
}
} ;
7.7 安装配置Vue-cookies
cnpm install vue- cookies - S
import cookies from 'vue-cookies'
Vue. prototype. $cookies= cookies
this. $cookies. set ( )
八、mysql拓展知识
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
MySQL有两种连接方式,一种是网络监听TCP/ IP端口的模式,还有一种是socket模式。
socket模式
在Linux下,socket是一种特殊的文件,也叫做套接字,是应用层与TCP/ IP协议族通信的中间软件抽象层。虽然性能会比较好,但是这种socket模式仅限本机使用,其他机器无法通过网络链接连接到socket文件
TCP/ IP端口模式
这个就是为了让远程的应用连接到MySQL数据库的服务。
在MySQL配置中mysqld节中,可以设置绑定的对应的IP和端口,需要重启服务
如果有使用- h指定主机的都是使用远程登录的方式,如果没有就是使用socket的方式
mysql - h 127.0 .0 .1 的时候,使用TCP/ IP连接, mysql server 认为该连接来自于127.0 .0 .1 或者是 localhost. localdomain
mysql - h localhost 的时候,是不使用TCP/ IP连接的,而使用 Unix socket。此时,mysqlserver则认为该 client 是来自 localhost
mysql权限管理中的"localhost" 有特定含义:
注意: 虽然两者连接方式有区别,但当localhost为默认的127.0 .0 .1 时,两种连接方式使用的权限记录都是以下的1 . row的记录( 因为记录在前,先被匹配)
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
MySQL在5.5 .3 版本之后增加了这个utf8mb4的编码,mb4就是most bytes 4 的意思,专门用来兼容四字节的unicode 。其实,utf8mb4是utf8的超集,理论上原来使用utf8,然后将字符集修改为utf8mb4,也会不会对已有的utf8编码读取产生任何问题。当然,为了节省空间,一般情况下使用utf8也就够了。
既然utf8应付日常使用完全没有问题,那为什么还要使用utf8mb4呢? 低版本的mysql支持的utf8编码,最大字符长度为 3 字节,如果遇到 4 字节的字符就会出现错误了。
三个字节的 UTF- 8 最大能编码的 Unicode 字符是 0xFFFFFF ,也就是 Unicode 中的基本多文平面(BMP)。也就是说,任何不在基本多文平面的 Unicode字符,都无法使用MySQL原有的 utf8 字符集存储。
这些不在BMP中的字符包括哪些呢?最常见的就是Emoji 表情(Emoji 是一种特殊的 Unicode 编码,常见于IOS和Android手机上),和一些不常用的汉字,以及任何新增的 Unicode 字符等等。
理论上将, UTF- 8 格式使用一至六个字节编码字符。最新的 UTF- 8 规范只使用一到四个字节,正好能够表示所有的 17 个 Unicode 平面。
而utf8 则是 Mysql 早期版本中支持的一种字符集,只支持最长三个字节的 UTF- 8 字符,也就是 Unicode 中的基本多文本平面。在MySQL5. 5.3 版本后,要在 Mysql 中保存 4 字节长度的 UTF- 8 字符,就可以使用 utf8mb4 字符集了。例如可以用utf8mb4字符编码直接存储emoj表情,而不是存表情的替换字符。
为了获取更好的兼容性,应该总是使用 utf8mb4 而非 utf8. 对于 CHAR 类型数据,utf8mb4 会多消耗一些空间,根据 Mysql 官方建议,使用 VARCHAR 替代 CHAR。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)