温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用python + Element实现作业任务Job操作

发布时间:2021-06-28 16:32:40 来源:亿速云 阅读:169 作者:chen 栏目:大数据

这篇文章主要讲解了“怎么用python + Element实现作业任务Job操作”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用python + Element实现作业任务Job操作”吧!

1.前端HTML和CSS

<div id="app">
    <div class="col-md-10 col-md-offset-1">
        <div class="container-fluid mb0 " >
            <div class="row">
                <div class="col-md-4">
                    <form class="form-horizontal">
                        <div class="form-group clearfix ">
                            <label class="col-sm-4 control-label bk-lh40 pt0">任务类型:</label>
                            <div class="col-sm-8">
                                <el-select v-model="searchJobType" placeholder="请选择任务类型" >
                                    <el-option v-for="item in jobType" :label="item.title" :value="item.title"></el-option>
                                </el-select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="col-md-4">
                    <form class="form-horizontal">
                        <div class="form-group clearfix ">
                            <label class="col-sm-4 control-label bk-lh40 pt0">任务名称:</label>
                            <div class="col-sm-8">
                                <el-input v-model="searchJobName" placeholder="请输入任务名称" ></el-input>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="col-md-4">
                    <form class="form-horizontal">
                        <div class="form-group clearfix ">
                            <div class="col-sm-8">
                                <el-button type="primary" @click="getSearch">搜索</el-button>
                                <el-button type="success" @click="addDialog = true">添加</el-button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <el-table :data="jobData" border >
            <el-table-column prop="bk_biz_id" label="业务ID"></el-table-column>
            <el-table-column prop="bk_biz_name" label="业务名称"></el-table-column>
            <el-table-column prop="temp_name" label="模板名称"></el-table-column>
            <el-table-column prop="job_name" label="作业名称"></el-table-column>
            <el-table-column prop="type" label="类型"></el-table-column>
            <el-table-column prop="interval" label="间隔时间"></el-table-column>
            <el-table-column prop="host_ip" label="主机IP"></el-table-column>
            <el-table-column prop="create_time" label="添加时间"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="editJobMethod(scope.row)">修改</el-button>
                    <el-button type="danger" size="small" @click="deleteJobMethod(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 新增的对话框 -->
        <el-dialog title="添加作业任务" :visible.sync="addDialog" width="40%">
            <el-form ref="addForm" :model="addForm" label-width="100px">
                <el-form-item label="选择业务">
                    <el-select v-model="addForm.add_biz" placeholder="请选择业务" >
                        <el-option v-for="item in bkBizData" :label="item.bk_biz_name" :value="item.bk_biz_id +':'+item.bk_biz_name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="巡检模板">
                    <el-select v-model="addForm.add_temp" placeholder="请选择巡检模板" >
                        <el-option v-for="item in TempData" :label="item.temp_name" :value="item.pk +':'+item.temp_name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名称">
                    <el-input v-model="addForm.add_job_name"></el-input>
                </el-form-item>
                <el-form-item label="任务类型">
                    <el-radio-group v-model="addForm.add_type">
                        <el-radio label="立即">立即</el-radio>
                        <el-radio label="周期">周期-----每隔
                            <el-input v-model="addForm.add_interval" ></el-input>
                            分钟执行一次
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="巡检服务器">
                    <el-select v-model="addForm.add_host_ip" placeholder="请选择巡检服务器" >
                        <el-option v-for="item in HostData" :label="item.host_name" :value="item.ip"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addDialogOk">立即创建</el-button>
                    <el-button @click="addTempDialog = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog title="修改作业任务" :visible.sync="editDialog" width="40%">
            <el-form ref="editForm" :model="editForm" label-width="100px">
                <el-form-item label="选择业务">
                    <el-select v-model="editForm.edit_bk_biz" placeholder="请选择业务" >
                        <el-option v-for="item in bkBizData" :label="item.bk_biz_name" :value="item.bk_biz_id +':'+item.bk_biz_name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="巡检模板">
                    <el-select v-model="editForm.edit_temp_name" placeholder="请选择巡检模板" >
                        <el-option v-for="item in TempData" :label="item.temp_name" :value="item.pk +':'+item.temp_name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名称">
                    <el-input v-model="editForm.edit_job_name"></el-input>
                </el-form-item>
                <el-form-item label="任务类型">
                    <el-radio-group v-model="editForm.edit_type">
                        <el-radio label="立即">立即</el-radio>
                        <el-radio label="周期">周期-----每隔
                            <el-input v-model="editForm.edit_interval" ></el-input>分钟执行一次
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="巡检服务器">
                    <el-select v-model="editForm.edit_host_ip" placeholder="请选择巡检服务器" >
                        <el-option v-for="item in HostData" :label="item.host_name" :value="item.ip"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editDialogOk">立即创建</el-button>
                    <el-button @click="editDialog = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 设置面板End -->
    </div>
