django中管理程序1

为了解决启动关闭程序方便,在django中启动结束任务的问题。

urls.py

    ################DJANGO start kill job############################
    (r'^startjob/$', app_view.startjob),
    (r'^showjob/$',  app_view.showjob),
    (r'^rmjob/$',    app_view.rmjob),
    ################DJANGO start kill job############################
 

  

views.py

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
def startjob(request):
     """Start a new long running process unless already started."""
     if not request.session.has_key('job'):
     #if True:
          # create a temporary file to save the resuls
          outfd,outname=mkstemp()
          request.session['jobfile']=outname
          outfile=fdopen(outfd,'a+')
          print job_workspace

          proc=Popen((PYTHON_ROOT+" myjob.py").split(),shell=False,stdout=outfile,cwd=job_workspace)
          # remember pid to terminate the job later
          request.session['job']=proc.pid
          print proc.pid
     return HttpResponse('A <a href="/showjob/">new job</a> has started.')

def showjob(request):
     """Show the last result of the running job."""
     if not request.session.has_key('job'):
          return HttpResponse('Not running a job.'+\
               '<a href="/startjob/">Start a new one?</a>')
     else:
          filename=request.session['jobfile']
          results=open(filename)
          lines=results.readlines()
          try:
               return HttpResponse(lines[-1]+\
                         '<p><a href="/rmjob/">Terminate?</a>')
          except:
               return HttpResponse('No results yet.'+\
                         '<p><a href="/rmjob/">Terminate?</a>')
     return response

def rmjob(request):
     """Terminate the runining job."""
     if request.session.has_key('job'):
          job=request.session['job']
          filename=request.session['jobfile']
          try:
               kill(job,signal.SIGKILL) # unix only
               unlink(filename)
          except OSError, e:
               pass # probably the job has finished already
          del request.session['job']
          del request.session['jobfile']
     return HttpResponseRedirect('/showjob/') # showjob

效果:

posted @ 2016-08-02 16:23  小小leo  阅读(173)  评论(0编辑  收藏  举报