目录
一、 环境搭建
二、 Django
2.1 创建项目
2.2 数据库配置
2.3 创建模型并且设计数据库表 Django app :myApp
2.4 创建新增和查询的接口
三、Vue
3.1、安装脚手架vue-cli
3.2、新建前端工程项目
3.3、安装依赖包
3.4、安装ElementUI
3.5、创建vue界面
3.6、配置路由
3.7、打包并启动前端项目
四、 整合
4.1、前端vue项目调用后端引入vue-resource
4.3、增加Django路由
4.4、重新构建前端项目
五、 总结
本文主要分为五个部分,逐一进行讲解前后端分离项目环境搭建流程,主要有:环境搭建、Django、vue、整合、总结;
一、 环境搭建
**开发工具:VsCode**
下载链接:https://code.visualstudio.com/Download
安装教程:https://www.runoob.com/w3cnote/vscode-tutorial.html
**开发语言:Python**
下载链接:https://www.python.org/downloads/windows/
安装教程: https://www.runoob.com/python3/python3-install.html
**框架:Django**
下载链接:https://www.djangoproject.com/download/
安装教程:https://www.runoob.com/django/django-install.html
**Node.js**
下载链接:https://nodejs.org/en/download/
安装教程:https://www.runoob.com/nodejs/nodejs-install-setup.html
**数据库:mysql**
下载链接:https://dev.mysql.com/downloads/mysql/
安装教程:https://www.runoob.com/mysql/mysql-tutorial.html
二、 Django
2.1 创建项目
命令行:`django-admin startproject 项目名`
验证:`python manage.py runserver`
2.2 数据库配置
安装完MySQL 建好数据库
cmd窗口登录MySQL:`mysql -uroot -p `
安装python的pymysql包:`pip install pymysql`
创建数据库:`create DATABASE 数据库名称 DEFAULT CHARSET utf8;`
**配置数据库:在setting.py 查找 DATABASES**
修改数据库连接信息:
DATABASES = {
???? 'default': {
???????? # 'ENGINE': 'django.db.backends.sqlite3',
???????? # 'NAME': BASE_DIR / 'db.sqlite3',
? ???????# 自定义数据库
???????? 'ENGINE': 'django.db.backends.mysql',? # 数据库引擎
???????? 'NAME': 'Django_ElementUI',? # 数据库名称
???????? 'HOST': '127.0.0.1',? # 数据库地址,本机 ip 地址 127.0.0.1
???????? 'PORT': 3306,? # 端口
???????? 'USER': 'root',? # 数据库用户名
???????? 'PASSWORD': '',? # 数据库密码
???? }
}
**引入模块:在 __init__.py文件里增加:**
> import pymysql
> pymysql.install_as_MySQLdb()
2.3 创建模型并且设计数据库表 Django app :myApp
命令行:`python manage.py startapp myApp`
设计数据库:在myApp 文件夹内打开models.py文件
插入要创建的表内容,**注意每行缩进**
from django.db import models
# Create your models here.
class Student(models.Model):
??? student_name = models.CharField(max_length=64)
??? student_sex = models.CharField(max_length=3)
??? create_time = models.DateTimeField(auto_now_add=True)
??? def __unicode__(self):
??????? return self.Student_name
??????? return self.id
在setting.py文件,在INSTALLED_APPS中? 添加'myApp'
INSTALLED_APPS = [
??? 'django.contrib.admin',
??? 'django.contrib.auth',
??? 'django.contrib.contenttypes',
??? 'django.contrib.sessions',
??? 'django.contrib.messages',
??? 'django.contrib.staticfiles',
??? 'myApp',#添加此项
]
**在项目目录下 启动cmd 依次执行下面两句命令,生成数据库迁移文件:**
`python manage.py migrate`
`python manage.py makemigrations myApp`
**执行迁移文件 完成数据库表的创建**
`python manage.py migrate myApp`
表名:由myapp_student组成
2.4 创建新增和查询的接口
views.py
创建两个视图函数
作为接口 给前端调用
# Create your views here.
from __future__ import unicode_literals
import json
from django.core import serializers
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from myApp.models import Student
#创建view
#add_student 接受一个get请求 网数据里添加一条student 数据
@require_http_methods(["GET"])
def add_student(request):
??? response = {}
??? try:
??????? student = Student(student_name=request.GET.get('student_name'))
??????? student.save()
??????? response['msg']="success"
??????? response['error_num']=0
??? except Exception as e:
??????????? response['msg'] = str(e)
??????????? response['error_num'] = 1
??? return JsonResponse(response)
# show_students返回所有的学生列表(通过JsonResponse返回能被前端识别的json格式数据)
@require_http_methods(["GET"])
def show_students(request):
??? response = {}
??? try:
??????? students = Student.objects.filter()
??????? response['list'] = json.loads(serializers.serialize("json", students))
??????? response['msg'] = 'success'
??????? response['error_num'] = 0
??? except Exception as e:
??????? response['msg'] = str(e)
??????? response['error_num'] = 1
??? return JsonResponse(response)
配置路由
配置分支路由,myApp下新增文件:urls.py
创建分支路由,把新增的两个视图函数放进来
from django.conf.urls import url
from myApp import views
urlpatterns = [
???? url('add_student/',views.add_student),
???? url('show_students/',views.show_students),
]
将分支路由加到项目文件夹下的主路由中urls.py;
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView? # 新增
from myApp import urls
urlpatterns = [
???? url(r'^admin/',admin.site.urls),
???? url(r'^api/',include(urls)),
???? #新增
???? url(r'^$',TemplateView.as_view( template_name="index.html" ) )
]
三、Vue
?
3.1、安装脚手架vue-cli
`npm install -g vue-cli`
3.2、新建前端工程项目
`vue-init webpack 项目名称`
3.3、安装依赖包
`npm install 包名称`
3.4、安装ElementUI
`npm i element-ui -S`
3.5、创建vue界面
在src/component下,新建组件Student.vue
调用之前在Django项目里的api 实现相应的功能
<template>
? <div class="home">
??? <el-row display="margin-top:10px">
??????? <el-input v-model="input" placeholder="请输入学生姓名" style="display:inline-table; width: 30%; float:left"></el-input>
??????? <el-button type="primary" @click="addStudent()" style="float:left; margin: 2px;">新增</el-button>
??? </el-row>
??? <el-row>
??????? <el-table :data="studentList" style="width: 100%" border>
????????? <el-table-column prop="id" label="编号" min-width="100">
??????????? <template slot-scope="scope"> {{ scope.row.pk }} </template>
????????? </el-table-column>
????????? <el-table-column prop="student_name" label="姓名" min-width="100">
??????????? <template slot-scope="scope"> {{ scope.row.fields.student_name }} </template>
? ????????</el-table-column>
????????? <el-table-column prop="student_sex" label="性别" min-width="100">
??????????? <template slot-scope="scope"> {{ scope.row.fields.student_sex }} </template>
????????? </el-table-column>
????????? <el-table-column prop="add_time" label="添加时间" min-width="100">
??????????? <template slot-scope="scope"> {{ scope.row.fields.create_time }} </template>
????????? </el-table-column>
??????? </el-table>
??? </el-row>
? </div>
</template>
<script>
export default {
? name: 'Student',
? data () {
??? return {
????? input: '',
????? studentList: []
??? }
? },
? mounted: function () {
??? this.showStudents()
? },
? methods: {
??? addStudent () {
????? this.$http.get('http://127.0.0.1:8000/api/add_student?student_name=' + this.input)
??????? .then((response) => {
????????? var res = JSON.parse(response.bodyText)
????????? if (res.error_num === 0) {
??????????? this.showStudents()
????????? } else {
??????????? this.$message.error('新增学生失败,请重试')
??????????? console.log(res['msg'])
????????? }
??????? })
??? },
??? showStudents () {
????? this.$http.get('http://127.0.0.1:8000/api/show_students')
??????? .then((response) => {
????????? var res = JSON.parse(response.bodyText)
????????? console.log(res)
????????? if (res.error_num === 0) {
??????????? this.studentList = res['list']
??????????? console.log(this.studentList)
????????? } else {
??????????? this.$message.error('查询学生失败')
??????????? console.log(res['msg'])
????????? }
??????? })
??? }
? }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
? font-weight: normal;
}
ul {
? list-style-type: none;
? padding: 0;
}
li {
? display: inline-block;
? margin: 0 10px;
}
a {
? color: #42b983;
}
</style>
3.6、配置路由
appfront/router文件夹下的index.js中增加页面路由;
import HelloWorld from '@/components/HelloWorld'
import Student from '@/components/Student'
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
??? routes: [{
??????????????? path: '/HelloWorld',
??????????????? name: 'HelloWorld',
??????????????? component: HelloWorld
??????????? },
??????????? {
??????????????? path: '/student',
??????????????? name: 'Student',
??????????????? component: Student
??????????? }
??????? ]
??????? // eslint-disable-next-line eol-last
})
appfront文件夹下的main.js中引入ElementUI并注册:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'default-passive-events'
import ElementUI from 'element-ui'
import Vue from 'vue'
// 引入vue-resource
import VueResource from 'vue-resource'
// 注册ElementUI组件
import '../node_modules/element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'
Vue.config.productionTip = false
// 注册ElementUI组件
Vue.use(ElementUI)
??? // 注册VueResource
Vue.use(VueResource)
/* eslint-disable no-new */
new Vue({
??? el: '#app',
??? router,
??? components: { App },
??? template: '<App/>'
??????? // eslint-disable-next-line eol-last
})
3.7、打包并启动前端项目
> npm run build
> npm run dev
然后去浏览器访问页面地址:http://localhost:8080/#/student
四、 整合
?
4.1、前端vue项目调用后端引入vue-resource
在appfront文件下运行命令:
`npm install --save vue-resource`
在main.js中引入vue-resource
> import VueResource from 'vue-resource'
> Vue.use(VueResource)
用Django的第三方包django-cors-headers来**解决跨域问题**
在DjangoElementUI根目录下输入命令:
`pip install django-cors-headers`
在settings.py中增加相关中间件代码
? 在MIDDLEWARE增加:
>?? 'corsheaders.middleware.CorsMiddleware'
> CORS_ORIGIN_ALLOW_ALL = True
4.3、增加Django路由
把Django的TemplateView指向我们刚才生成的前端dist文件
在DjangoElementUI目录下的urls.py中增加代码:
`from django.views.generic import TemplateView`
修改静态资源文件路径以及指向前端appfront 相关文件
在DjangoElementUI目录下的setting.py中增加代码:
` 'DIRS': [os.path.join(BASE_DIR, 'appfront/dist')], `
增加此项 for vue.js
STATICFILES_DIRS = [
???? os.path.join(BASE_DIR, "appfront/dist/static")
]
4.4、重新构建前端项目
> npm run build
> python manage.py runserver
五、 总结
?
1、python 运行过程中,需要什么包,安装什么包;
?python 包库:https://pypi.org/
2、数据库创建的过程中,一定要注意大小写的问题,数据库字段和Django的Models页面,View页面和Vue中的组件页面都有关联.很容易一个大小写不注意,导致整个接口无法使用.
3、连接MySQL需要按照对应的包,同时需要在根目录的_ini_.py中引入pymysql
4、在整个环境的搭建过程中VUE环境的搭建需要耗费较长的npm安装时间,需要耐心等待.
5、前后台连接需要在前端引入**vue-resource**,Django需要引入**django-cors-headers**
|