[英]How to download a file from Flask with send_from_directory?
[英]Flask send_from_directory serving html file instead of specified file
我正在生成流程图并使用 Flask 的 send_from_directory 为其提供服务。
这按预期工作:
在控制器中:
elif fcf.validate_on_submit():
subtopic = fcf.subtopicSelect.data
topic = fcf.topicSelect.data
t = Tree(topic, subtopic)
token = t.getFlowChart()
fileName = '{}.png'.format(token)
filePath = SSTempDirectory
return send_from_directory(filePath, fileName, as_attachment=True, attachment_filename = "flowchart.png")
以及模型中的相关功能:
def getFlowChart(self):
graph = pydot.Dot(graph_type='digraph')
nodeDict = {}
for c in self.cards:
newNode = pydot.Node(c.title, style="filled", fillcolor="#ffffff")
nodeDict[c.id] = newNode
graph.add_node(newNode)
for c in self.cards:
if self.triggers[c.id] != {}:
for triggerID, trigger in self.triggers[c.id].items():
nodeA = nodeDict[trigger.cardId]
nodeB = nodeDict[trigger.destinationCardId]
graph.add_edge(pydot.Edge(nodeA, nodeB, label=trigger.label))
token = secrets.token_urlsafe()
graph.write_png(os.path.join(SSTempDirectory, '{}.png'.format(token)))
return token
所有这些都按预期工作; .png 文件在没有页面刷新的情况下提供,用户可以下载它。
现在这里是另一块代码。 请注意这些是如何完全相同的:
控制器:
if af.hitCountSubmit.data:
subtopic = af.subtopicSelect.data
topic = af.topicSelect.data
t = Tree(topic, subtopic)
token = t.countCardHits()
fileName = '{}.png'.format(token)
filePath = SSTempDirectory
return send_from_directory(filePath, fileName, as_attachment=True, attachment_filename = "flowchart.png")
模型:
def getAnalyticGraph(self, cardHits):
graph = pydot.Dot(graph_type='digraph')
nodeDict = {}
for c in self.cards:
try:
newNode = pydot.Node(c.title + " - " + str(cardHits[c.id]), style="filled", fillcolor="#ffffff")
except KeyError:
newNode = pydot.Node(c.title + " - " + str(0), style="filled", fillcolor="#ffffff")
nodeDict[c.id] = newNode
graph.add_node(newNode)
for c in self.cards:
if self.triggers[c.id] != {}:
for triggerID, trigger in self.triggers[c.id].items():
nodeA = nodeDict[trigger.cardId]
nodeB = nodeDict[trigger.destinationCardId]
graph.add_edge(pydot.Edge(nodeA, nodeB))
token = secrets.token_urlsafe()
graph.write_png(os.path.join(SSTempDirectory, '{}.png'.format(token)))
return token
我可以看到文件是在正确的位置使用正确的唯一标识符正确生成的。 我可以看到我正在传递正确的文件名和文件路径。 一切都与其他代码块完全相同。 但是当文件被提供时,它是页面的 HTML 文件,而不是指定的 png 文件。
我一整天都在尝试调试它,但我什么也想不通,一切都与工作代码相同,一切都正确完成,直到 send_from_directory 函数任意返回 HTML 模板。
请帮忙,我完全不知所措。
我想到了。 我的数据库连接没有被正确关闭。 我不知道这些是如何相关的,此时我没有时间去了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.