动态内容未使用 Django 休息框架在部署服务器上写入 docx在本地机器上工作正常

问题描述

以下是步骤。

  1. 从包含 4 个需要在运行时替换的字段的静态文件夹中获取“static/tac_template.docx”模板文件
  2. 从该文件获取所有段落并用动态数据替换这些字段。
  3. 填写动态字段后,按公司名称将该文件保存在静态文件夹中。
  4. 将该文件转换为 pdf 并将其保存在同一个静态文件夹中
  5. 使用 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 (将#修改为@)