【发布时间】:2019-08-30 07:59:17
【问题描述】:
我现在正在处理一个需要提取附加到模型的 PDF 的项目。然后,PDF 与项目相关,如下 models.py:
class Project(models.Model):
name = models.CharField(max_length=100)
files = models.FileField('PDF Dataset',
help_text='Upload a zip here',
null=True)
class Pdf(models.Model):
name = models.CharField(max_length=100)
file = models.FileField(null=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
然后我有一个任务可以通过 Celery 触发以提取 PDF 并将每个文件保存为自己的记录。我的示例tasks.py如下:
from django.core.files.base import ContentFile
from celery import shared_task
from zipfile import ZipFile
import re
def extract_pdfs_from_zip(self, project_id: int):
project = Project.objects.get(pk=project_id)
...
# Start unzipping from here.
# NOTE: This script precludes that there's no MACOSX shenanigans in the zip file.
pdf_file_pattern = re.compile(r'.*\.pdf')
pdf_name_pattern = re.compile(r'.*\/(.*\.pdf)')
with ZipFile(project.files) as zipfile:
for name in zipfile.namelist():
# S2: Check if file is .pdf
if pdf_file_pattern.match(name):
pdf_name = pdf_name_pattern.match(name).group(1)
print('Accessing {}...'.format(pdf_name))
# S3: Save file as a new Pdf entry
new_pdf = Pdf.objects.create(name=pdf_name, project=project)
new_pdf.file.save(ContentFile(zipfile.read(name)),
pdf_name, save=True) # Problem here
print('New document saved: {}'.format(new_pdf))
else:
print('Not a PDF: {}'.format(name))
return 'Run complete, all PDFs uploaded.'
但由于某种原因,保存文档的部分不再输出 PDF。我知道原始 zip 的内容,所以我确定它们是 PDF。任何想法如何保存文件同时保留其 PDF 特性?
预期结果是 PDF 可读。现在,当我打开文件时,它显示为已损坏。感谢您在这方面的帮助。
【问题讨论】:
标签: python django python-3.x pdf celery