Python 在 Flask 中设置静态文件夹路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27234593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:32:36  来源:igfitidea点击:

Setting up static folder path in Flask

pythonflask

提问by Stupid.Fat.Cat

Seems like my static files aren't being served properly. This is what it looks like right now:

似乎我的静态文件没有正确提供。这是它现在的样子:

myApp
    __init__.py
    static
       img
       js
         bootstrap.min.js
       etc.

This is what my app config in my __init__.pylooks like:

这是我的应用程序配置的__init__.py样子:

app = Flask(__name__, static_url_path="", static_folder="static")

This is the error:

这是错误:

127.0.0.1 - - [01/Dec/2014 13:12:01] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 -

As far as the url routing goes, no problems there, localhost/home routes to home, localhost/contact routes to contact, etc. But static files aren't being found :( Am I missing something?

就 url 路由而言,那里没有问题,本地主机/家庭路由到家,本地主机/联系人路由联系等。但是没有找到静态文件:(我错过了什么吗?

NOTE: I'm hosting this on my Mac, purely local host

注意:我在我的 Mac 上托管这个,纯本地主机

This is my __init__.pymain method:

这是我的__init__.py主要方法:

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

Running as:

运行为:

python __init.py__

采纳答案by dirn

It looks like you are hardcoding to static file URLs. You tell Flask to server them with no URL prefix -- the default would have been /static-- but the log shows the request going to /static/js/bootstrap.min.js. You probably have something like the following in a template file.

看起来您正在硬编码到静态文件 URL。您告诉 Flask 以不带 URL 前缀的方式为它们提供服务——默认是这样/static——但日志显示请求将转到/static/js/bootstrap.min.js。您可能在模板文件中有如下内容。

<script src="/static/js/bootstrap.min.js"></script>

Instead, you should use url_forto create the URL for you. Change the above to

相反,您应该使用url_for为您创建 URL。把上面的改成

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

This will result in

这将导致

<script src="/js/bootstrap.min.js"></script>