</div>

2.前端JS

<script type="text/javascript">
    new Vue({
        el: '#app',
        data: {
            bkBizData: [],
            jobData: [],
            HostData: [],
            TempData: [],
            editDialog:false,
            addDialog:false,
            addForm: {
                add_biz: '',
                add_temp: '',
                add_job_name: '',
                add_type: '',
                add_interval: '',
                add_host_ip: ''
            },
            editForm: {
                pk:'',
                edit_bk_biz: '',
                edit_temp_name: '',
                edit_job_name: '',
                edit_type: '',
                edit_interval: '',
                edit_host_ip: ''
            },
            jobType:[
                {
                    title: '全部',
                    key: '全部'
                },
                {
                    title: '立即',
                    key: '立即'
                },
                {
                    title: '周期',
                    key: '周期'
                }
            ],
            searchJobType: '',
            searchJobName:''
        },
        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');
                axios.get(site_url + "get_bk_hosts/").then(res => {
                    if (res.data.result){
                        this.HostData = res.data.data;
                    }else{
                        this.$message.error('获取模板失败');
                    }
                },'json');
                this.getSearch();
            },
            getSearch() {
                axios.get(site_url + "job_view/?search_type=" + this.searchJobType + "&query_str=" + this.searchJobName).then(res => {
                    if (res.data.result){
                        this.jobData = res.data.data;
                        console.log(this.jobData)
                    }else{
                        this.$message.error('获取模板失败');
                    }
                },'json');
            },
            addDialogOk() {
                axios.post(site_url + "job_view/", this.addForm).then(res => {
                    if (res.data.result) {
                        this.$message.success('添加作业任务成功');
                        this.addDialog = false;
                        this.init();
                        this.addForm = {
                            add_biz: '',
                            add_temp: '',
                            add_job_name: '',
                            add_type: '',
                            add_interval: '',
                            add_host_ip: ''
                        }
                    } else {
                        this.$message.error('添加作业任务失败');
                    }
                }, 'json');
            },
            editJobMethod(row) {
                this.editForm.edit_bk_biz = row.bk_biz_id + ":" + row.bk_biz_name;
                this.editForm.edit_temp_name = row.temp_id + ":" + row.temp_name;
                this.editForm.edit_job_name = row.job_name;
                this.editForm.edit_type = row.type;
                this.editForm.edit_interval = row.interval;
                this.editForm.edit_host_ip = row.host_ip;
                this.editForm.pk = row.pk;
                this.editDialog = true;
            },
            deleteJobMethod(row) {
                this.$confirm('正在删除作业任务, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                    axios.delete('/job_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 + "job_view/", this.editForm).then(res => {
                    if (res.data.result) {
                        this.$message.success('更新作业任务成功');
                        this.editDialog = false;
                        this.init();
                    } else {
                        this.$message.error('更新作业任务失败');
                    }
                }, 'json');
            }
        }
    })
</script>

3.Django代码

urls.py文件内容

from django.conf.urls import patterns

from home_application.temp import views as temp_view
from home_application.job import views as job_view

urlpatterns = patterns(
    'home_application.views',
    (r'^$', job_view.job),
    (r'^get_biz_list/$', job_view.get_biz_list),
    (r'^get_bk_hosts/$', job_view.get_bk_hosts),
    (r'^temp_view/$', temp_view.TemplateView.as_view()),
    (r'^job_view/$', job_view.JobView.as_view()),
    ...
)

job\views.py文件内容

import json

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

from common.mymako import render_mako_context

from home_application.models import Job

