0

我正在使用 Python拥抱 APIGET为前端创建一个 API。前端可以下载创建的word文档文件,例如通过下载按钮。但是,在浏览了文档之后,我仍然无法找到一种方法来做到这一点。

到目前为止,这是我的工作脚本:

import os
import hug
from docx import Document

@hug.get("/download_submission_document")
def download_submission_document():
    file_name = 'example.docx'
    document = Document()
    document.add_heading('Test header', level=2)
    document.add_paragraph('Test paragraph')
    document.save(file_name)
    # TO DO: send a created file to frontend

我不确定我们是否可以立即发送对象,或者我们必须先将其保存在某个地方,然后再发送前端。(要求:hug,,python-docx

我正在尝试使用类似的东西

@hug.get("/download_submission_document", output=hug.output_format.file)

但不确定如何返回文件。

4

1 回答 1

1

好吧,我找到了一个比我想象的更容易的解决方案。只需执行以下操作:

@hug.get("/download_submission_document", output=hug.output_format.file)
def download_submission_document():
    file_name = 'example.docx'
    document = Document()
    document.add_heading('Test header', level=2)
    document.add_paragraph('Test paragraph')
    document.save(file_name)
    return file_name

返回file_name已经下载的docx

于 2020-04-06T14:16:37.327 回答