Be careful : The whole process of the project needs to be from the back to the front , Immediate database -> Back end -> front end ; Starting the process is also to start the back-end project first , Then start the front-end project
development tool :Visual Studio Code( recommend )、WebStorm
open cmd, install Vue The scaffold , The order is as follows :
npm install -g @vue/cli
establish Vue2 project , be known as vue-axios
vue create vue-axios
choice Manually select features
Create , enter
At present, only check Router
, enter
choice 2.x
, enter
Select the following , enter , Waiting to download dependency
When the download is complete , Enter the project
cd vue-axios
install axios library
npm install axios --save
install Element UI library
npm i element-ui -S
stay src Under the new utils Folder , take request.js
Place on src/utils/ Next ,request.js
yes axios Secondary packaging of , as follows :
import axios from 'axios'
const request = axios.create({
baseURL: 'http://127.0.0.1:666', // Be careful !! Here is the overall unity plus Back end interface prefix Prefix , The backend must be cross domain configured !
timeout: 5000
})
// request Interceptor
// Some requests can be processed before they are sent
// For example, unified plus token, Uniformly encrypt the request parameters
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // Set request header
return config
}, error => {
return Promise.reject(error)
});
// response Interceptor
// The results can be processed uniformly after the interface responds
request.interceptors.response.use(
response => {
let res = response.data;
// If it is a returned file
if (response.config.responseType === 'blob') {
return res
}
// Compatible with the string data returned by the server
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
modify main.js, To register
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import request from "@/utils/request"
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
// Turn off the prompt in production mode
Vue.config.productionTip = false
// Set up axios by Vue Prototype properties of
Vue.prototype.$axios = request
Vue.use(ElementUI);
new Vue({
router,
render: function (h) {
return h(App) }
}).$mount('#app')
Remove redundant components , If in src/views and src/components Under the vue Components ; stay src/views newly build Home.vue
Components :
<template>
<div class="home">
<h1> Small separation of front and rear ends demo</h1>
<!-- Table area -->
<el-table
:data="table"
stripe
:cell-
:header-cell-
>
<el-table-column prop="id" label="ID" width="100" sortable />
<el-table-column prop="name" label=" full name " />
<el-table-column prop="age" label=" Age " />
<el-table-column prop="sex" label=" Gender " />
<el-table-column label=" operation " width="210">
<template slot="header">
<span class="op"> operation </span>
<el-button size="mini" class="add" @click="add" icon="el-icon-plus"
> Add a record </el-button
>
</template>
<template slot-scope="scope">
<el-button
type="info"
size="mini"
@click="handEdit(scope.$index, scope.row)"
icon="el-icon-edit"
round
> edit </el-button
>
<el-popconfirm
title=" Are you sure to delete ?"
@confirm="handDelete(scope.$index, scope.row)"
>
<el-button
type="danger"
size="mini"
icon="el-icon-delete"
round
slot="reference"
> Delete </el-button
>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!-- Pop up window -->
<el-dialog
:title="title"
:visible="dialogVisible"
width="30%"
:before-close="handleClose"
>
<el-form
:model="form"
status-icon
:rules="rules"
ref="form"
label-width="60px"
>
<el-form-item label=" full name " prop="name">
<el-input v-model="form.name" autocomplete="off" />
</el-form-item>
<el-form-item label=" Age " prop="age">
<el-input
type="number"
min="1"
max="99"
v-model="form.age"
autocomplete="off"
/>
</el-form-item>
<el-form-item label=" Gender " prop="sex">
<el-radio-group v-model="form.sex">
<el-radio label=" male "></el-radio>
<el-radio label=" Woman "></el-radio>
<el-radio label=" Unknown "></el-radio>
</el-radio-group>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="reset"> Reset </el-button>
<el-button type="primary" @click="save"> indeed set </el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
name: 'Home',
data() {
// Custom validation rules
var validateAge = (rule, value, callback) => {
if (value === '' || value === undefined) {
callback(new Error(' Please enter age '))
} else if (isNaN(value)) {
callback(new Error(' Please enter a number '))
} else if (value < 1 || value > 100) {
callback(new Error(' Age must be in 1~100 Between '))
} else {
callback()
}
}
return {
table: [],
dialogVisible: false,
title: '',
form: {},
rules: {
name: [{ required: true, message: ' Please enter a name ', trigger: 'blur' }],
age: [{ required: true, validator: validateAge, trigger: 'blur' }],
sex: [{ required: true, message: ' Please choose gender ', trigger: 'blur' }],
}
}
},
created() {
this.init()
},
methods: {
init() {
this.$axios.get('/all').then(res => {
console.log(res);
this.table = res.data
})
},
add() {
this.dialogVisible = true
this.title = ' Add records '
this.form = {}
},
handEdit(index, row) {
this.dialogVisible = true
this.title = ' Edit the record '
this.form = JSON.parse(JSON.stringify(row))
},
handDelete(index, row) {
let id = JSON.parse(JSON.stringify(row)).id
this.$axios.delete(`/delete?id=${id}`).then(res => {
if (res.code == 200) {
this.$notify.success({
title: ' success ',
message: res.msg,
duration: 2000
})
this.init()
} else {
this.$notify.success({
title: ' Failure ',
message: res.msg,
duration: 2000
})
}
})
},
handleClose() {
this.dialogVisible = false
this.init()
},
reset() {
let id = undefined
if ('id' in this.form) {
id = this.form.id
}
this.form = {}
if (id != undefined) this.form.id = id
},
save() {
this.$refs['form'].validate(valid => { // Determine whether it passes validation
if (valid) {
console.log(this.form);
if ('id' in this.form) {
// console.log(' modify ');
this.$axios.put('/update', this.form).then(res => {
if (res.code == 200) {
let _this = this
this.$notify.success({
title: ' success ',
message: res.msg,
duration: 2000,
onClose: function () { _this.handleClose() }
});
} else {
this.$notify.error({
title: ' error ',
message: res.msg,
duration: 2000
});
}
})
} else {
// console.log(' add to ');
this.$axios.post('/add', this.form).then(res => {
if (res.code == 200) {
let _this = this
this.$notify.success({
title: ' success ',
message: res.msg,
duration: 2000,
onClose: function () { _this.handleClose() }
});
} else {
this.$notify.error({
title: ' error ',
message: res.msg,
duration: 2000
});
}
})
}
}
})
}
}
}
</script>
<style>
h1 {
text-align: center;
margin: 50px 0;
}
.el-table {
width: 60% !important;
margin: 0 auto;
}
.el-button {
margin: 0 5px;
}
span.op {
display: inline-block;
margin-left: 6px;
}
.el-dialog__body {
padding-bottom: 0;
}
</style>
modify App.vue, as follows :
<template>
<div id="app">
<router-view />
</div>
</template>
<style>
/* Introduce the outside css */
@import "./assets/css/reset.css";
</style>
among reset.css
as follows :
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
modify src/router/index.js as follows :
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: () => import('@/views/Home.vue')
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
Open the terminal or cmd, Enter the following command to start the project
npm run serve
Type in the browser http://localhost:8080/
You can open the home page , Query all data by default , as follows :
Add a page :
Edit page :
Delete page :
The basic addition, deletion, modification and query have been realized , All are implemented in the way of interface request , Under the web toolbar of the developer tool , You can see the request sent by the front end , as follows :
And the preview results of the backend response data :
development environment :PyCharm( recommend )、Visual Studio Code
open cmd, install flask library , The order is as follows :
pip install flask
install flask_cors library , The order is as follows :
pip install flask_cors
install pymysql library , The order is as follows :
pip install pymysql
establish Python project , be known as python-flask
newly build json_response.py
, Unified json Returns the format
# A unified json Returns the format
class JsonResponse(object):
def __init__(self, code, msg, data):
self.code = code
self.msg = msg
self.data = data
# Specify a class method as a class method , Usually use self To pass an instance of the current class -- object ,cls Pass the current class .
@classmethod
def success(cls, code=200, msg='success', data=None):
return cls(code, msg, data)
@classmethod
def fail(cls, code=400, msg='fail', data=None):
return cls(code, msg, data)
def to_dict(self):
return {
"code": self.code,
"msg": self.msg,
"data": self.data
}
newly build json_flask.py
, send flask Support return JsonResponse object
from flask import Flask, jsonify
from json_response import JsonResponse
class JsonFlask(Flask):
def make_response(self, rv):
# The view function can directly return : list、dict、None
if rv is None or isinstance(rv, (list, dict)):
rv = JsonResponse.success(rv)
if isinstance(rv, JsonResponse):
rv = jsonify(rv.to_dict())
return super().make_response(rv)
newly build config.py
, Database operation
# Database operation class
import pymysql
DB_CONFIG = {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"passwd": "123456",
"db": "test",
"charset": "utf8"
}
class SQLManager(object):
# Initialize the instance method
def __init__(self):
self.conn = None
self.cursor = None
self.connect()
# Connect to database
def connect(self):
self.conn = pymysql.connect(
host=DB_CONFIG["host"],
port=DB_CONFIG["port"],
user=DB_CONFIG["user"],
passwd=DB_CONFIG["passwd"],
db=DB_CONFIG["db"],
charset=DB_CONFIG["charset"]
)
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
# Query multiple data
def get_list(self, sql, args=None):
self.cursor.execute(sql, args)
return self.cursor.fetchall()
# Query single data
def get_one(self, sql, args=None):
self.cursor.execute(sql, args)
return self.cursor.fetchone()
# Execute a single article SQL sentence
def modify(self, sql, args=None):
row = self.cursor.execute(sql, args)
self.conn.commit()
return row > 0
# Execute more than one SQL sentence
def multi_modify(self, sql, args=None):
rows = self.cursor.executemany(sql, args)
self.conn.commit()
return rows > 0
# Close the database cursor And connections
def close(self):
self.cursor.close()
self.conn.close()
newly build app.py
, The main program
from flask import request
from flask_cors import *
from json_flask import JsonFlask
from json_response import JsonResponse
from config import *
import json
# Create a view application
app = JsonFlask(__name__)
# To solve the cross domain
CORS(app, supports_credentials=True)
db = SQLManager()
# Write view functions , Bind route
@app.route("/all", methods=["GET"]) # Inquire about ( All )
def all():
result = db.get_list(sql='select * from user')
return JsonResponse.success(msg=' The query is successful ', data=result)
@app.route("/add", methods=["POST"]) # add to ( Single )
def add():
data = json.loads(request.data) # take json String to dict
isOk = db.modify(sql='insert into user(name,age,sex) values(%s,%s,%s)',
args=[data['name'], data['age'], data['sex']])
return JsonResponse.success(msg=' Add success ') if isOk else JsonResponse.fail(msg=' Add failure ')
@app.route("/update", methods=["PUT"]) # modify ( Single )
def update():
data = json.loads(request.data) # take json String to dict
if 'id' not in data:
return JsonResponse.fail(msg=' Need to id')
isOk = db.modify(sql='update user set name=%s,age=%s,sex=%s where id=%s',
args=[data['name'], data['age'], data['sex'], data['id']])
return JsonResponse.success(msg=' Modification successful ') if isOk else JsonResponse.fail(msg=' Modification failed ')
@app.route("/delete", methods=["DELETE"]) # Delete ( Single )
def delete():
if 'id' not in request.args:
return JsonResponse.fail(msg=' Need to id')
isOk = db.modify(sql='delete from user where id=%s', args=[request.args['id']])
return JsonResponse.success(msg=' Delete successful ') if isOk else JsonResponse.fail(msg=' Delete failed ')
# function flask: The default is 5000 port , Set the port here as 666
if __name__ == '__main__':
app.run(host="0.0.0.0", port=666, debug=True)
Start project .
use MySQL, Because it is small demo, The design here is simple , The database name is test
, Table, user
, Table structure and data SQL The statement is as follows :
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
`age` int(11) NOT NULL,
`sex` varchar(255) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = gbk COLLATE = gbk_chinese_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'tom', 20, ' male ');
INSERT INTO `user` VALUES (2, 'mary', 20, ' Woman ');
INSERT INTO `user` VALUES (3, 'jack', 21, ' male ');
INSERT INTO `user` VALUES (5, 'test', 20, ' Unknown ');
INSERT INTO `user` VALUES (8, 'tom', 20, ' male ');
INSERT INTO `user` VALUES (9, 'add', 20, ' Unknown ');
INSERT INTO `user` VALUES (10, 'Saly', 11, ' Woman ');
SET FOREIGN_KEY_CHECKS = 1;