Flask,继续使用send_static_file获取404服务静态文件 [英] Flask, Keep getting 404 serving static files using send_static_file
问题描述
我遵循了如何在Flask中提供静态文件的说明,但仍然无法正常工作.
I followed the instructions from How to serve static files in Flask, but still couldn't get it working.
这是我的项目结构:
Project_path
|
+--app
| |
| +--main.py
+--static
|
+--js
|
+--jquery-1.11.2.min.js
这里是main.py
:
@app.route('/js/<path:path>')
def serve_static(path):
root_dir = os.path.dirname(os.getcwd())
print(os.path.join(root_dir, 'static', 'js', path))
return app.send_static_file(os.path.join(root_dir, 'static', 'js', path))
这里是index.html
:
...
<script type="text/javascript" src="/js/jquery-1.11.2.min.js"></script>
...
当我访问/
时,我可以看到屏幕上打印的javascript文件的正确路径
是Project_path/static/js/jquery-1.11.2.min.js
.
And when I visit /
, I could see the correct path of javascript file printed on the screen
which is Project_path/static/js/jquery-1.11.2.min.js
.
但我还是
127.0.0.1 - - [22/Dec/2014 11:26:30] "GET /js/jquery-1.11.2.min.js HTTP/1.1" 404 -
感谢您的帮助.
编辑
逐步完成send_static_file
方法后,我发现发生了什么事.基本上,我不应该使用abspath作为参数,flask在send_static_file
中有一个判断:
EDIT
After stepping through the send_static_file
method, I find out what's going on. Basically, I shouldn't use abspath as argument, flask has a judgement in send_static_file
:
if os.path.isabs(filename) or \
filename == '..' or \
filename.startswith('../'):
raise NotFound()
而且由于我进入的filename
是一个无礼的人,所以烧瓶会升起NotFound()
.
似乎应该传递给的是self.static_folder
的相对路径(自身为<Flask 'main'>
),在我的项目中为Project_name/app/static
.但是,我自己没有设置static_folder
,这意味着flask认为静态文件夹应该在其中.
And since the filename
I passed into is a abspath, flask raise NotFound()
.
It seems that what it supposed to be passed in is a relative path to self.static_folder
(self is <Flask 'main'>
), which, in my project, is Project_name/app/static
. However, I didn't set static_folder
myself which means flask thinks the static folder should be there.
我仍在试图找出解决方法.
I'm still trying to figure out what to do.
推荐答案
最后使它正常工作.使用 flask.send_from_directory
Finally got it working. use flask.send_from_directory
from flask import send_from_directory
@app.route('/js/<path:filename>')
def serve_static(filename):
root_dir = os.path.dirname(os.getcwd())
return send_from_directory(os.path.join(root_dir, 'static', 'js'), filename)
现在我很清楚,flask确实讨厌人们将app.py
或在我的情况下main.py
放到子目录中. 仅在烧瓶认为是静态文件夹的情况下才使用send_static_file
,即与app.py在同一目录中名称为static
的文件夹.
It is now clear to me that flask really hate people putting app.py
or in my case main.py
into a subdirectory. Use send_static_file
only if your static folder is what flask thinks to be, i.e. a folder with name static
in the same directory with app.py.
这篇关于Flask,继续使用send_static_file获取404服务静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!