我需要從flask中的檔案夾中公開一些圖示,如下所示:
PROJECT NAME
>> static
>> assets
>> icon-16.png
>> icon-32.png
>> icon-64.png
>> icon-80.png
>> icon-120.png
>> logo-filled.png
>> templates
>> commands.html
>> index.html
>> taskpane.html
>> app.py
我需要使assets路由可路由,以便我可以從這樣的 url 訪問 png 檔案:
https://pythonlinuxtest.azurewebsites.net/assets/icon-16.png
https://pythonlinuxtest.azurewebsites.net/assets/icon-32.png
https://pythonlinuxtest.azurewebsites.net/assets/icon-64.png
這是我app.py到目前為止所擁有的:
from flask import Flask
from flask import render_template
app = Flask(__name__)
# @app.route("/")
# def hello():
# return "Hello, World!"
@app.route("/")
def index():
return render_template("index.html")
@app.route("/taskpane.html")
def taskpane():
return render_template("taskpane.html")
@app.route("/commands.html")
def commands():
return render_template("commands.html")
我不確定如何將assets目錄添加到 app.py 以便可以訪問 png 檔案。
uj5u.com熱心網友回復:
from flask import Flask
from flask import render_template
from flask.helpers import send_file
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/taskpane.html")
def taskpane():
return render_template("taskpane.html")
@app.route("/commands.html")
def commands():
return render_template("commands.html")
@app.route("/assets/<file_name>")
def get_image(file_name):
return send_file(f"./static/assets/{file_name}",mimetype='image/png')
你能試試這個嗎
uj5u.com熱心網友回復:
我想到了!!但是,如果有人知道更好的方法,請告訴我。
我將圖片添加到 app.py 使用 send_file
現在是整個 app.py :)
from flask import Flask
from flask import render_template
from flask.helpers import send_file
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/taskpane.html")
def taskpane():
return render_template("taskpane.html")
@app.route("/commands.html")
def commands():
return render_template("commands.html")
@app.route("/assets/icon-16.png")
def icon16():
return send_file("./static/assets/icon-16.png",mimetype='image/png')
@app.route("/assets/icon-32.png")
def icon32():
return send_file("./static/assets/icon-32.png",mimetype='image/png')
@app.route("/assets/icon-64.png")
def icon64():
return send_file("./static/assets/icon-64.png",mimetype='image/png')
@app.route("/assets/icon-80.png")
def icon128():
return send_file("./static/assets/icon-80.png",mimetype='image/png')
@app.route("/assets/logo-filled.png")
def iconlogofilled():
return send_file("./static/assets/logo-filled.png",mimetype='image/png')
如果有人知道更有效的方法,我會給你答案。謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/391664.html
