You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Flask新手求助:如何通过Flask展示图片(附404报错及代码)

Fixing Flask Image 404 Error

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:

  1. Create a static folder in your project root directory (same level as server.py and templates).
  2. Move your tree.jpg file into this static folder.
  3. In your template file, use Flask's url_for function 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 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

火山引擎 最新活动