从Flask提供HTML,找不到图片?

时间:2019-01-30 14:25:37

标签: python python-3.x flask

我正在创建Flask应用程序前端,我的index.html找不到代码中引用的图像和文件。

我尝试移动到同一文件夹,但没有成功。

服务器:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return open('html/index.html').read()

if __name__ == '__main__':
    app.run(host='localhost', port=8000, debug=True)

HTML行:

<img src="shards-logo-white.svg" alt="Example Navbar 1" class="mr-2" height="30">

<script src="js/shards.min.js"></script>
<script src="js/demo.min.js"></script>

服务器调试输出:

127.0.0.1 - - [30/Jan/2019 12:19:28] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [30/Jan/2019 12:19:29] "GET /shards-logo-white.svg HTTP/1.1" 404 -
127.0.0.1 - - [30/Jan/2019 12:19:29] "GET /html/js/shards.min.js HTTP/1.1" 404 -
127.0.0.1 - - [30/Jan/2019 12:19:29] "GET /html/js/demo.min.js HTTP/1.1" 404 -
  • 图像shards-logo-white.svg位于同一文件夹中。
  • js脚本位于子目录html-> js-> 文件中。

1 个答案:

答案 0 :(得分:1)

否,Flask不提供文件系统中的任意文件。将任何静态文件移动到static子目录中,然后通过该路径进行引用;您可以在static路径中使用嵌套目录的完整路径:

<img src="/static/shards-logo-white.svg" alt="Example Navbar 1" class="mr-2" height="30">

<script src="/static/html/js/shards.min.js"></script>
<script src="/static/html/js/demo.min.js"></script>

可以提供HTML rendered from a template,此时您可以使用{{ url_for('static', filename="shards-logo-white.svg") }}{{ url_for('static', filename="html/js/shards.min.js") }}等,让Flask为这些路径生成有效的URL

请参见Static Files section of the quickstartStatic Files chapter of the tutorial

如果您不使用模板,那么也可以将html/index.html文件作为静态文件使用。就目前而言,您既不会将其呈现为模板,也不会对文件内容进行任何其他运行时更改。

即使有时确实需要从磁盘有条件地提供文件,而不是将其全部读取到内存中,我也将使用flask.send_file() function确保文件被有效地提供并带有合理的内容类型标头:

from flask import send_file

@app.route('/')
def hello():
    return send_file('html/index.html')

相对路径针对Flask.root_path进行解析。您可能还想考虑使用flask.send_from_directory(),它可以确保文件名的用户输入不会被滥用来提供指定目录之外的任意文件。