如何在Flask中提供静态文件 [英] How to serve static files in Flask

查看:415
本文介绍了如何在Flask中提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这很尴尬。我有一个应用程序扔在 Flask 中,现在它只是提供一个静态的HTML页面,其中包含一些链接到CSS和JS的链接。而且我找不到在文件 Flask 中描述了返回静态文件的地方。是的,我可以使用 render_template ,但我知道数据不是模板化的。我以为 send_file url_for 是正确的,但是我无法让这些工作。与此同时,我打开文件,阅读内容,并使用合适的mimetype绑定 Response

  import os.path 
$ b $ from flask flask Flask,Response

$ b app = Flask(__ name__)
app .config.from_object(__ name__)

$ b $ def root_dir():#pragma:no cover
return os.path.abspath(os.path.dirname(__ file__))

$ b def get_file(filename):#pragma:no cover
try:
src = os.path.join(root_dir(),filename)
#找出烧瓶如何返回静态文件
#尝试:
# - render_template
# - send_file
#这应该不是那么明显
return open(src ).read()
除了IOError作为exc:
返回str(exc)


@ app.route('/',methods = ['GET' ():$ p $ b $ def $ ent,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 )
ext = os.path.splitext(path)[1]
mimetype = mimetypes.get(ext,text / html)
content = get_file(complete_path)
返回响应(content,mimetype = mimetype)


if __name__ =='__main__':#pragma:no cover
app.run(port = 80)

有人想为此提供代码示例或网址吗?我知道这是简单的。

解决方案

首选的方法是使用nginx或其他web服务器来提供静态文件;他们将能够比Flask更有效地做到这一点。



但是,您可以使用 send_from_directory 从目录发送文件,在某些情况下可能非常方便:

 从瓶子导入Flask,request,send_from_directory 

#将项目根目录设置为静态文件夹,您可以设置其他的。
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()

不使用 send_file send_static_file 与用户提供的路径。

send_static_file 示例:

  from flask import Flask,请求
#将项目根目录设置为静态文件夹,您可以设置其他项目。
app = Flask(__ name__,static_url_path ='')

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


So this is embarrassing. I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation Flask describes returning static files. Yes, I could use render_template but I know the data is not templatized. I'd have thought send_file or url_for was the right thing, but I could not get those to work. In the meantime, I am opening the files, reading content, and rigging up a Response with appropriate mimetype:

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)

Someone want to give a code sample or url for this? I know this is going to be dead simple.

解决方案

The preferred method is to use nginx or another web server to serve static files; they'll be able to do it more efficiently than Flask.

However, you can use send_from_directory to send files from a directory, which can be pretty convenient in some situations:

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 not use send_file or send_static_file with an user-supplied path.

send_static_file example:

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

这篇关于如何在Flask中提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