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


当前回答

你可以使用这个函数:

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

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

其他回答

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

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

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

最简单的方法是在主项目文件夹中创建一个静态文件夹。包含。css文件的静态文件夹。

主文件夹

/Main Folder
/Main Folder/templates/foo.html
/Main Folder/static/foo.css
/Main Folder/application.py(flask script)

图像的主文件夹包含静态和模板文件夹和烧瓶脚本

from flask import Flask, render_template

app = Flask(__name__)

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

html(布局)

<!DOCTYPE html>
<html>
    <head>
        <title>Project(1)</title>
        <link rel="stylesheet" href="/static/styles.css">
     </head>
    <body>
        <header>
            <div class="container">
                <nav>
                    <a class="title" href="">Kamook</a>
                    <a class="text" href="">Sign Up</a>
                    <a class="text" href="">Log In</a>
                </nav>
            </div>
        </header>  
        {% block body %}
        {% endblock %}
    </body>
</html>

html

{% extends "layout.html" %}

{% block body %}
    <div class="col">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Login">
    </div>
{% endblock %}

这对我来说很管用:

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:])

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

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