【问题标题】:Flask redirect page after response is complete响应完成后烧瓶重定向页面
【发布时间】:2021-03-09 03:13:04
【问题描述】:

所以我目前在我的 html 脚本中有一个按钮,它调用路由 /return-files。此路由返回带有压缩文件的响应,并且我还禁用了任何缓存,因为每次做出此响应时都尝试获取新文件时遇到问题。这运行良好,但由于我无法返回多个内容(响应和重定向),因此在向用户发送 zip 文件后无法刷新当前页面。现在我已经阅读了许多解决方案,例如使用 javascript 创建连续响应。我正在寻找最简单的技术。源码如下,感谢大家的帮助。

@app.route('/return-files')
def creareturn_files_tut():
    global itemsList
    global clientName
    try:
        if len(itemsList) <= 0:
            flash("The itemList was found to contain no items")
        else:
            taxPercent = 0.13
            ziped = FileHandler(clientName, itemsList, taxPercent)
            file = ziped.addToZip()
            os.remove(ziped.excelFileName)
            os.remove(ziped.wordFileName)
            # os.remove(file)
            itemsList = []
            clientName = None
            response = make_response(send_file(file, file, as_attachment=True))

            # remove cache for the file so that a new file can be sent each time
            response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
            response.headers["Pragma"] = "no-cache"
            response.headers["Expires"] = "0"
            response.headers['Cache-Control'] = 'public, max-age=0'

            return response
        # return out
    except Exception as e:
        return str(e)

【问题讨论】:

    标签: python flask web-applications response sendfile


    【解决方案1】:

    您可以像这样使用send_from_directory()send_file()

    file = ziped.addToZip()
    os.remove(ziped.excelFileName)
    os.remove(ziped.wordFileName)
    itemsList = []
    clientName = None
    return send_from_directory(directory='', filename=file, as_attachment=True, cache_timeout=0)
    

    file = ziped.addToZip()
    os.remove(ziped.excelFileName)
    os.remove(ziped.wordFileName)
    itemsList = []
    clientName = None
    return send_file(file, cache_timeout=0, as_attachment=True)
    

    请注意,通过将 cache_timeout 设置为 0 来禁用缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多