簡體   English   中英

Flask 將 HTML 附加到 static 服務文件

[英]Flask appending HTML to a static served file

希望對於在 Flask 方面比我有更多經驗的人來說,這將是一個簡單的問題。 我正在為它提供 static 文件,我只想在 append 中提供一些 HTML 給它,或者在某些文本下方提供文件。 有什么辦法可以做到這一點,還是我以錯誤的方式接近它?

@app.route('/compile/<filename>')
def uploaded_file(filename):
    return *(Random HTML here)* + send_from_directory(app.config['UPLOAD_FOLDER'], filename)

我嘗試的一切都會產生錯誤,我找不到其他任何東西來處理這個問題。 我想也許可以從 HTML 模板打印文件,但是當我嘗試上傳文件時它給了我一個錯誤。 任何幫助將不勝感激。

這個問題可以簡化為

@route('/compile/<filename>')
def uploaded_file(filename):
    html_prefix = ...
    html_suffix = ...
    return html_prefix + content(filename) + html_suffix

獲取內容的簡單方法是

def content(filename)
    with open(os.path.join(app.config['UPLOAD_FOLDER'], filename) as f:
        return f.read()

錯誤處理是一個練習。 如果您需要更改響應的 mimetype(或將狀態碼更改為 200 以外的內容),請參閱https://flask.palletsprojects.com/en/1.1.x/quickstart/#about-responses

我認為您正在尋找的可能是iFramesend_from_directory的組合。 它用途廣泛,易於使用,對我來說最有意義。

@app.route('/compile/<path:filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/compile/')
def compile():
    return render_template('compile.html')
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Compile</title>
  </head>
  <body>
    <iframe
      src="{{ url_for('uploaded_file', filename='example.txt') }}"
      style="border: 1px solid black; width:100%;"
      ></iframe>
  </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM