【问题标题】:Flask: Download a .zip file using a GET requestFlask:使用 GET 请求下载 .zip 文件
【发布时间】:2021-05-21 10:02:31
【问题描述】:

Flask v1.1.2、Python v3.7

我正在尝试让 Flask 向我发送它根据 GET 请求生成的 .zip 文件。

我有一个页面,用户可以在其中单击下载按钮,该按钮发出 GET 请求并将键解析为值。基于此密钥创建 .zip 文件并将其移至我的 /static 文件夹。在被执行的处理程序下方:

    def download(self):
        key = request.args['action']
        zip_location = os.path.join(app.static_folder, "files.zip")
        res = self.recorder.down.download(key, zip_location)
        return send_file("static/files.zip", as_attachment=True)

我尝试使用send_filesend_from_directoryapp.send_static_file 发送文件,但它们都导致出现相同的奇怪错误:

Serving Flask app "webapp.webUI" (lazy loading) 
Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: on
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
  File "/home/pi/somepath/env/lib/python3.7/site-packages/werkzeug/wsgi.py", line 506, in __next__
    return self._next()
  File "/home/pi/somepath/env/lib/python3.7/site-packages/werkzeug/wrappers/base_response.py", line 45, in _iter_encoded
    for item in iterable:
TypeError: 'Response' object is not iterable
127.0.0.1 - - [18/Feb/2021 13:34:58] "GET /download?action=20210216+16u11s19 HTTP/1.1" 200 -

Google 帮不上什么忙,我已经搜索了几个小时的错误原因。

【问题讨论】:

    标签: python flask download response-headers


    【解决方案1】:

    试试

    from flask import Flask, request
    # set the project root directory as the static folder, you can set others.
    app = Flask(__name__, static_url_path='')
    
    @app.route('/download')
    def download():
        return app.send_static_file('files.zip')
    

    【讨论】:

    • 正如我所描述的,我已经尝试过app.send_static_file。但没有尝试设置静态网址。所以我按照你的描述设置它,但它不能解决问题。我得到了与我在原始帖子中描述的相同的错误
    • 好的,所以我通过使用self.app.add_url_rule 手动注册端点来使用flask,这似乎会导致错误。我使用@app.route 尝试了您的建议,它确实有效。很高兴知道它会起作用,现在使用add_url_rule 让它起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    相关资源
    最近更新 更多