Thomas Browne
Thomas Browne

Reputation: 24898

Flask serves static file, but without images

I am trying to serve static files from Flask, but said static file contains an image which is not showing up. Here is my flask code:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return app.send_static_file("somefile.html")  

if __name__ == '__main__':
    app.run(debug = True)

And here is my html file "somefile.html" which is in the "static" sub-directory under the directory which holds the above code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <div> this is some garbage text </div>
  <img id="ansvg" src="./ppnow.svg">
</body>
</html>

The graphic is sitting in the same "static" subdirectory as somefile.html.

If I drag the html file directly into the browser, no problem, I get the graphic, but if I run the flask server and point to localhost:5000 then the graphics doesn't show up (though the text does).

What's going on? Thank you.

Upvotes: 0

Views: 370

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121584

You are serving the HTML page under the root URL, /. The browser will then load all relative URLs based of the root url.

Your image is thus going to be loaded as /ppnow.svg, not /static/ppnow.sgv.

You could fix the link to the image, or you could alter the base URL with a <base> tag:

<base href="/static/">

Note that without a domain name (an absolute URL) the base tag may be ignored by IE.

Upvotes: 2

Related Questions