Python models 模块,Task() 实例源码

我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用models.Task()

项目:crondeamon    作者:zhoukunpeng504    | 项目源码 | 文件源码
def runrecord(request):
    "????"
    getinfo=request.GET
    postinfo=request.POST
    tid=getinfo.get("tid")
    page=getinfo.get("page",'1')
    rows=getinfo.get("rows","10")
    page,rows=int(page),int(rows)
    buff={}
    task=Task.objects.get(pk=int(tid))
    runlog=Runlog.objects.filter(tid=int(tid)).order_by("-rid")
    buff["records"]=runlog.count()
    paginator=Paginator(runlog,rows)
    buff["total"]=paginator.num_pages
    try:
        page_obj=paginator.page(page)
    except:
        page_obj=paginator.page(paginator.num_pages)
    buff["page"]=page_obj.number
    buff["rows"]=[{"cell":[i.get_type(),i.get_code_info(task),i.get_crondatetime(),i.get_begindatetime(),i.get_enddatetime(),i.get_status(),i.rid]} for i in page_obj]
    return  HttpResponse(json.dumps(buff,ensure_ascii=False,indent=True),mimetype="application/javascript")
项目:TWEleReceipt    作者:hsucw    | 项目源码 | 文件源码
def getTask():

    tasks = Task.objects.filter( queued=False, solved = False ).order_by('fail_cnt')
    dblog.info( "Tasks remain : {}" .format( len( tasks ) ))

    if tasks:
        task = tasks[0]
        task.queued = True
        task.save()
        thread.start_new_thread( taskTimeOut, (150, task.id))
        task = task.as_json()
        task['result'] = 'success'
        dblog.debug( "task send to client : {}".format(task) )

        return json.dumps( task )
    else:
        return json.dumps( { "result":"error" } )
项目:TWEleReceipt    作者:hsucw    | 项目源码 | 文件源码
def addTask( task ):

    tskDate = datetime.strptime(task['date'],"%Y/%m/%d")
    if tskDate.date() > date.today():
        dblog.warn("Cannot add task, dateOverToday:{}".format(tskDate.date()))
        return
    if task['fail_cnt'] >= 5:
        dblog.warn("Cannot add task, fail count limit")
        return

    #if len( Task.objects.filter(receipt = task['receipt']) ) == 0 :
    try:
        Task.objects.create(
            receipt = task['receipt'],
            date = task['date'],
            direction = task['direction'],
            distance = task['distance'],
            fail_cnt = task['fail_cnt'],
        )
    except Exception, e:
        dblog.error( str(e) )
        #traceback.print_exc(file=sys.stdout)
        dblog.warn("Cannot add Task, already exists")

    return
项目:ClassGotcha-Backend    作者:ClassGotcha    | 项目源码 | 文件源码
def create(self, validated_data):
        # if no involved
        # if 'involved' in validated_data and validated_data['involved'] == []:
        #   # deal with involved later on
        #   del validated_data['involved']

        task = Task.objects.create(**validated_data)

        # TODO: Task add to all classroom users immediately
        if task.task_of_classroom_id:
            task.involved.add(*task.task_of_classroom.students.all())

        elif task.group:
            task.involved.add(*task.group.members.all())

        return task
项目:bid2charge    作者:soton-agents    | 项目源码 | 文件源码
def validate_task(sender, instance, **kwargs):
    instance.full_clean()



# @receiver(post_save, sender=Task)
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def sudomain(request):
    '''??????????''' 
    history_tasks = Task.objects.filter(Q(status = 'SUCCESS') | Q(status ='FAILURE')).order_by('-add_time').values()
    return render(
        request,
        'task_history.html',
        context_instance = RequestContext(request,
        {
        'task_objs': history_tasks,
        'is_null': Task.objects.filter(Q(status = 'SUCCESS') | Q(status ='FAILURE')).count() == 0
        })
    )
