Flask新手求助:如何通过Flask展示图片(附404报错及代码)
Hey there! Let's break down why your image is returning a 404 and how to fix it quickly.
The Root Cause
Looking at your error log:
Flask: 127.0.0.1 - - "GET /home/n/templates/tree.jpg HTTP/1.1" 404 -
Your browser is trying to fetch the image directly from the absolute path /home/n/templates/tree.jpg, but Flask doesn't automatically serve files from the templates folder. Templates are meant for rendering dynamic HTML, not for hosting static assets like images, CSS, or JS.
The Proper Fix (Flask Best Practice)
Flask has a built-in system for static files—here's how to use it:
- Create a
staticfolder in your project root directory (same level asserver.pyandtemplates). - Move your
tree.jpgfile into thisstaticfolder. - In your template file, use Flask's
url_forfunction to generate the correct image URL:<img src="{{ url_for('static', filename='tree.jpg') }}" alt="Tree">
This will tell Flask to serve the image from the /static/tree.jpg path, which it handles automatically—no extra routes needed!
If You Really Want to Use the Templates Folder (Not Recommended)
If you have a reason to keep images in the templates folder, you can add a custom route to serve those files. Add this to your server.py:
@app.route('/templates/<path:filename>') def serve_template_assets(filename): return send_from_directory(tmpl_dir, filename)
Then in your template, reference the image as /templates/tree.jpg. But again, separating static assets into the dedicated static folder is the standard Flask approach and keeps your project organized.
Quick Check for Your Code
Make sure your server.py is correctly set up—your template folder configuration looks fine, but the key issue is how you're referencing the image in your template. Swap that direct path with url_for('static', filename='tree.jpg') and you should be good to go!
内容的提问来源于stack exchange,提问作者user9588242




