PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 5, 2022

[FIXED] why I do get a broken picture icon instead of the image in my folder when I run the flask app?

 May 05, 2022     flask, html, image, python, src     No comments   

Issue

I get this broken-image-icon thing when I run my flask app

    from flask import Flask
    panda = Flask(__name__)
    @panda.route("/")
    def home():
        return '''
                <body>
                    <img src="panda.jpg" 
                    alt="A picture of a panda" 
                    height="600" width="600">
                </body>
                '''
    if __name__ == "__main__":
        panda.run()

When I set the source of the <img tag to the relative or absolute path of that image (it is in the same directory as the flask app btw) the server doesn't show the image. Amazingly, when I set the source as the url of that image (it is taken from the internet) it works just fine! Could this be a problem specific to my device or maybe the web servers I use? I use Google Chrome and Microsoft Edge, same problem on both. Is it a flask thing? because the same html code works perfectly fine on its own, it is only within flask that I get this problem.

I need help, please don't answer with "just use the url then!", obviously I want to upload different images and this is just a simplified version of my actual code, this is the problem part of it, everything else is ok.


Solution

you need to use flask render templates.

File structure:

app.py
static
   |----test.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
  return render_template('index.html')

app.run()

index.html

<html>
  <head>
  </head>
  <body>
    <h1>Index page</h1>
    <img src="{{url_for('static', filename='test.jpg')}}" />
  </body>
</html>


Answered By - h1w
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing