I created a small Flask app for the purpose of processing and presenting data for my local consumption on my local machine. My Flask app processes data in a subfolder and then opens a webpage to display the processed data. Everything looks great except that images are not being served. For example the resulting HTMl source will have something like:
<img src="/Users/username/Desktop/datafolder/pics/pic1.png" alt="pic1">
however there will be no image. The paths are correct so I am guessing it has to do with how images are passed, or not passed, to Flask in the render_template
. Perhaps there is a way to specify a media directory as I see in this django post?
Any suggestions on how I might be able to include images would be very welcome.
best regards, zach cp
Edit: As mentioned in the answers and comments, all static files must be in the designated static directory. My use of the "file://" construct triggered the browser to give an error message: "Not allowed to load local resource: file:///Users/username/Desktop/datafolder/pics/pic1.png"
which is why I could not see the image. I could use any of the solutions below that result in the images I want to have served in the designated static folder.
The Flask application defaults the files where it attempts to serve static files as the "static" path in the root directory for the application. Thus, if you run your program in...
C:\Users\username\Desktop\MyApp
the static folder will be
C:\Users\username\Desktop\MyApp\Static
Thus, when attempting to serve
/Users/username/Desktop/datafolder/pics/pic1.png
the file Flask will try to serve will actually be...
C:\Users\username\Desktop\MyApp\Static\Users\username\Desktop\datafolder\pics\pic1.png
This probably isn't right.
Therefore, you can do a few things:
Change the files that are being processed to the "static" folder of where you Flask app is running from, and make the HTML src value relative to that directory
Set the static_folder
parameter on the Flask constructor. This allows you to set specifically where the static files will be served from.
app = Flask(static_folder='C:\\Some\\Directory')
As some comments have suggested, change to using the file:// type. If it doesn't work, then post what you're trying, because it should work :)
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