# end def sudomain
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def atk_add(request):
    '''?????????'''
    #print 100*"b"
    if request.method == 'GET':
        form = TaskAddForm()
    else:
        form = TaskAddForm(request.POST)
    # end if
    if not form.is_valid():
        #print 1000*'A'
        return render(
        request,
        'task_add.html',
        context_instance = RequestContext(request,
        {
             'form': form ,
        })
    # end if
    )

    attack_route = form.cleaned_data.get('attack_route','') 
    target = form.cleaned_data.get('target','') 
    task_name   = form.cleaned_data.get('task_name', '')  
    target = target.strip()
    #print 100*'A'
    #ATK?????????ATK_K0,ATK_K1...
    task = Task(attack_target = target, attack_type = 'ATK_'+str(attack_route),task_name = task_name, status = 'WAITTING') 
    task.save()
    transaction.commit()

    print ">>>>>>>Staring Multi Module ATTACK  %s<<<<<<<" % str(target)


    html = '<!doctype html><html><head><script>confirm("%s");  window.location = "/";</script></head><body> </html>'  
    if len('cc') > 1:
        ret = html % '??%s???' % str(target) #?????
    else:
        ret = html % '??%i???' % str(target) #?????
    # end if
    return response(ret)
# end def atk_add
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def task_queue(request):
    '''????????''' 
    if request.method == 'GET':
        queues = Task.objects.exclude(Q(status = 'SUCCESS') | Q(status ='FAILURE')).order_by('-add_time').values()
        numOfResult = len(queues)


        paginator = Paginator(queues, 10) # Shows only 10 records per page
    # end if

        page = request.GET.get('page')
        try:
            results_pag = paginator.page(page)
        except PageNotAnInteger:
        # If page is not an integer, deliver first page.
            results_pag = paginator.page(1)
        except EmptyPage:
        # If page is out of range (e.g. 7777), deliver last page of results.
            results_pag = paginator.page(paginator.num_pages)

        # end try

    max_task = int(5)
    return render(
        request,
        'task_queue.html',
        context_instance = RequestContext(request,
        {
        "num": numOfResult,
        'task_objs': results_pag,
        'max_tasks': max_task,
        })
    )
# end def task_queue
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def task_history(request):
    '''??????????''' 

    if request.method == 'GET':
        history_tasks = Task.objects.filter(Q(status = 'SUCCESS') | Q(status ='FAILURE')).order_by('-add_time').values()
        numOfResult = len(history_tasks)


        paginator = Paginator(history_tasks, 10) # Shows only 10 records per page
    # end if

        page = request.GET.get('page')
        try:
            results_pag = paginator.page(page)
        except PageNotAnInteger:
        # If page is not an integer, deliver first page.
            results_pag = paginator.page(1)
        except EmptyPage:
        # If page is out of range (e.g. 7777), deliver last page of results.
            results_pag = paginator.page(paginator.num_pages)

        # end try


    return render(
        request,
        'task_history.html',
        context_instance = RequestContext(request,
        {
        'task_objs': results_pag,
        'is_null': Task.objects.filter(Q(status = 'SUCCESS') | Q(status ='FAILURE')).count() == 0
        })
    )
# end def task_history
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def http_flow(request):
    '''??http???''' 

    if request.method == 'GET':
        history_tasks = Task.objects.filter(Q(status = 'SUCCESS') | Q(status ='FAILURE')).order_by('-add_time').values()
        numOfResult = len(history_tasks)


        paginator = Paginator(history_tasks, 10) # Shows only 10 records per page
    # end if

        page = request.GET.get('page')
        try:
            results_pag = paginator.page(page)
        except PageNotAnInteger:
        # If page is not an integer, deliver first page.
            results_pag = paginator.page(1)
        except EmptyPage:
        # If page is out of range (e.g. 7777), deliver last page of results.
            results_pag = paginator.page(paginator.num_pages)

        # end try


    return render(
        request,
        'http_flow.html',
        context_instance = RequestContext(request,
        {
        'task_objs': results_pag,
        'is_null': Task.objects.filter(Q(status = 'SUCCESS') | Q(status ='FAILURE')).count() == 0
        })
    )
