2017-09-23 18 views
0

我是新來的蟒蛇,也芹菜我開始使用今天而已,我想讀的更新文件定期 我已經使用了這些:Reading from a frequently updated filePython - Reading from a text file that is being written in WindowsRead from a log file as it's being written using python但他們甚至沒有閱讀文件,更不用說定期!Django的:在形式定期讀取升級文件和數據顯示

我的看法是:

def myView(request): 
title = 'Algorithms' 
if request.method == 'GET': 
    template = 'algoInput.html' 
    form = AlgoInputForm() 
    context = {'title': title, 'form': form} 

if request.method == 'POST': 
    form = AlgoInputForm(request.POST, request.FILES) 
    if form.is_valid(): 
     task = configAndRun(form.cleaned_data) 
     output = readFile.delay('algorithms/out-file.txt') 

     template = 'result.html' 
     result = AlgoResult(initial={'outputData': output}) 
     context = {'title': title, 'form': form, 'result': result} 

return render(request, template, context) 

以上configAndRun方法使用的子進程來運行一個艱鉅的任務,它創建一個文件,你可以在那裏所有輸出到一個文件中把它想象成ping google。 下一個方法readFile讀取該文件並顯示輸出。它是一種芹菜tasks.py如下:

from celery import shared_task 

@shared_task 
def readFile(file): 
try: 
    file = open(file, "r") 
    loglines = follow(file) 
    data = [] 
    for line in loglines: 
     data.append(line) 
    return data 
except Exception as e: 
    raise e 

def follow(thefile): 
    thefile.seek(0,2) 
    while True: 
     line = thefile.readline() 
     if not line: 
      time.sleep(0.1) 
      continue 
     yield line 

我的形式是:

class AlgoInputForm(forms.Form): 
    epoch = forms.IntegerField(label='Epoch', help_text='Enter Epoch.') 
    learnRate = forms.IntegerField(label='Learning rate(η)', help_text='Enter Epoch.') 
    miniBatch = forms.IntegerField(label='Mini-batch size(B)', help_text='Enter Mini-batch size.') 
class AlgoResult(forms.Form): 
    outputData = forms.CharField(label='Evaluation Results', required=False,widget=forms.Textarea(attrs={'rows': 30, 'cols': 80, 'readonly': 'readonly'})) 

我celery.py是:

from __future__ import absolute_import, unicode_literals 
import os 
from celery import Celery 

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebApp.settings') 

app = Celery('WebApp') 

app.config_from_object('django.conf:settings', namespace='CELERY') 

app.autodiscover_tasks() 

@app.task(bind=True) 
def debug_task(self): 
    print('Request: {0!r}'.format(self.request)) 

當我運行這個項目,我得到這樣的5997dad7 -c1b9-4258-8f4d-8e45ebcf1c78作爲我的AlgoResult表單上的輸出。

你能否給我指點一下。 A碼可以理解

回答

0

你們看到在您的形式其實是芹菜TASK_ID

你不能指望靜態Django的形式異步行爲,並按照你的任務執行和更新了自己的面前。

你應該通過實現其中一種技術(WebSocket,長池等)來實現異步更新到你的前端。