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)

有人愿意给出一个代码示例或url吗?我知道这非常简单。


当前回答

基于其他答案的一个最简单的工作示例如下:

from flask import Flask, request
app = Flask(__name__, static_url_path='')

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

if __name__ == '__main__':
  app.run(debug=True)

使用名为index.html的HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World!</title>
</head>
<body>
    <div>
         <p>
            This is a test.
         </p>
    </div>
</body>
</html>

重要提示:index.html在一个名为static的文件夹中,这意味着<projectpath>有.py文件,<projectpath>\static有html文件。

如果你想让服务器在网络上可见,使用app.run(debug=True, host='0.0.0.0')

EDIT:如果需要显示文件夹中的所有文件,请使用此选项

@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

这基本上就是黑曼巴的答案,所以给他们点赞。

其他回答

对于angular+样板流,它创建下一个文件夹树:

backend/
|
|------ui/
|      |------------------build/          <--'static' folder, constructed by Grunt
|      |--<proj           |----vendors/   <-- angular.js and others here
|      |--     folders>   |----src/       <-- your js
|                         |----index.html <-- your SPA entrypoint 
|------<proj
|------     folders>
|
|------view.py  <-- Flask app here

我使用以下解决方案:

...
root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ui", "build")

@app.route('/<path:path>', methods=['GET'])
def static_proxy(path):
    return send_from_directory(root, path)


@app.route('/', methods=['GET'])
def redirect_to_index():
    return send_from_directory(root, 'index.html')
...

它有助于重新定义“静态”文件夹自定义。

你可以使用这个函数:

send_static_file(文件名) 内部用于发送静态数据的函数 文件从静态文件夹转移到浏览器。

app = Flask(__name__)
@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

静态文件的URL可以使用静态端点创建,如下所示:

url_for('static', filename = 'name_of_file')
<link rel="stylesheet" href="{{url_for('static', filename='borders.css')}}" />
app = Flask(__name__, static_folder="your path to static")

如果你的根目录中有模板,放置app=Flask(name)将工作,如果文件包含这个也在相同的位置,如果这个文件在另一个位置,你必须指定模板的位置,以使Flask指向该位置

我相信你会在那里找到你需要的东西:http://flask.pocoo.org/docs/quickstart/#static-files

基本上你只需要在你的包的根目录下有一个“静态”文件夹,然后你就可以使用url_for('static', filename='foo.bar')或者直接用http://example.com/static/foo.bar链接到你的文件。

编辑:正如评论中所建议的那样,你可以直接使用'/static/foo. xml '。但是url_for()开销(性能明智)是相当低的,使用它意味着你将能够轻松地自定义行为之后(改变文件夹,改变URL路径,移动你的静态文件到S3等)。