# end def http_flow
项目:TWEleReceipt    作者:hsucw    | 项目源码 | 文件源码
def taskTimeOut( delay, id ):
    time.sleep( delay )
    task = Task.objects.filter( id=id )
    if task:
        task[0].queued = False
        task[0].save()
项目:TWEleReceipt    作者:hsucw    | 项目源码 | 文件源码
def getTaskObject(rcpt, dt):
    #dblog.info("get object by {} {}".format(rcpt, dt))
    try:
        return Task.objects.get(receipt=rcpt, date=dt)
    except Exception, e:
        dblog.debug("*_*_*_*_*_*_* Cannot get object {} {}".format(rcpt, dt))
        dblog.debug(e)
        return None
项目:TWEleReceipt    作者:hsucw    | 项目源码 | 文件源码
def createTaskObject(rcpt, dt, dirtn):
    #dblog.info("create object by {} {}".format(rcpt, dt, dirtn))
    try:
        return Task.objects.create(receipt=rcpt, date=dt, direction=dirtn)
    except Exception, e:
        dblog.debug("*_*_*_*_*_*_* Cannot create object {} {} {}".format(rcpt,dt,dirtn))
        dblog.debug(e)
        return None
项目:flow-dashboard    作者:onejgordon    | 项目源码 | 文件源码
def __init__(self, rkey):
        super(TaskReportWorker, self).__init__(rkey, start_att="dt_created", title="Task Report")
        self.prefetch_props = ['habit']
        self.headers = [
            "Date Created", "Date Due", "Date Done", "Title", "Done", "Archived", "Seconds Logged",
            "Complete Sessions Logged"]
项目:bid2charge    作者:soton-agents    | 项目源码 | 文件源码
def update_shortest_paths(sender, instance, **kwargs):
    # Delete all existent precomputed Shortest Paths
    ShortestPath.objects.all().delete()

    # Retrieve the complete list of tasks from the database
    tasks_db = Task.objects.all()

    for i in range(len(tasks_db)):
        for task_selection in combinations(tasks_db, i + 1):
            # Create the Home Task
            home = Task()
            home.description = "Home"
            home.x = 0.5
            home.y = 0.5

            # Transform to list, sort and insert the home task as the first in the list
            task_selection = list(task_selection)
            task_selection = sorted(task_selection, key=lambda task: task.description)
            task_selection.insert(0, home)

            # Get the shortest path by solving TSP
            path = tsp.solve_tsp(task_selection)
            total_cost = math.floor(tsp.total_distance(path))

            # Remove the first Task (the Home Task added at the beginning)
            path.pop(0)

            # Create a new ShortestPath object to be persisted in db
            shortest_path = ShortestPath()

            # Build the Task Selection string by concatenatig
            # all task names (description) from the initial task 
            # selection array, separated by a set separator symbol 
            shortest_path.task_selection = ";".join("{0}{1}".format(t.description, "") for t in task_selection)

            # for task in task_selection:
            #     shortest_path.task_selection += task.description + ";"
            # shortest_path.task_selection = shortest_path.task_selection[:-1]

            # Build the Solution string by concatenating all 
            # task names (description) from the computed tsp 
            # problem, separated by a set seaparator symbol.
            # Calculate the total probability of the tour.
            shortest_path.solution = ";".join("{0}{1}".format(t.description, "") for t in path)
            shortest_path.total_reward = sum(t.reward for t in path)

            # for task in path:
            #     shortest_path.solution += task.description + ";"
            #     shortest_path.total_reward += task.reward
            # shortest_path.solution = shortest_path.solution[:-1]

            # Assign the Shortest Path Cost
            shortest_path.total_cost = total_cost

            # Save the new shortest path discovered
            shortest_path.save()
