zoukankan      html  css  js  c++  java
  • django中管理程序2

    升级版

    from os import path
    TASKS_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
    PYTHON_ROOT = '/usr/bin/python'
    job_workspace =   path.join(TASKS_ROOT,'app').replace('\', '/')
    from tempfile import mkstemp
    from os import fdopen,unlink,kill
    from subprocess import Popen
    import signal
    from django.http import HttpResponse
    from django.core import serializers
    import psutil
    def startjob(request):
        request.session.modified = True
        """Start a new long running process unless already started."""
        if not request.session.has_key('running_job'):
            request.session['running_job'] = {}
    
        job_name = request.GET.get('job_name')
        # print request.session['running_job']
        #
        if job_name  not in request.session['running_job']:
            job_execfile = ''
            if job_name == 'flower':
                job_execfile = " myjob.py"
            if job_name == 'worker':
                job_execfile = " myjob.py"
             
            if job_execfile:   
                # create a temporary file to save the results
                outfd,outname=mkstemp()
                # request.session['jobfile']=outname
                outfile=fdopen(outfd,'a+')
                # print job_workspace
    
                proc=Popen((PYTHON_ROOT + job_execfile).split(),shell=False,stdout=outfile,cwd=job_workspace)
                # remember pid to terminate the job later
                request.session['running_job'][job_name]=proc.pid
                # remember tempfile to delete the job later
                request.session['running_job'][job_name+'_tmpfile']=outname
    
        return JsonResponse(request.session['running_job'], safe=False) 
    
    def showjob(request):
        """Show the last result of the running job."""
        # print request.session
    
        if not  request.session.has_key('running_job'):
            RUNNING_JOB_DIC = {}
            return JsonResponse(RUNNING_JOB_DIC, safe=False) 
        else:
            RUNNING_JOB_DIC = request.session['running_job']
            return JsonResponse(RUNNING_JOB_DIC, safe=False) 
    
    def rmjob(request):
        """Terminate the runining job."""
        request.session.modified = True
        if request.session.has_key('running_job'):
            job_name = request.GET.get('job_name')
            #if the job in running dict()
            if request.session['running_job'].has_key(job_name):
                jobpid =  request.session['running_job'][job_name]
                filename = request.session['running_job'][job_name + '_tmpfile']
                print jobpid,filename
                # if the job has finished already
                if not psutil.pid_exists(jobpid):
                    # make sure running_job dictionary   has delete
                    #try:
                    del request.session['running_job'][job_name]
    
                    del request.session['running_job'][job_name + '_tmpfile']
                    #print  request.session['running_job'] 
                    return JsonResponse(request.session['running_job'], safe=False) 
                try:
                    print  jobpid,filename
                    kill(jobpid,signal.SIGKILL) # unix only
                    unlink(filename)
                except OSError, e:
                    # probably the job has finished already
                    return JsonResponse({'error':'kill pid or unlink tmpfile error!'})
    
                del request.session['running_job'][job_name]
                del request.session['running_job'][job_name + '_tmpfile']
    
        return JsonResponse(request.session['running_job'], safe=False) 
    

    前端代码:

    <script src="/static/js/jquery.min.js"></script>
    <script>
    setInterval(function() {
        $.getJSON("/showjob/", function(json){
          console.log(json);
          if(typeof json.flower == "undefined"){
            $("#resulist tr:eq(0) td:nth-child(2)").html("stop"); 
          }
          else{
            $("#resulist tr:eq(0) td:nth-child(2)").html("running"); 
          }
    
          if(typeof json.localworker == "undefined"){
            $("#resulist tr:eq(1) td:nth-child(2)").html("stop"); 
          }
          else{
            $("#resulist tr:eq(1) td:nth-child(2)").html("running"); 
          }
    
        });
        
    }, 1000);
    
    function start_stop(myservice)
    {
    if (myservice === "startflower")
      {
         $.get("/startjob/?job_name=flower",function(data,status){
            $("#resulist tr:eq(0) td:nth-child(2)").html("running");   }
          );
      }
    if (myservice === "stopflower")
      {
         $.get("/rmjob/?job_name=flower",function(data,status){
            $("#resulist tr:eq(0) td:nth-child(2)").html("stop"); }
          );
      }
    
    
    if (myservice === "startlocalworker")
      {
         $.get("/startjob/?job_name=localworker",function(data,status){
            $("#resulist tr:eq(0) td:nth-child(2)").html("running");   }
          );
      }
    if (myservice === "stoplocalworker")
      {
         $.get("/rmjob/?job_name=localworker",function(data,status){
            $("#resulist tr:eq(0) td:nth-child(2)").html("stop"); }
          );
      }
    
    }
    
    
    
    </script>
    
     
     
            <table class="table table-hover">
    
               
                <thead>
                <tr>
                    <th>程序</th>
                    <th>状态</th>
                     <th>操作</th>
                  
                </tr>
                </thead>
                <tbody id="resulist">
                 
                    <tr>    
                    <td>flower</td>
                    <td>stop</td>
                    <td>
                        <div class="btn-group btn-group-xs">
                          <button type="button" onclick="start_stop(this.name)"  name="startflower" class="btn btn-default">启动</button>
                          <button type="button" onclick="start_stop(this.name)"  name="stopflower"  class="btn btn-default">停止</button>
                        </div>
                     </td>
                         
                    </tr>
    
                    <tr>    
                    <td>local worker </td>
                    <td>running</td>
                    <td>
                        <div class="btn-group btn-group-xs">
                          <button type="button" onclick="start_stop(this.name)"  name="startlocalworker" class="btn btn-default">启动</button>
                          <button type="button" onclick="start_stop(this.name)"  name="stoplocalworker"  class="btn btn-default">停止</button>
                        </div>
                     </td>
                         
                    </tr>
    
                    <tr>    
                    <td>DNSLog</td>
                    <td>running</td>
                    <td>
                        <div class="btn-group btn-group-xs">
                          <button type="button"  onclick="start_stop(this.name)"  name="x"  class="btn btn-default">启动</button>
                          <button type="button"  onclick="start_stop(this.name)"  name="x"  class="btn btn-default">停止</button>
                        </div>
                     </td>
                         
                    </tr>            </tbody>
    </table>
                
    

      

    --- --- --- --- From 小小leo 的博客 --- --- --- ---
  • 相关阅读:
    根据用户行为发送客服消息
    tp5链接访问
    统计每天分享次数总和
    csv中文乱码
    Jupyter Notebook命令
    Laplace(拉普拉斯)算子
    Sobel算子
    Opencv图像连通域
    Opencv常用函数讲解
    12306 Pytho抢票代码
  • 原文地址:https://www.cnblogs.com/xiaoxiaoleo/p/5735713.html
Copyright © 2011-2022 走看看