Python Flask,使用 send_static_file 继续获取 404 服务静态文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27596297/
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:59:53  来源:igfitidea点击:

Flask, Keep getting 404 serving static files using send_static_file

pythonflask

提问by laike9m

I followed the instructions from How to serve static files in Flask, but still couldn't get it working.

我按照如何在 Flask 中提供静态文件的说明进行操作,但仍然无法正常工作。

Here's my project structure:

这是我的项目结构:

Project_path  
 |
 +--app
 |  |
 |  +--main.py
 +--static
    |
    +--js
       |
       +--jquery-1.11.2.min.js

Here's main.py:

这是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))

Here's index.html:

这是index.html

  ...
  <script type="text/javascript" src="/js/jquery-1.11.2.min.js"></script>
  ...

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.

当我访问时/,我可以看到屏幕上打印的 javascript 文件的正确路径
Project_path/static/js/jquery-1.11.2.min.js.

But still, I got

但是,我还是得到了

127.0.0.1 - - [22/Dec/2014 11:26:30] "GET /js/jquery-1.11.2.min.js HTTP/1.1" 404 -

Any help is appreciated.

任何帮助表示赞赏。

EDIT
After stepping through the send_static_filemethod, I find out what's going on. Basically, I shouldn't use abspath as argument, flask has a judgement in send_static_file:

编辑
在逐步完成该send_static_file方法后,我发现了发生了什么。基本上,我不应该使用 abspath 作为参数,flask 有一个判断send_static_file

if os.path.isabs(filename) or \
   filename == '..' or \
   filename.startswith('../'):
    raise NotFound()

And since the filenameI 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_foldermyself which means flask thinks the static folder should be there.

由于filenameI 传入的是一个 abspath,因此 flask raise NotFound()
似乎它应该传入的是self.static_folder(self is <Flask 'main'>)的相对路径,在我的项目中,它是Project_name/app/static. 但是,我没有设置static_folder自己,这意味着 Flask 认为静态文件夹应该在那里。

I'm still trying to figure out what to do.

我仍在努力弄清楚该怎么做。

采纳答案by laike9m

Finally got it working. use flask.send_from_directory

终于让它工作了。用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)

It is now clear to me that flask really hate people putting app.pyor in my case main.pyinto a subdirectory. Use send_static_fileonly if your static folder is what flask thinks to be, i.e. a folder with name staticin the same directory with app.py.

现在我很清楚,flask 真的很讨厌人们将app.py或在我的情况下main.py放入子目录。仅当您的静态文件夹是flask 认为的文件夹时才使用send_static_file,即名称static与 app.py 位于同一目录中的文件夹

回答by Antoine Catton

You forgot to add 'static'in the last os.path.joinin the returnclause.

您忘记在子句'static'的最后添加。os.path.joinreturn

回答by Burhan Khalid

All you need to do is, pass the static_folderparameterto the initiator:

您需要做的就是将static_folder参数传递给启动器:

static_url_path– can be used to specify a different path for the static files on the web. Defaults to the name of the static_folderfolder.

static_folder– the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

static_url_path– 可用于为网络上的静态文件指定不同的路径。默认为static_folder文件夹的名称。

static_folder– 包含应该在 static_url_path 提供的静态文件的文件夹。默认为应用程序根路径中的“静态”文件夹。

app = Flask(__name__, static_folder=os.path.abspath('/foo/bar/zoo/'))

Now, flask will look for a directory named staticin /foo/bar/zoofrom where to serve static files. You only use send_from_directoryif you are serving mediafiles which may not be in the same location as static files.

现在,flask 将寻找一个名为staticin的目录,/foo/bar/zoo从哪里提供静态文件。仅send_from_directory当您提供的媒体文件可能与静态文件不在同一位置时才使用。

回答by alone

for me this one worked :

对我来说,这个有效:

@app.route('/static/<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)       

beside adding this script into init

除了将此脚本添加到init

app._static_folder = os.path.abspath("static/")
app = Flask(__name__)

into __init__.py

进入 __init__.py

回答by bob

One possible cause of 404 error for pages you just added (even if programmed correctly), is if you have previous versions of the script (.py file) still running: make sure to close out and end (terminate) the process.

您刚刚添加的页面(即使编程正确)出现 404 错误的一个可能原因是,如果您的脚本(.py 文件)的先前版本仍在运行:确保关闭并结束(终止)进程。