项目:crondeamon    作者:zhoukunpeng504    | 项目源码 | 文件源码
def add(request):
    "????task"
    getinfo=request.GET
    postinfo=request.POST
    if getinfo.has_key("data"):
        datatype=getinfo.get("data")
        if datatype=="table":
            u"??????"
            pageindex=getinfo.get("page")
            pageindex=int(pageindex)
            rowsnum=getinfo.get("rows")
            rowsnum=int(rowsnum)
            _task=Task.objects.all().order_by("-tid")
            buff={}
            task_pageobj=Paginator(_task,rowsnum)
            buff["records"]=_task.count()
            buff["total"]=task_pageobj.num_pages
            try:
                task_list=task_pageobj.page(pageindex)
            except:
                task_list=task_pageobj.page(task_pageobj.num_pages)
            add_fail_count_to_tasklist(task_list)
            add_run_status_to_tasklist(task_list)
            buff["page"]=task_list.number
            buff["rows"]=[{"cell":[i.tid,i.name,i.get_status(),[i.running,i.count],i.project,i.app,i.get_info() ,i.owner ,i.ip]}  for i in task_list]
        elif datatype=="add":
            u"????Task"
            ip=postinfo.get("ip")
            name=postinfo.get("name")
            svnpath=postinfo.get("url").strip()
            version=postinfo.get("version")
            svnuser=postinfo.get("svnuser")
            svnpasswd=postinfo.get("svnpasswd")
            info=postinfo.get("fn")
            args=""
            filename=postinfo.get("filename")
            buff={}
            valid_result= valid_input(ip,name,svnpath,version,svnuser,svnpasswd,info,args,filename)
            if valid_result!=True:
                buff["status"],buff["message"]=valid_result
            else:
                if version=="*":
                    versioninfo=get_svn_top_version(svnurl=svnpath,svnuser=svnuser,svnpasswd=svnpasswd)
                    if versioninfo[0]==False:
                        buff["status"],buff["message"]=versioninfo
                    else:
                        version=versioninfo[1]
                if buff=={}:
                    serve=get_task_serve()
                    try:
                        result=serve.adddaemon(name,svnpath,str(version),svnuser,svnpasswd,info,request.user.username,args,filename)
                        if True == result:
                            buff["status"],buff["message"]= True,u"?????"
                        else:
                            buff["status"],buff["message"]=False,u"?????"
                    except Exception as e:
                        buff["status"],buff["message"]=False,str(e)
        return HttpResponse(json.dumps(buff,ensure_ascii=False),mimetype="application/javascript")
    cronserve=CronServe.objects.all().values()
    return  render_to_response("add_task.html",locals(),context_instance=RequestContext(request))
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def task_add(request):
    '''????'''
    if request.method == 'GET':
        form = TaskAddForm()
    else:
        form = TaskAddForm(request.POST)
    # end if
    if not form.is_valid():
        #print 1000*'A'
        return render(
        request,
        'task_add.html',
        context_instance = RequestContext(request,
        {
             'form': form ,
        })
    # end if
    )

    target = form.cleaned_data.get('target','') 

    #?????????
    if  str(request.path).lower() == '/task/add':
        attack_type   = form.cleaned_data.get('attack_type', '')    
        task_name   = form.cleaned_data.get('task_name', '')  
        target = target.strip()
        target = target.strip().split('\r\n')
        if len(target)>1:
            target = ','.join(target)# fnascan ??????
        elif len(target)==1:
            target = target[0]
        # end if
        param = dict(form.data)
        for k in param.keys():
            param[k] = param[k][0]
        # end for
        param[u'ip_range'] = target
        param_str = json.dumps(param)

        print ">>>>>>>Staring Single Module ATTACK  %s<<<<<<<" ,target
        task = Task(attack_target = target, attack_type = attack_type,task_name = task_name, status = 'WAITTING', parameter = param_str) 
        task.save()
        transaction.commit()

    # end if
    html = '<!doctype html><html><head><script>confirm("%s");  window.location = "/";</script></head><body> </html>'  
    if len('cc') > 1:
        ret = html % '??%s???' % str(target) #?????
    else:
        ret = html % '??%i???' % str(target) #?????
    # end if
    return response(ret)
# end def task_add