1.Django安装及设置:
1.1 安装Django
pip install Django==4.1 -i https://pypi.douban.com/simple
1.2 创建Django项目
django-admin startproject web
1.3 创建应用
python manage.py startapp user
1.4 在项目路径下的settings,将应用添加到项目中
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'user',
]
1.5 在应用下新建数据库模型(models.py),并在数据库中建立
class User(models.Model):
name = models.CharField('用户名', max_length=20)
pwd = models.CharField('密码', max_length=20)
email = models.EmailField('邮箱')
# tel = models.CharField('手机号', max_length=20)
level = models.IntegerField('权限', default=0)
is_active = models.BooleanField('激活', default=False)
create_time = models.DateTimeField('创建事件', auto_now=True)
def __str__(self):
return f'{self.name}, {self.email}'
class Meta:
db_table = 'user'
在数据库中创建相应的表格:
python manage.py makemigrations
python manage.py migrate
1.6 在项目url和应用url中新建连接,用于访问时能转到相应的views里
# 主urls中设置
urlpatterns = [
path('admin/', include('user.urls')),
path('download/', include('download.urls')),
path('need/', include('business.urls')),
path('', TemplateView.as_view(template_name="index.html"))
]
# 应用url中设置
urlpatterns = [
path('login', views.userLogin), # 用户登入
path('register', views.userRegister), # 用户注册
path('verify', views.userVerify), # 验证码请求
]
1.7 应用Views中处理逻辑代码,并返回相应的数据
def userLogin(request):
res = {'msg': '', 'user': {}}
if request.method == "POST":
body = json.loads(request.body)
name = body['name']
pwd = body['pwd']
md5_pwd = md5(pwd.encode('utf-8')).hexdigest()
re_c = re.compile(r'(.*)@\w+\.com$')
res = re.match(re_c, name, re.I)
if res:
try:
user = User.objects.get(email=name)
res['user'] = user.value()
if user.pwd == md5_pwd:
res['msg'] = 'ok'
return JsonResponse(res)
except:
res['msg'] = '用户名或密码错误'
return JsonResponse(res)
else:
res['msg'] = '用户不存在'
return JsonResponse(res)
if request.method == 'GET':
name = request.GET.get('name')
print(name)
return HttpResponse('ok')
1.8 启动项目进行验证
python manage.py runserver 8002
1.9 配置静态文件夹
# 在settins中配置
STATIC_URL = 'static/'
STATICFILES_DIRS = (BASE_DIR / 'framework/dist/static',)
1.10 配置上传文件夹
# settings中配置
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR / 'media')
# 在主url中配置
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
1.11 用redis作为缓存数据库
# 安装redis数据库 添加环境变量
# 安装包pip install django-redis
# settings进行设置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache", # 使用django-redis的缓存
"LOCATION": "redis://127.0.0.1:6379/0", # redis数据库的位置
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 300},
"DECODE_RESPONSES": True, # 自动将byte转成字符串
# "PASSWORD": "", # 设置密码
}
}
}
REDIS_TIMEOUT = 7 * 24 * 60 * 60 # 缓存超时
CUBES_REDIS_TIMEOUT = 60 * 60
NEVER_REDIS_TIMEOUT = 365 * 24 * 60 * 60
# 编写缓存前缀函数
def cache_line_info(fn):
def inner(request, *args, **kwargs):
body = json.loads(request.body)
line_id = body['line_id'] # 获取产线id
if not cache.has_key(str(line_id) + 'stations'):
stations = Station.objects.filter(line_id=line_id) # 获取工位信息
# 获取启示站和结束站
list_first = stations.filter(Num=0)
list_last = stations.filter(Num=100)
today = datetime.date.today()
today_status = StationStatus.objects.filter(Q(create_time__contains=today) & Q(station__in=stations))
first_status = today_status.filter(station__in=list_first)
last_status = today_status.filter(station__in=list_last)
cache.set(str(line_id) + 'stations', stations) # 将工位数据存储到缓存中
cache.set(str(line_id) + 'first_status', first_status) # 将第一站状态存储到缓存中
cache.set(str(line_id) + 'last_status', last_status) # 将最后一战状态存储到缓存中
cache.set(str(line_id) + 'today_status', today_status) # 将当天状态存储到缓存中
return fn(request, *args, **kwargs)
return inner
2.MySQL安装及使用:
2.1 安装mysql
具体步骤如下:保姆级别安装教程--好用
2.2 安装mysql workbench方便增、删、改、查
具体步骤如下:安装及使用教程
2.3 新建数据库 web_db
3.Django与MySQL建立连接:
3.1 安装mysql驱动,用于Django访问mySQL
pip install pymysql -i https://pypi.douban.com/simple
pip install mysqlclient -i https://pypi.douban.com/simple
3.2 Django中设置建立关系
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'web_db', # 数据库名称
'USER': 'root', # 访问用户名
'PASSWORD': '123456', # 访问密码
'HOST': 'localhost', # 访问路径
'POST': '3306' # 访问端口
}
}
3.3 用Django指令新建数据库表格, 若新建成功,说明已经建立好连接
python manage.py makemigrations
python manage.py migrate
3.4 如果报错可安装下面包
pip install cryptography -i https://pypi.douban.com/simple
4.Vue安装及使用:
4.1 安装node.js
4.2 安装vue.js及其他依赖, -g表示安装到全局目录中
npm install vue -g
npm install webpack -g
npm install yarn -g
npm install webpack-cli -g
4.3 安装路由,vue-router
npm install vue-router -g
4.4 安装vue脚手架
npm install vue-cli -g
4.5 新建vue项目
vue init webpack Web
4.6 运行npm run dev查看是否能运行
详细的操作流程可查看:Vue安装及使用
5.引用element-ui、echarts、axios、VueX、router便于开发
5.1 安装element-ui
npm i element-ui -S
5.2 在Vue中进行配置element
import ElementUI from 'element-ui';
Vue.use(ElementUI);
5.3 安装echars
npm install echarts --save
5.4 在Vue中配置echarts
import echarts from 'echarts'
//需要挂载到Vue原型上
Vue.prototype.$echarts = echarts
5.5 安装axios用于前后端通信(Django与Vue通信)
npm install axios
5.6 在Vue进行配置
import Axios from 'axios'
Vue.prototype.$http = Axios
Axios.defaults.baseURL = 'http://127.0.0.1:80'; # 配置默认访问主URl
5.7 配置使用VueX,用于Vue组件之间数据交互(缓存在内存)
# 新建store文件夹
# 新建index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { // 存放数据 和data类似
},
mutations: { // 用来修改state和getters里面的数据
},
getters: { // 相当于计算属性
},
actions: { // vuex中用于发起异步请求
},
modules: {// 拆分模块
}
})
5.8 在Vue中配置VueX
import store from './store'
new Vue({
el: '#app',
router,
store, # 引用VueX
render: h => h(App),
components: {App},
template: '<App/>',
})
5.9 配置router
# 新建router文件夹
# 新建index.js
import Vue from 'vue'
import Router from 'vue-router'
import Index from "../components";
import Product from "../components/Product";
import Scheme from "../components/Scheme";
import Information from "../components/Information";
import Download from "../components/Download";
import Technology from "../components/Technology";
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'index',
component: Index
},
{
path: '/product',
name: 'product',
component: Product
},
{
path: '/scheme',
name: 'scheme',
component: Scheme
},
{
path: '/information',
name: 'information',
component: Information
},
{
path: '/download',
name: 'download',
component: Download
},
{
path: '/technology',
name: 'technology',
component: Technology
},
]
})
5.10 在Vue中配置router
import router from './router'
new Vue({
el: '#app',
router, # 引用路由
store,
render: h => h(App),
components: {App},
template: '<App/>',
})
6.将Vue挂到Django中
6.1 安装连接包
pip install django-cors-headers -i https://pypi.douban.com/simple
6.2 在Django进行配置
# settings中配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'user',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'web/dist'], # 配置Vue路径
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# 在主url中进行配置
from django.views.generic import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name="index.html"))
]
详细操作可查看:VUE+Django
7. Apache配置
7.1 下载apache
7.2 修改conf中的httpd.conf文件
Define SRVROOT "D:/Apache24" # apacha的存放路径
7.3 安装apache
# cmd进入到bin目录下
httpd.exe -k install
# 启动
net start apache2.4
# 停止
net stop apache2.4
# 删除
net delete apache2.4
7.4 安装mod-wsgi并进行配置
7.5 修改apache中的httpd.conf文件
# mod-wsgi-express module-config获取config信息填写到httpd.conf配置文件中
LoadFile "D:/Program Files/Python310/python310.dll"
LoadModule wsgi_module "D:/Program Files/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd"
WSGIPythonHome "D:/Program Files/Python310"
# django项目中的wsgi.py文件路径
WSGIScriptAlias / D:\M_WEB\M_WEB\wsgi.py
# django项目路径
WSGIPythonPath D:\M_WEB
# 设置wsgi.py文件权限
<Directory D:\M_WEB\M_WEB>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
# 静态文件访问
Alias /static D:\M_WEB\framework\dist\static
<Directory D:\M_WEB\framework\dist\static>
AllowOverride None
Options None
Require all granted
</Directory>
# 上传文件访问
Alias /media D:\M_WEB\media
<Directory D:\M_WEB\media>
AllowOverride None
Options None
Require all granted
</Directory>
7.6 重启apache详细
详细操作可查看:Apache部署