Flask中提供靜態(tài)文件的實例講解
1、可以使用send_from_directory從目錄發(fā)送文件,這在某些情況下非常方便。
from flask import Flask, request, send_from_directory
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
@app.route('/js/<path:path>')
def send_js(path):
return send_from_directory('js', path)
if __name__ == "__main__":
app.run()
2、可以使用app.send_file或app.send_static_file,但強(qiáng)烈建議不要這樣做。
因為它可能會導(dǎo)致用戶提供的路徑存在安全風(fēng)險。
send_from_directory旨在控制這些風(fēng)險。
最后,首選方法是使用NGINX或其他Web服務(wù)器來提供靜態(tài)文件,將能夠比Flask更有效地做到這一點(diǎn)。
知識點(diǎn)補(bǔ)充:
如何在Flask中提供靜態(tài)文件
import os.path
from flask import Flask, Response
app = Flask(__name__)
app.config.from_object(__name__)
def root_dir(): # pragma: no cover
return os.path.abspath(os.path.dirname(__file__))
def get_file(filename): # pragma: no cover
try:
src = os.path.join(root_dir(), filename)
# Figure out how flask returns static files
# Tried:
# - render_template
# - send_file
# This should not be so non-obvious
return open(src).read()
except IOError as exc:
return str(exc)
@app.route('/', methods=['GET'])
def metrics(): # pragma: no cover
content = get_file('jenkins_analytics.html')
return Response(content, mimetype="text/html")
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def get_resource(path): # pragma: no cover
mimetypes = {
".css": "text/css",
".html": "text/html",
".js": "application/javascript",
}
complete_path = os.path.join(root_dir(), path)
ext = os.path.splitext(path)[1]
mimetype = mimetypes.get(ext, "text/html")
content = get_file(complete_path)
return Response(content, mimetype=mimetype)
if __name__ == '__main__': # pragma: no cover
app.run(port=80)
到此這篇關(guān)于Flask中提供靜態(tài)文件的實例講解的文章就介紹到這了,更多相關(guān)Flask中如何提供靜態(tài)文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python+Selenium+phantomjs實現(xiàn)網(wǎng)頁模擬登錄和截圖功能(windows環(huán)境)
Python是一種跨平臺的計算機(jī)程序設(shè)計語言,它可以運(yùn)行在Windows、Mac和各種Linux/Unix系統(tǒng)上。這篇文章主要介紹了Python+Selenium+phantomjs實現(xiàn)網(wǎng)頁模擬登錄和截圖功能,需要的朋友可以參考下2019-12-12
Python使用ftplib實現(xiàn)簡易FTP客戶端的方法
這篇文章主要介紹了Python使用ftplib實現(xiàn)簡易FTP客戶端的方法,實例分析了ftplib模塊相關(guān)設(shè)置與使用技巧,需要的朋友可以參考下2015-06-06
Pycharm連接遠(yuǎn)程服務(wù)器并遠(yuǎn)程調(diào)試的全過程
PyCharm 是 JetBrains 開發(fā)的一款 Python 跨平臺編輯器,下面這篇文章主要介紹了Pycharm連接遠(yuǎn)程服務(wù)器并遠(yuǎn)程調(diào)試的全過程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2021-06-06
應(yīng)用OpenCV和Python進(jìn)行SIFT算法的實現(xiàn)詳解
這篇文章主要介紹了應(yīng)用OpenCV和Python進(jìn)行SIFT算法的實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

