我是python的新手,也是芹菜,我今天才开始使用,我正在尝试定期读取更新文件我已经使用了这些:Reading from a frequently updated file,Python - Reading from a text file that is being written in Windows和Read 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的输出。
你能告诉我怎么走吗?一个代码将会很受欢迎
发布于 2017-09-24 06:30:01
您在表单中看到的实际上是celery task_id
您不能期望静态Django表单异步运行,并自动跟踪您的任务执行和更新前端。
您应该通过实现其中一种技术( WebSockets、长池等)来实现对前端的异步更新。
https://stackoverflow.com/questions/46384532
复制相似问题