亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

服務器上不存在文件時不顯示按鈕 - 使用 Flask

服務器上不存在文件時不顯示按鈕 - 使用 Flask

小怪獸愛吃肉 2023-07-27 16:47:10
是否可以僅在我的 Flask 應用程序創建文件后才顯示下載按鈕?使用 PHP,它可能是這樣的:<style>.hidden{ display:none;}</style><?phpif(!file_exists("path") ){ $class = "hidden" }  echo "<button type=\"submit\" onclick=\"window.open(\'file.txt\')\">Download!</button>";?>我嘗試直接在 HTML 文件中使用 Python 代碼:{% if os.path.isfile('file.txt') %}    <button type="submit" onclick="window.open('file.txt')">Download!</button>{% else %}    <button type="submit" class="hidden" onclick="window.open('file.doc')">Download!</button>{% endif %}但出現錯誤:jinja2.exceptions.UndefinedError: 'os' is undefined更新@furas 回復后的完整代碼。代碼應該做什么:創建一個新線程,該線程將寫入文件。模板已呈現,并帶有隱藏的下載按鈕。文件已創建下載按鈕自動可見 - 因為現在文件存在。然而,在下面的代碼中,該按鈕在文件寫入后保持隱藏狀態。僅當創建文件后重新加載頁面時,該按鈕才會顯示。app.pyfrom flask import Flask, render_templateimport threadingimport timeimport osglobal exporting_threadsclass ExportingThread(threading.Thread):    def run(self):        time.sleep(1)                file = open("file.txt", "w")         file.close()app = Flask(__name__)app.debug = [email protected]('/')def index():    exporting_threads = ExportingThread()    exporting_threads.start()    return render_template('index.html', file_exist = os.path.isfile('file.txt'))if __name__ == '__main__':    app.run()index.html,位于“templates”文件夾內。<!DOCTYPE html><html><head>    <style>    .hidden{ display:none;}    </style></head><body>    {% if file_exist %}        <button type="submit" onclick="window.open('file.doc')">Download!</button>    {% else %}        <button type="submit" class="hidden" onclick="window.open('file.doc')">Download!</button>    {% endif %}</body></html>
查看完整描述

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()



查看完整回答
反對 回復 2023-07-27
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號