最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Flask中提供靜態(tài)文件的實(shí)例講解

 更新時(shí)間:2021年12月19日 09:54:21   作者:小妮淺淺  
在本篇文章里小編給大家分享的是一篇關(guān)于Flask中提供靜態(tài)文件的實(shí)例及相關(guān)知識(shí)點(diǎn)詳解,有興趣的朋友們可以跟著學(xué)習(xí)下。

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)烈建議不要這樣做。

因?yàn)樗赡軙?huì)導(dǎo)致用戶(hù)提供的路徑存在安全風(fēng)險(xiǎn)。

send_from_directory旨在控制這些風(fēng)險(xiǎn)。

最后,首選方法是使用NGINX或其他Web服務(wù)器來(lái)提供靜態(tài)文件,將能夠比Flask更有效地做到這一點(diǎn)。

知識(shí)點(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)文件的實(shí)例講解的文章就介紹到這了,更多相關(guān)Flask中如何提供靜態(tài)文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

蕲春县| 新干县| 长丰县| 梅州市| 崇州市| 突泉县| 余江县| 盖州市| 新沂市| 诸暨市| 萝北县| 凌源市| 新乐市| 房产| 浙江省| 南和县| 中阳县| 耿马| 工布江达县| 灵宝市| 长宁区| 西安市| 巴塘县| 固始县| 芦山县| 延长县| 嘉祥县| 镇赉县| 哈密市| 遂宁市| 三明市| 喀什市| 徐州市| 咸丰县| 磐石市| 林周县| 四子王旗| 宁晋县| 周宁县| 留坝县| 巴里|