189 8069 5689

怎么用python+Element实现模板Temp操作

本篇内容介绍了“怎么用python+Element实现模板Temp操作”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

创新互联建站主要从事成都做网站、网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务榕江,十余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108

1.前端HTML和CSS


    
        
            
                
                    
                        
                            选择业务:
                            
                                
                                
                              
                            
                        
                                     
                                                                                           模板名称:                                                                                                                                                                                                                                                                                       搜索                                 导出                                 添加模板                                                                                                                                                                                                                                                                         修改                     删除                                                                                                                                                                                                                                                                                                                                                                                                                                             立即创建                     取消                                                                                                                                                                                                                                                                                                                                                                                                                                    立即创建                     取消                                            

2.前端JS


    new Vue({
        el: '#app',
        data: {
            bkBizData: [],
            tempData: [],
            searchBiz:'',
            searchTempName:'',
            editDialog:false,
            addDialog:false,
            addForm: {
                add_bk_biz: '',
                add_temp_name: '',
                add_temp_script: '',
                add_temp_value: '',
                add_temp_note: ''
            },
            editForm: {
                pk:'',
                edit_bk_biz: '',
                edit_temp_name: '',
                edit_temp_script: '',
                edit_temp_value: '',
                edit_temp_note: ''
            }
        },
        mounted() {
            // 页面加载就获取所有模板
            this.init()
        },
        methods: {
            init() {
                axios.get(site_url + "get_biz_list/").then(res => {
                    if (res.data.result){
                        this.bkBizData = res.data.data;
                    }else{
                        this.$message.error('获取业务失败');
                    }
                },'json');
                axios.get(site_url + "temp_view/").then(res => {
                    if (res.data.result){
                        this.tempData = res.data.data;
                    }else{
                        this.$message.error('获取模板失败');
                    }
                },'json');
            },
            getSearch() {
                axios.get(site_url + "temp_view/?search_biz_id=" + this.searchBiz + "&query_str=" + this.searchTempName).then(res => {
                    if (res.data.result){
                        this.tempData = res.data.data;
                    }else{
                        this.$message.error('获取模板失败');
                    }
                },'json');
            },
            addDialogOk() {
                axios.post(site_url + "temp_view/", this.addForm).then(res => {
                    if (res.data.result) {
                        this.$message.success('添加模板成功');
                        this.addDialog = false;
                        this.init();
                        this.addForm = {
                            add_bk_biz: '',
                            add_temp_name: '',
                            add_temp_script: '',
                            add_temp_value: '',
                            add_temp_note: ''
                        }
                    } else {
                        this.$message.error('添加模板失败');
                    }
                }, 'json');
            },
            editTempMethod(row) {
                this.editForm.edit_bk_biz = row.bk_biz_name;
                this.editForm.edit_temp_name = row.temp_name;
                this.editForm.edit_temp_script = row.script;
                this.editForm.edit_temp_value = row.threshold;
                this.editForm.edit_temp_note = row.note;
                this.editForm.pk = row.pk;
                this.editDialog = true;
            },
            deleteTempMethod(row) {
                this.$confirm('正在删除模板, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete('/temp_view/',{data:{id:row.pk}}).then(res => {
                        if (res.data.result) {
                            this.$message.success('删除模板成功');
                            this.init();
                        } else {
                            this.$message.error('删除模板失败');
                        }
                    }, 'json');
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消删除'
                  });
                });
            },
            editDialogOk() {
                axios.put(site_url + "temp_view/", this.editForm).then(res => {
                    if (res.data.result) {
                        this.$message.success('更新模板成功');
                        this.editDialog = false;
                        this.init();
                    } else {
                        this.$message.error('更新模板失败');
                    }
                }, 'json');
            },
            exportTemp() {
                location.href = site_url + 'export_temp/'
            }
        }
    })

3.Django代码

urls.py文件内容

from django.conf.urls import patterns

from home_application.temp import views as temp_view

urlpatterns = patterns(
    'home_application.views',
    (r'^temp/$', 'temp'),
    (r'^temp_view/$', temp_view.TemplateView.as_view()),
    (r'^get_biz_list/$', 'get_biz_list'),
    (r'^export_temp/$', temp_view.export_temp),
    ...
)

temp\views.py文件内容

import json

import xlwt
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.http import JsonResponse, HttpResponse
from django.db.models import Q

from home_application.models import Template

class CsrfExemptView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(CsrfExemptView, self).dispatch(request, *args, **kwargs)

