如何解决动态内容未使用 Django 休息框架在部署服务器上写入 docx在本地机器上工作正常
以下是步骤。
- 从包含 4 个需要在运行时替换的字段的静态文件夹中获取“static/tac_template.docx”模板文件。
- 从该文件中获取所有段落并用动态数据替换这些字段。
- 填写动态字段后,按公司名称将该文件保存在静态文件夹中。
- 将该文件转换为 pdf 并将其保存在同一个静态文件夹中
- 使用 mandrill 发送带有 pdf 附件的电子邮件。
这适用于本地机器,但不适用于部署服务器。
下面是代码。
def send_practice_welcome_email(user_id):
practice = models.Practice.objects.select_related("user").get(user_id=user_id)
temppath = create_docx(practice)
context = emails.PracticeWelcomeContext(
company_name=practice.company_name,tips_url=settings.PRACTICE_TIPS_URL,benefits_url=settings.PRACTICE_BENEFITS_URL,)
file_template=f"static/tac_template_"+practice.company_name+".pdf"
attachment_dict= {"file_name": "tac_template_"+practice.company_name+".pdf","file_path": file_template,"mime_type": "application/pdf"}
return mailer.send(emails.PRACTICE_WELCOME,practice.user.email,context,files_to_attach=[attachment_dict])
def create_docx(instance):
tac_accepted_snapshot = JSONField(null=True)
tac_template_path = f"static/tac_template.docx"
if not os.path.exists(tac_template_path):
raise FileNotFoundError
doc = Document(tac_template_path)
paragraphs = get_all_paragraphs(doc)
tac_accepted_snapshot = generate_tac_snapshot(instance)
fill_paragraphs_with_data(paragraphs,tac_accepted_snapshot)
company_template_path= f"static/tac_template_"+instance.company_name+".docx"
doc.save(company_template_path)
pdf_file=convert_docx_to_pdf_EmailAttachment(company_template_path)
return pdf_file
def convert_docx_to_pdf_EmailAttachment(path):
process = subprocess.check_output(["libreoffice","--convert-to","pdf","--outdir","/app/backend/static",path])
filename = re.search("-> (.*?) using filter",process.decode())
if filename is None:
raise LibreOfficeError(process.stdout.decode())
return filename.group(1)
def generate_tac_snapshot(practice):
date_format = "%d %B %Y"
timestamp_format = "%d %B %Y,%H:%M:%s %p"
date = datetime.datetime.utcNow()
return {
"[Date]": date.strftime(date_format),"[Company.Name]": practice.company_name,"[Company.Reg.No]": practice.company_registration_id,"[Contact.Name]": practice.contact_full_name,"[Timestamp]": date.strftime(timestamp_format),}
def get_all_paragraphs(doc):
paragraphs = list(doc.paragraphs)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
paragraphs.extend(cell.paragraphs)
return paragraphs
def fill_paragraphs_with_data(paragraphs,data):
for paragraph in paragraphs:
for key in data:
if key in paragraph.text:
paragraph.text = paragraph.text.replace(key,str(data[key]))
paragraph.style.font.name = FONT_NAME
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。