如何在Flask中提供静态文件

问题:

所以这很尴尬。我有一个我在Flask中投掷的应用程序,现在它只是提供一个静态HTML页面,其中包含一些链接到CSS和JS。我找不到文档Flask描述返回静态文件的位置。是的,我可以使用render_template,但我知道数据没有模板化。我以为send_fileurl_for是正确的,但我不能让那些工作。在此期间,我打开文件,阅读内容,并使用适当的mimetype装载Response

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)

有人想为此提供代码示例或网址?我知道这将会很简单。

回答:

首选方法是使用nginx或其他Web服务器来提供静态文件;他们将能够比Flask更有效地执行此操作。
但是,您可以使用send_from_directory从目录中发送文件,这在某些情况下可能非常方便:

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

Do 使用用户提供的路径send_filesend_static_file
 send_static_file示例:

from flask import Flask, request
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/')
def root():
    return app.send_static_file('index.html')

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to serve static files in Flask

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

51 + = 60