1.后端准備
環境說明
python版本:3.6.6
Django版本:1.11.8
數據庫:MariaDB 5.5.60
新建Django項目,在項目中新建app,配置好數據庫
2.后端代碼(基於CBV方式)
api_test/app01/models.py
文件內容
from django.db import models
from .utils.parse_time import parse_datetime_to_string
class HostInfo(models.Model):
hostname = models.CharField("主機名", max_length=32)
ip = models.CharField("IP地址", max_length=16)
status = models.CharField("主機狀態", max_length=16)
date = models.DateTimeField("主機添加時間", auto_now_add=True)
def to_dict(self):
return {
"hostname": self.hostname,
"id": self.pk,
"ip": self.ip,
"status": self.status,
"when_insert": parse_datetime_to_string(self.date),
}
app01/utils/parse_time.py
文件內容
def parse_datetime_to_string(datetime_str, flag=True):
"""
把datetime時間轉化成時間字符串
:param datetime_str: datetime生成的時間,例子:datetime.datetime.now()
或者: datetime.datetime.now() - datetime.timedelta(hours=1) # 一個小時之前
或者: datetime.datetime.now() - datetime.timedelta(days=1) # 一天之前
:return:
"""
# 將日期轉化為字符串 datetime => string
# 在數據庫中定義字段信息時為:models.DateTimeField(auto_now_add=True)
# 查詢數據庫之后,使用此方法把查詢到的時間轉換成可用的時間字符串
# when_insert__range=(an_hour_time, now_time)
# an_hour_time和 now_time 都是 datetime時間字符串,查詢兩個datetime時間字符串之間的數據
if flag:
return datetime_str.strftime('%Y-%m-%d %H:%M:%S')
else:
return datetime_str.strftime('%Y-%m-%d')
api_test/urls.py
文件內容
from django.conf.urls import url
from django.contrib import admin
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^host/$', csrf_exempt(views.HostInfoView.as_view())),
]
api_test/app01/views.py
文件內容
class HostInfoView(View):
def get(self, request):
res_list = []
host_list = HostInfo.objects.all()
for i in host_list:
res_list.append(i.to_dict())
return JsonResponse({"data": res_list, "result": True}, safe=False)
def post(self, request):
data = json.loads(request.body)
res = {"result": False}
id = data.get("id")
hostname = data.get("hostname")
ip = data.get("ip")
status = data.get("status")
operate = data.get("operate")
if operate == "delete":
try:
HostInfo.objects.filter(id=id).delete()
res = {"result": True}
except Exception:
res = {"result": False}
elif operate == "create":
try:
HostInfo.objects.create(hostname=hostname, ip=ip, status=status)
res = {"result": True}
except Exception:
res = {"result": False}
elif operate == "edit":
try:
HostInfo.objects.filter(id=id).update(hostname=hostname, ip=ip, status=status)
res = {"result": True}
except Exception:
res = {"result": False}
return JsonResponse(res, safe=False)
3.前端代碼
首先新建一個項目,然后引入iView插件,配置好router
npm安裝iView
npm install iview --save
cnpm install iview --save
src/main.js
文件內容
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import iView from 'iview';
import 'iview/dist/styles/iview.css';
Vue.use(iView);
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
src/router.js
文件內容
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/form1',
component: () => import('./views/Form1.vue')
},
{
path:'/',
redirect:'/form1'
}
]
})
src/views/Form1.vue
文件內容
<template>
<div style="padding: 32px 200px;">
<h1>Form組件實踐</h1>
<br><br>
<Table border :columns="tableColumns" :data="tableData"></Table>
<Button @click="handleOpenCreate">添加</Button>
<Modal :title="type === 'create' ? '新增主機':'修改主機'" v-model="openModal" @on-ok="handleOk" @on-cancel="handleCancel">
<Form :model="ModelForm" :label-width="70">
<FormItem label="主機名稱">
<Input v-model="ModelForm.hostname"/>
</FormItem>
<FormItem label="IP地址">
<Input v-model="ModelForm.ip"/>
</FormItem>
<FormItem label="主機狀態">
<Select v-model="ModelForm.status">
<Option label="processing" value="processing"/>
<Option label="error" value="error"/>
</Select>
</FormItem>
</Form>
</Modal>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
tableData: [],
openModal: false,
deleteModal: false,
type: 'create', // create || edit
editIndex: -1,
ModelForm: {
id: '',
hostname: '',
ip: '',
status: '',
operate: ''
},
tableColumns: [
{
title: '主機名稱',
key: 'hostname'
},
{
title: 'IP地址',
key: 'ip'
},
{
title: '主機狀態',
key: 'status'
},
{
title: '最后修改時間',
key: 'when_insert'
},
{
title: '操作',
render: (h, params) => {
return h('div', [
h('Button', {
props: {
type: 'primary',
},
on: {
click: () => {
this.handleOpenEdit(params.row)
}
}
}, '修改'),
h('Button', {
props: {
type: 'error',
},
style: {
marginLeft: '10px'
},
on: {
click: () => {
// this.$router.push({path: '/hostperforms', query: {host_id: Number(params.row.host_id)}})
this.handleDelete(params.row)
}
}
}, '刪除'),
]);
}
}
]
}
},
mounted() {
this.getData()
},
methods: {
handleOpenEdit(row) {
this.openModal = true;
this.type = 'edit';
this.ModelForm = row;
},
handleOpenCreate() {
this.openModal = true;
this.type = 'create';
},
handleCancel() {
this.openModal = false;
this.ModelForm = {
hostname: '',
ip: '',
status: '',
}
},
handleOk() {
this.ModelForm.operate = this.type
axios.post('http://127.0.0.1:8000/host/',this.ModelForm).then(res => {
if (res.data.result) {
this.$Message.success('請求成功');
this.hostRow.status = this.ModelForm.status
} else {
this.$Message.error('請求失敗');
}
})
this.openModal = false;
this.ModelForm = {
hostname: '',
ip: '',
status: '',
}
this.getData();
},
getData() {
axios.get('http://127.0.0.1:8000/host/').then(res => {
if (res.data.result) {
this.tableData = res.data.data;
} else {
this.$Message.error('請求失敗');
}
})
},
handleDelete(row) {
this.$Modal.confirm({
title: '警告',
content: '正在刪除主機信息,是否繼續?',
onOk: () => {
row.operate = "delete"
axios.post('http://127.0.0.1:8000/host/', row).then(res => {
if (res.data.result) {
this.$Message.success('刪除主機成功');
this.getData();
} else {
this.$Message.error('刪除主機失敗');
}
})
},
onCancel: () => {
this.$Message.info('取消刪除');
}
});
}
}
}
</script>
<style scoped>
</style>
分別運行前后端代碼,瀏覽器打開URL:http://127.0.0.1:8080/#/form1
,會在頁面列出所有主機
點擊某台主機主機后的修改
按鈕,彈出模態框,模態框的title為:修改主機
點擊頁面的新增
按鈕,彈出模態框,模態框的title為:新增主機
點擊某台主機后的刪除
按鈕,彈出對話框,提示用戶正在刪除主機