常用配置
Django-MySQL-SQLite3
DATABASES = {
'default': {
'ENGINE': "django.db.backends.mysql",
'NAME': " ",
"USER": " ",
"PASSWORD": " ",
"HOST": "127.0.0.1",
"PORT": 3306,
"CHARSET": "utf8mb4",
}
}
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
VUE
jquery
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
bootstrap.css v3
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
bootstrap.js v3
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
bootstrap.css v5
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
bootstrap.js v5
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
vue.js
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
解决跨域问题
pip install django-cors-headers
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',
)
也可以在视图函数中添加
from django.http import JsonResponse
def my_view(request):
response = JsonResponse({'message': 'Hello, world!'})
response['Access-Control-Allow-Origin'] = 'http://localhost:63342'
return response
序列化字典和列表
let publishData = JSON.parse(JSON.stringify(this.publish));
let authorData = JSON.parse(JSON.stringify(this.author));
这两行代码的目的是将 Vue 实例中的 this.publish
和 this.author
这两个数据转换为普通的 JavaScript 对象,即将其从 Vue 的响应式数据对象转换为普通的 JSON 字符串,然后再解析成 JavaScript 对象。
具体来说,JSON.stringify()
方法用于将 JavaScript 对象转换为 JSON 字符串,而 JSON.parse()
方法则用于将 JSON 字符串解析为 JavaScript 对象。
因此,这两行代码的执行过程如下:
JSON.stringify(this.publish)
将 Vue 实例中的this.publish
数据转换为 JSON 字符串。JSON.parse(JSON.stringify(this.publish))
将 JSON 字符串解析为 JavaScript 对象,从而得到了publishData
对象。类似地,
JSON.stringify(this.author)
将 Vue 实例中的this.author
数据转换为 JSON 字符串。JSON.parse(JSON.stringify(this.author))
将 JSON 字符串解析为 JavaScript 对象,从而得到了authorData
对象。
这样做的目的是为了将 Vue 实例中的响应式数据转换为普通的 JavaScript 对象,以便在发送请求时能够使用普通的数据格式,并避免发送带有 Vue 的响应式数据结构的数据。
vite创建vue3集成vue-router
cnpm install vue-router -S
router/index.js
import {createRouter, createWebHashHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from "../views/AboutView.vue";
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: AboutView
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
main.js
import {createApp} from 'vue'
import App from './App.vue'
import router from "./router/index.js";
createApp(App).use(router).mount('#app')
vue3+vite集成pinia
cnpm install pinia -S
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router/index.js";
import {createPinia} from 'pinia'
const pinia = createPinia()
createApp(App).use(router).use(pinia).mount('#app')
vue3+vite集成element-plus
cnpm install element-plus -S
import {createApp} from 'vue'
import App from './App.vue'
import router from "./router/index.js";
import {createPinia} from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const pinia = createPinia()
createApp(App).use(router).use(pinia).use(ElementPlus).mount('#app')
Django-serializer
序列化获得性别
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ['name', 'age', 'gender']
gender = serializers.CharField(source='get_gender_display')
Django-DRF-纯净环境
后期如果项目的用户表,不用auth的user表,做成纯净环境
-1 删除其他app 剩下 'django.contrib.staticfiles'
-2 删除所有中间件
-3 安装drf
-4 配置
INSTALLED_APPS = [
'app01',
'rest_framework',
'django.contrib.staticfiles'
]
REST_FRAMEWORK = {
"UNAUTHENTICATED_USER": None,
}
pip换源
文件管理器文件路径地址栏敲:%APPDATA% 回车,快速进入 C:\Users\电脑用户\AppData\Roaming 文件夹中
新建 pip 文件夹并在文件夹中新建 pip.ini 配置文件
新增 pip.ini 配置文件内容
[global]
index-url = https://mirrors.aliyun.com/pypi/simple
[install]
use-mirrors =true
mirrors =https://mirrors.aliyun.com/pypi/simple
trusted-host =mirrors.aliyun.com
开启media访问
pip install pillow
在settings/dev.py中开启media访问
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
在总路由中配置
这样就可以访问到了
from django.views.static import serve
from django.conf import settings
path('media/<path:path>', serve, {'document_root': settings.MEDIA_ROOT})
# 这里访问路径就是 http://127.0.0.1:8000/media/ 后面的路径自己定
icon = models.ImageField(upload_to='icon', default='icon/default.png')
loguru
pip install loguru
from loguru import logger
logger = logger.opt()
logger.debug('这是一条debug日志')
logger.info("这是一条信息日志")
logger.warning("这是一条警告日志")
logger.error("这是一条错误日志")
utils/common_logger.py
# -*- coding: utf-8 -*-
# author : heart
# blog_url : https://www.cnblogs.com/ssrheart/
# time : 2024/5/9
from loguru import logger
# from settings.dev import BASE_DIR
import os
LOG_PATH = os.path.join('logs', 'luffy.log')
def configure_logger():
# logger.remove() # 清除默认的日志处理器 不会在控制台打印
# logger.level("CRITICAL")
# 设置Loguru日志记录器的配置
# logger.add(f"{LOG_PATH}", rotation="300 MB", level="DEBUG")
logger.add(f"{LOG_PATH}", rotation="300 MB", level='CRITICAL')
# logger.add(f"{LOG_PATH}", rotation="300 MB", level="INFO")
# 在Django启动时调用配置函数
configure_logger()
settings/dev.py
from utils import common_logger
common_logger.configure_logger()
views.py
@logger.catch
放在函数上,所有异常都会捕获
虚拟环境
使用mkvirtualenv前提是需要下载模块
配置详细 转载至:https://www.cnblogs.com/alice-cj/p/11642744.html
pip3 install virtualenv virtualenvwrapper
pip install virtualenvwrapper-win #Windows使用该命令
mkvirtualenv -p python3 xxx
pip install django==4.2.13
创建后端项目 使用命令
django-admin startproject 项目名
python中打开创建的项目,配置虚拟解释器环境
创建vite
npm create vite@latest
git
git pull --rebase origin master
get_xxx_display
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="导师身份"
)
class TeacherSerializer(serializers.ModelSerializer):
role_name = serializers.CharField(source="get_role_display", read_only=True)
class Meta:
model = Teacher
fields = ["name", "role_name", "title", "signature", "image", "brief"] # 重写
VUE3播放器
参考:https://blog.csdn.net/weixin_56709740/article/details/136855807
npm install vue-video-player video.js
main.js
import VueVideoPlayer from 'vue-video-player';
import 'video.js/dist/video-js.css';
<template>
<div style="width: 51%; height: 51%">
<video-player
class="video-player vjs-custom-skin"
ref="videoPlayer"
:playsinline="true"
:options="playerOptions"
></video-player>
</div>
</template>
<script setup>
import "video.js/dist/video-js.css";
// eslint-disable-next-line no-unused-vars
import VueVideoPlayer from "vue-video-player";
const playUrl =
"";//替换你的视频地址
const playerOptions = {
autoplay: true,//自动播放
muted: false, //静音播放
loop: false, //循环播放
preload: "auto", //预加载
language: "zh-CN", //语言
aspectRatio: "16:9", //宽高比
fluid: true, //父容器的大小而自适应
sources: [
{
type: "",
src: playUrl,
},
],
notSupportedMessage: "此视频暂无法播放,请稍后再试",
controls: true, // 视频播放器的控制条
controlBar: {
timeDivider: true,
durationDisplay: true,
remainingTimeDisplay: false,
fullscreenToggle: true, // 全屏播放
playToggle: true, // 播放/暂停
volumePanel: true, // 音量控制
qualitySelector: true, // 清晰度选择
},
qualitySelector: {
default: "high", // 默认的清晰度
options: [
{ value: "high", label: "高清" },
{ value: "ultra", label: "超清" },
],
},
};
</script>
<style></style>
Simpleui
pip install django-simpleui
admin注册
admin.site.register()
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ("id", "username", "mobile")
小程序
tabBar
"tabBar": {
"selectedColor": "#b4282d",
"position": "bottom",
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "images/home.png",
"selectedIconPath": "images/home_select.png"
},
{
"pagePath": "pages/my/my",
"text": "我的",
"iconPath": "images/my.png",
"selectedIconPath": "images/my_select.png"
}
]
},
window
"window": {
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black",
"navigationBarTitleText": "test",
"backgroundColor": "#eeeeee",
"backgroundTextStyle": "light"
},
mysql查看隔离级别
5.7
SELECT @@tx_isolation;
8.0
SELECT @@transaction_isolation;
这两条命令都会返回当前会话的隔离级别。常见的隔离级别有:
READ-UNCOMMITTED
READ-COMMITTED
REPEATABLE-READ
SERIALIZABLE
全局异常捕获
# 异常捕获
REST_FRAMEWORK = {
"EXCEPTION_HANDLER": "utils.common_exception.exception_handler",
}
requirements
pip freeze > requirements.txt
pip install -r requirements.txt
后端gitignore
.idea
*.log
*.pyc
__pycache__
**/migrations/*.py
!**/migrations/__init__.py
.venv
scripts
db.sqlite3
.vscode
前端gitignore
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.vscode
README.md
总gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
.db
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/