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


当前回答

所有的答案都很好,但对我来说工作得很好,只是使用Flask的简单函数send_file。当host:port/ApiName将在浏览器中显示文件的输出时,当你只需要发送一个html文件作为响应时,这种方法很有效


@app.route('/ApiName')
def ApiFunc():
    try:
        return send_file('some-other-directory-than-root/your-file.extension')
    except Exception as e:
        logging.info(e.args[0])```

其他回答

使用重定向和url_for

from flask import redirect, url_for

@app.route('/', methods=['GET'])
def metrics():
    return redirect(url_for('static', filename='jenkins_analytics.html'))

这个服务器在你的html中引用的所有文件(css & js…)

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

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)

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

如果您只想移动静态文件的位置,那么最简单的方法是在构造函数中声明路径。在下面的示例中,我已经将模板和静态文件移动到名为web的子文件夹中。

app = Flask(__name__,
            static_url_path='', 
            static_folder='web/static',
            template_folder='web/templates')

static_url_path= "从URL中删除任何前面的路径(即。 默认/static)。 Static_folder ='web/static'提供在文件夹中找到的任何文件 Web /static作为静态文件。 Template_folder ='web/templates'类似地,这将改变 模板文件夹。

使用这个方法,下面的URL将返回一个CSS文件:

<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">

最后,这里是文件夹结构的快照,其中flask_server.py是Flask实例:

这是最简单的方法之一。干杯!

demo.py

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

@app.route("/")
def index():
   return render_template("index.html")

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

现在创建名为templates的文件夹。 将index.html文件添加到templates文件夹中

index . html

<!DOCTYPE html>
<html>
<head>
    <title>Python Web Application</title>
</head>
<body>
    <div>
         <p>
            Welcomes You!!
         </p>
    </div>
</body>
</html>

项目结构

-demo.py
-templates/index.html

如果你只是想打开一个文件,你可以使用app.open_resource()。读取文件看起来就像这样

with app.open_resource('/static/path/yourfile'):
      #code to read the file and do something