简体   繁体   English

在 Flask/Python 中返回 stream 和模板

[英]Return stream and template in Flask/Python

After researching, I know there is no way to send_file and render_template in one return;经过研究,我知道没有办法将send_filerender_template一次返回; however, all of the other solutions pointed to a document that is stored on a server.但是,所有其他解决方案都指向存储在服务器上的文档。 Is there a workaround for a stream to send_file and load a template either in the same page or another one? stream 是否有解决方法来send_file并在同一页面或另一个页面中加载模板?

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def homes():
    if request.method == 'POST':
        document = request.files['test']
        stream = io.BytesIO(document.read())
        doc = aw.Document(stream)
        # random doc manipulation


    return send_file(doc, as_attachment=True, download_name='test.docx')
    return render_template("index.html")

You can seperate the two routes like:您可以将两条路线分开,例如:

app.py应用程序.py

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def homes():
    return render_template("index.html") <- post a link to the `download_file` route in this template

@app.route('/download_file', methods=['GET'])
def download_file():
    if request.method == 'GET'
        document = request.files['test']
        stream = io.BytesIO(document.read())
        doc = aw.Document(stream)

    return send_file(doc, as_attachment=True, download_name='test.docx')

Then in your html file use this:然后在您的 html 文件中使用:

index.html (example) index.html (示例)

<!DOCTYPE html>
<html lang="en">
<body>
    <ul>
        <li><a href="{{ url_for('download_file') }}">Download</a>
    </ul>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM