Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

python - Unable to retrieve files from send_from_directory() in flask

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...