gpt4 book ai didi

python - flask : How to serve static files from under the template directory?

转载 作者:太空狗 更新时间:2023-10-30 00:56:45 25 4
gpt4 key购买 nike

我使用 Flask 并想更改我的 Assets 文件夹目录。这是我的文件夹结构:

/python
/static
/js
/img
/font
/css
/templates
/default
/css
/js
/img
/venv
app.py

我想将静态文件夹(js,css,font,img)下的所有文件夹移动到文件夹default下。但是当我这样做时,我的 css 文件和其他文件(js 等) 无法加载页面。我应该为我的应用程序设置一个属性吗?我也试过这个:

app = Flask(__name__,static_path="/templates/default")

但是做不到。还有其他方法吗?非常感谢。

更新:当我删除上面一行中的前导斜杠 (static_path="templates/default") 时出现此错误 ValueError: urls must start with a leading slash 与回溯:

Traceback (most recent call last):
File "app.py", line 17, in <module>
app = Flask(__name__,static_path="templates/default")
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 481, in __init__
view_func=self.send_static_file)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 63, in wrapper_func
return f(self, *args, **kwargs)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 943, in add_url_rule
rule = self.url_rule_class(rule, methods=methods, **options)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/werkzeug/routing.py", line 550, in __init__
raise ValueError('urls must start with a leading slash')
ValueError: urls must start with a leading slash

最佳答案

初始化app时应该是static_folder而不是static_path。

app = Flask(__name__,static_folder="/templates/default")

在模板中:

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

希望对您有所帮助。

关于python - flask : How to serve static files from under the template directory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com