Celery + django - pdf generator

时间:2018-01-10 19:50:28

标签: python django pdf celery

我有一些问题:如何捕获我在tasks.py中生成的pdf文件,并在重定向到主页后自动开始下载并将下载链接放入此页面?我的task.py有效,因为我在终端看到了结果。

我的tasks.py:

@shared_task
def html_to_pdf(ctx):
    html_string = render_to_string('pdf_template.html', ctx)
    html = HTML(string=html_string)
    html.write_pdf('/tmp/report.pdf')

    fs = FileSystemStorage('/tmp')
    with fs.open('report.pdf') as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] \
            = 'attachment; filename="report.pdf"'
        return response

我的views.py:

class PdfCreatorView(View):

def get(self, request):
    form = PdfForm
    return render(request, 'home_page.html', {'form': form})

def post(self, request):
    form = PdfForm(request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        date_of_generation = form.cleaned_data['date_of_generation']
        pdf_text_content = form.cleaned_data['pdf_text_content']
        pdf_numbers_content = form.cleaned_data['pdf_numbers_content']
        ctx = {'name': name,
               'date_of_generation': date_of_generation,
               'pdf_text_content': pdf_text_content,
               'pdf_numbers_content': pdf_numbers_content}

        html_to_pdf.delay(ctx)

        url = reverse('home_page')
        return HttpResponseRedirect(url)

1 个答案:

答案 0 :(得分:0)

您的芹菜任务是在响应时执行的(因此task.delay())。当他们到达该页面时,任务很可能仍在生成PDF。如果要运行此任务然后等待,则可以执行

    ctx = {'name': name,
           'date_of_generation': date_of_generation,
           'pdf_text_content': pdf_text_content,
           'pdf_numbers_content': pdf_numbers_content}

    tsk = html_to_pdf.apply_async(ctx)
    ret = tsk.get()

    url = reverse('home_page')
    return HttpResponseRedirect(url)

然后,我要做的是找出一种方法来创建另一个提供文件的端点,而不是将其作为Response对象提供。