def cc_search_host():
    """
    根据条件查询主机
    :return:
    """
    url = "{0}/api/c/compapi/v2/cc/search_host/".format(BK_PAAS_HOST)
    kwargs = {
        "bk_app_code": APP_ID,
        "bk_app_secret": APP_TOKEN,
        "bk_username": "admin",
        "condition": [
            {
                "bk_obj_id": "host",
                "fields": ["bk_host_name", "bk_host_innerip", "bk_host_id", "bk_cloud_id", ],
            },
            {
                "bk_obj_id": "biz",
                "fields": ["bk_biz_id", "bk_biz_name"],
            }
        ],
        # "page": {"start": 0, "limit": 10}
    }
    response = requests.post(url=url, data=json.dumps(kwargs), verify=False)
    if response.status_code == 200:
        return json.loads(response.content).get("data")

# 获取所有业务,测试OK
def cc_search_business(fields=[]):
    """
    获取业务列表
    :param request:
    :return:
    """
    client = get_client_by_user("admin")
    params = {'fields': fields}
    res = client.cc.search_business(**params)
    if res.get('code') == 0:
        return res.get('data', {}).get('info', [])

def job(request):
    return render_mako_context(request, '/home_application/job_center.html')

def get_biz_list(request):
    fields = ["bk_biz_id", "bk_biz_name"]
    return JsonResponse({"result": True, "data": data})

def get_bk_hosts(request):
    from home_application.utils.cc_by_request import cc_search_host
    res_data = cc_search_host()
    return JsonResponse({"result": True, "data": res_data})

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

class JobView(CsrfExemptView):
    def get(self, request, *args, **kwargs):
        search_type = request.GET.get("search_type")
        query_str = request.GET.get("query_str")
        try:
            job_query = Job.objects.all()
        except Exception:
            return JsonResponse({"result": False})
        if search_type:
            job_query = job_query.filter(type=search_type)
        if query_str:
            job_query = job_query.filter(job_name__icontains=query_str)
        res_data = [i.to_dict() for i in job_query]
        return JsonResponse({"result": True, "data": res_data})

    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        job_obj = {
            "bk_biz_id": data.get("add_biz").split(":")[0],
            "bk_biz_name": data.get("add_biz").split(":")[1],
            "temp_id": data.get("add_temp").split(":")[0],
            "temp_name": data.get("add_temp").split(":")[1],
            "job_name": data.get("add_job_name"),
            "type": data.get("add_type"),
            "interval": data.get("add_interval"),
            "host_ip": data.get("add_host_ip"),
        }
        try:
            Job.objects.create(**job_obj)
            return JsonResponse({"result": True})
        except Exception as e:
            print(e)
            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]
        temp_id = data.get("edit_temp_name").split(":")[0]
        temp_name = data.get("edit_temp_name").split(":")[1]
        bk_biz_name = data.get("edit_bk_biz").split(":")[1]
        job_name = data.get("edit_job_name")
        type = data.get("edit_type")
        interval = data.get("edit_interval")
        host_ip = data.get("edit_host_ip")
        job_obj = {
            "bk_biz_id": bk_biz_id,
            "bk_biz_name": bk_biz_name,
            "temp_id": temp_id,
            "temp_name": temp_name,
            "job_name": job_name,
            "type": type,
            "interval": interval,
            "host_ip": host_ip,
        }
        try:
            Job.objects.filter(pk=pk).update(**job_obj)
            return JsonResponse({"result": True})
        except Exception as e:
            return JsonResponse({"result": False})

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

models.py文件内容

class Job(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_id = models.CharField(u"模板ID", max_length=8, blank=True, null=True)
    temp_name = models.CharField(u"模板名称", max_length=32, blank=True, null=True)
    job_name = models.CharField(u"作业名称", max_length=16, blank=True, null=True)
    type = models.CharField(u"类型", max_length=8, blank=True, null=True)
    interval = models.CharField(u"间隔时间", max_length=4, blank=True, null=True)
    host_ip = models.CharField(u"主机IP", max_length=32, 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_id": self.temp_id,
            "temp_name": self.temp_name,
            "job_name": self.job_name,
            "type": self.type,
            "interval": self.interval,
            "host_ip": self.host_ip,
            "create_time": parse_datetime_to_timestr(self.create_time),
        }

实现效果

怎么用python + Element实现作业任务Job操作

怎么用python + Element实现作业任务Job操作

感谢各位的阅读,以上就是“怎么用python + Element实现作业任务Job操作”的内容了,经过本文的学习后,相信大家对怎么用python + Element实现作业任务Job操作这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI