1 回答

TA貢獻1946條經驗 獲得超4個贊
PHP將代碼與 HTML 混合在一起會造成大混亂。但 Flask 試圖將其分開。
在渲染模板之前檢查文件是否存在于代碼中并僅將結果發送到模板 - 即。
return render_string(...., file_exist=os.path.isfile('file.txt'))
并在模板中
{% if file_exist %}
編輯:
通常文件位于子文件夾中,您應該使用
os.path.isfile('subfolder/file.txt')
甚至
os.path.isfile('/full/path/to/file.txt')
編輯:
問題比較復雜。服務器需要更長的時間在單獨的線程中創建文件,因此當服務器檢查時該文件還不存在isfile()。它需要 JavaScript 和 AJAX,它將定期向其他功能(即/check)發送請求,并且它會True從.Falseisfile()
使用純 JavaScript 的最小工作示例,XMLHttpRequest但您可以嘗試fetch()使用庫來編寫它jQuery
from flask import Flask, render_template_string
import threading
import time
import os
# delete only for test code
#if os.path.isfile('file.txt'):
# os.unlink("file.txt")
class ExportingThread(threading.Thread):
def run(self):
time.sleep(5)
file = open("file.txt", "w")
file.close()
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
exporting_threads = ExportingThread()
exporting_threads.start()
return render_template_string('''<!DOCTYPE html>
<html>
<head>
<style>
.hidden {display:none;}
</style>
</head>
<body>
<button id="button" type="submit" class="hidden" onclick="window.open('file.doc')">Download!</button>
<script>
// ask server if file exists
function check() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
if(this.responseText == 'True') {
// show button
document.getElementById("button").classList.remove("hidden");
// stop checking
clearTimeout(timer);
}
}
};
xhttp.open("GET", "/check", true);
xhttp.send();
}
// repeate function `check` every 1000ms (1s)
var timer = setInterval(check, 1000);
</script>
</body>
</html>''')
@app.route('/check')
def check():
return str(os.path.isfile('file.txt'))
if __name__ == '__main__':
app.run()
添加回答
舉報