当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: