我有一些问题:如何捕获我在 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)
你的芹菜任务在响应中超时执行(因此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)
然后我要做的是找出一种方法来制作另一个提供文件的端点,而不是将其作为响应对象提供。