响应完成后的Flask重定向页面

2024-10-01 22:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我目前在html脚本中有一个按钮,用于调用路由/返回文件。这个路由返回一个带有压缩文件的响应,我还禁用了任何缓存,因为每次响应时我都无法获取新文件。这工作得很好,但由于我无法返回多个内容(一个响应和一个重定向),因此在向用户发送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)

Tags: 文件no路由cachereturnosresponsefiles
1条回答
网友
1楼 · 发布于 2024-10-01 22:36:01

您可以像这样使用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来禁用缓存

相关问题 更多 >

    热门问题