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)
If you look at the docs for send_from_directory
you'll see that it takes the path to the directory in which the files are held on disk. Unless you have your image files saved in a root-level directory named static
, you'll want to update your file path:
send_from_directory("/some/path/to/static", "my_image_file.jpg")
That being said, if you are using this for anything that will be under any load, it is better to ensure that your web server serves the files, rather than serving static files from your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With