无法从flask中的send_from_directory()中检索文件 [英] Unable to retrieve files from send_from_directory() in flask

查看:453
本文介绍了无法从flask中的send_from_directory()中检索文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < img src =img / snacks.png > 
< link href =css / bluestrap.css =stylesheet>

因此,浏览器试图通过这个方法来调用它, b

  http://127.0.0.1:5000/img/snacks.png 

在多个文件中有很多这样的引用,因此更改引用是不可能的。我如何从FLASK提供这些静态文件



我已经将所有这些静态文件复制到静态文件夹,并试过这个

  @ app.route('/< path:filename>')
def send_file(filename):
return send_from_directory('/ static' ,文件名)

然而,这是行不通的,有没有其他办法可以做到这一点?或者我做错了什么?在生产中,你不想使用瓶服务器来提供静态文件。我建议你使用一个合适的Web服务器来做到这一点。



对于开发者,因为你不想使用 url_for ,你可以尝试初始化你的烧瓶应用程序,如下所示。这样,烧瓶就知道你的静态文件在哪里。

  app = Flask(__ name__,static_folder ='static')

@ app.route(' /< path:filename>')
def send_file(filename):
return send_from_directory(app.static_folder,filename)

看到这个帖子有很多信息
Flask - robot.txt,sitemap.xml(mod_wsgi)中的静态文件


I have a html file which references static object like this

<img src="img/snacks.png">
<link href="css/bluestrap.css" rel="stylesheet">

Hence the browser tries to call this via and flask fails to do so

http://127.0.0.1:5000/img/snacks.png  

There are lots of such references across multiple files hence changing the references is not possible. How do i serve these static files from FLASK

I have copied all these static files to the 'static' folder and tried this

@app.route('/<path:filename>')  
def send_file(filename):  
      return send_from_directory('/static', filename)

However this does not work, Is there any other way to do this ? or what am i doing wrong ?

解决方案

In production, you don't want to serve static files using the flask server. I suggest you use a proper web server to do that.

For dev, since you don't want to use url_for, you can try to initialize your flask app as below. This way, flask knows where your static files are.

app = Flask(__name__, static_folder='static')  

@app.route('/<path:filename>')  
def send_file(filename):  
    return send_from_directory(app.static_folder, filename)

See this post with a lot of info Static files in Flask - robot.txt, sitemap.xml (mod_wsgi)

这篇关于无法从flask中的send_from_directory()中检索文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