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吗?我知道这非常简单。


当前回答

在我的情况下,我需要一个静态文件夹中的所有文件都可以由用户访问,以及我需要为我的一些html文件使用模板,这样公共html代码可以放在模板中,代码得到重用。以下是我如何同时实现这两个目标的:

from flask import Flask, request, render_template
from flask.json import JSONEncoder

app = Flask(__name__, template_folder='static')


@app.route('/<path:path>')
def serve_static_file(path):
    # In my case, only html files are having the template code inside them, like include.
    if path.endswith('.html'):
        return render_template(path)
    # Serve all other files from the static folder directly.
    return app.send_static_file(path)

我所有的文件都保存在静态文件夹下,与主flask文件平行。

其他回答

例如,要返回我使用过的Adsense文件:

@app.route('/ads.txt')
def send_adstxt():
    return send_from_directory(app.static_folder, 'ads.txt')

这对我来说很管用:

import os
from flask import Flask, render_template, send_from_directory
app = Flask(__name__)


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

@app.route('/', methods=['GET'])
def main(request):
    path = request.path
    if (path == '/'):
        return send_from_directory(root, 'index.html')
    else:
        return send_from_directory(root, path[1:])

我相信你会在那里找到你需要的东西: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等)。

你可以使用这个函数:

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

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

我使用的是一个“模板”目录和一个“静态”目录。我把所有的.html文件/Flask模板放在模板目录中,静态包含CSS/JS。据我所知,render_template适用于通用html文件,不管你在多大程度上使用Flask的模板语法。下面是views.py文件中的一个示例调用。

@app.route('/projects')
def projects():
    return render_template("projects.html", title = 'Projects')

只要确保当您想要引用单独静态目录中的某个静态文件时使用url_for()即可。你可能会在CSS/JS文件链接的html中这样做。例如……

<script src="{{ url_for('static', filename='styles/dist/js/bootstrap.js') }}"></script>

这里有一个链接到“规范的”非正式的Flask教程——这里有很多很棒的提示,可以帮助你快速上手。

http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world