class TemplateView(CsrfExemptView):
    def get(self, request, *args, **kwargs):
        search_biz_id = request.GET.get("search_biz_id")
        query_str = request.GET.get("query_str")
        try:
            temp_query = Template.objects.all()
        except Exception:
            return JsonResponse({"result": False})
        if search_biz_id:
            temp_query = temp_query.filter(bk_biz_id=search_biz_id)
        if query_str:
            temp_query = temp_query.filter(
                Q(temp_name__icontains=query_str) | Q(script__contains=query_str) | Q(note__contains=query_str)
            )
        res_data = [i.to_dict() for i in temp_query]
        return JsonResponse({"result": True, "data": res_data})

    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        temp_obj = {
            "bk_biz_id": data.get("add_bk_biz").split(":")[0],
            "bk_biz_name": data.get("add_bk_biz").split(":")[1],
            "temp_name": data.get("add_temp_name"),
            "note": data.get("add_temp_note"),
            "threshold": data.get("add_temp_value"),
            "script": data.get("add_temp_script"),
        }
        try:
            Template.objects.create(**temp_obj)
            return JsonResponse({"result": True})
        except Exception:
            return JsonResponse({"result": False})

    def put(self, request, *args, **kwargs):
        data = json.loads(request.body)
        pk = data.get("pk")
        bk_biz_id = data.get("edit_bk_biz").split(":")[0]
        bk_biz_name = data.get("edit_bk_biz").split(":")[1]
        temp_name = data.get("edit_temp_name")
        script = data.get("edit_temp_script")
        threshold = data.get("edit_temp_value")
        note = data.get("edit_temp_note")
        temp_obj = {
            "bk_biz_id": bk_biz_id,
            "bk_biz_name": bk_biz_name,
            "temp_name": temp_name,
            "script": script,
            "threshold": threshold,
            "note": note,
        }
        try:
            Template.objects.filter(pk=pk).update(**temp_obj)
            return JsonResponse({"result": True})
        except Exception as e:
            print(e)
            return JsonResponse({"result": False})

    def delete(self, request, *args, **kwargs):
        data = json.loads(request.body)
        pk = data.get("id")
        try:
            Template.objects.filter(pk=pk).delete()
            return JsonResponse({"result": True})
        except Exception:
            return JsonResponse({"result": False})

def generate_temp():
    f = xlwt.Workbook()
    # 添加一个Sheet,名字为 sheet_name 所传的参数
    sheet1 = f.add_sheet("Sheet1", cell_overwrite_ok=True)
    title = [u"模板ID", u"业务ID", u"业务名称", u"模板名称", u"巡检脚本", u"阀值", u"备注", u"创建时间"]
    # 写文件头
    for i in range(0, len(title)):
        # i 表示第一行的第 i 列
        sheet1.write(0, i, title[i])

    temp_query = Template.objects.all()
    temp_list = [i.to_dict() for i in temp_query]

    # 从第二行开始写入数据
    for i in range(0, len(temp_list)):
        # 向每一行的第1列写入数据
        sheet1.write(i + 1, 0, temp_list[i].get("pk"))
        sheet1.write(i + 1, 1, temp_list[i].get("bk_biz_id"))
        # 向每一行的第2列写入数据
        sheet1.write(i + 1, 2, temp_list[i].get("bk_biz_name"))
        sheet1.write(i + 1, 3, temp_list[i].get("temp_name"))
        sheet1.write(i + 1, 4, temp_list[i].get("script"))
        sheet1.write(i + 1, 5, temp_list[i].get("threshold"))
        sheet1.write(i + 1, 6, temp_list[i].get("note"))
        sheet1.write(i + 1, 7, temp_list[i].get("create_time"))
    f.save('模板.xls')

def export_temp(request):
    generate_temp()
    file = open('模板.xls', 'rb')
    response = HttpResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="模板.xls"'
    return response

models.py文件内容

from django.db import models

from home_application.utils.parse_time import parse_datetime_to_timestr

class Template(models.Model):
    bk_biz_id = models.CharField(u"业务ID", max_length=8, blank=True, null=True)
    bk_biz_name = models.CharField(u"业务名称", max_length=32, blank=True, null=True)
    temp_name = models.CharField(u"模板名称", max_length=32, blank=True, null=True)
    script = models.TextField(u"巡检脚本", max_length=2048, blank=True, null=True)
    threshold = models.CharField(u"阀值", max_length=32, blank=True, null=True)
    note = models.CharField(u"备注", max_length=256, blank=True, null=True)
    create_time = models.DateTimeField(u"创建时间", auto_now_add=True)

    def to_dict(self):
        return {
            "pk": self.pk,
            "bk_biz_id": self.bk_biz_id,
            "bk_biz_name": self.bk_biz_name,
            "temp_name": self.temp_name,
            "script": self.script,
            "threshold": self.threshold,
            "note": self.note,
            "create_time": parse_datetime_to_timestr(self.create_time),
        }

实现效果

怎么用python+Element实现模板Temp操作

怎么用python+Element实现模板Temp操作

“怎么用python+Element实现模板Temp操作”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


网站名称:怎么用python+Element实现模板Temp操作
标题URL:http://cdxtjz.cn/article/jgijho.html

联系我们

您好HELLO!
感谢您来到成都网站建设公司,若您有合作意向,请您为我们留言或使用以下方式联系我们, 我们将尽快给你回复,并为您提供真诚的设计服务,谢谢。
  • 电话:028- 86922220 18980695689
  • 商务合作邮箱:631063699@qq.com
  • 合作QQ: 532337155
  • 成都网站设计地址:成都市青羊区锣锅巷31号五金站写字楼6楼

小谭建站工作室

成都小谭网站建设公司拥有多年以上互联网从业经验的团队,始终保持务实的风格,以"帮助客户成功"为已任,专注于提供对客户有价值的服务。 我们已为众企业及上市公司提供专业的网站建设服务。我们不只是一家网站建设的网络公司;我们对营销、技术、管理都有自己独特见解,小谭建站采取“创意+综合+营销”一体化的方式为您提供更专业的服务!

小谭观点

相对传统的成都网站建设公司而言,小谭是互联网中的网站品牌策划,我们精于企业品牌与互联网相结合的整体战略服务。
我们始终认为,网站必须注入企业基因,真正使网站成为企业vi的一部分,让整个网站品牌策划体系变的深入而持久。