django:定期读取UPDATING文件并以

时间:2017-09-23 21:40:15

标签: python django celery

我是python的新手,也是我今天才开始使用的芹菜,我正在尝试定期阅读更新文件 我已经使用了这些: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但他们甚至没有定期阅读文件!!

我的观点是:

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))

当我运行这个项目时,我会在我的AlgoResult表单上输出5997dad7-c1b9-4258-8f4d-8e45ebcf1c78作为输出。

你能告诉我指示吗?我们将非常感谢代码

1 个答案:

答案 0 :(得分:0)

您在表单中看到的实际上是celery task_id

您不能指望静态Django表单异步运行并跟进您的任务执行并自行更新前端。

您应该通过实施其中一种技术(WebSockets,长池等)来对您的前端进行异步更新。