-1

I have a flask application where I need to render an image created by Pygal (a visualization library).So I plan to give users access to this created image at an endpoint /viz

app = Flask(__name__)

@app.route("/viz")
def viz():
    img_url = '/home/souvik/PycharmProjects/ServiceHandler/static/histo_visual.svg'
    return render_template('app.html', image_url=img_url)

Below is the app.html file

<html>
<head>
     <title> Metric Visualization</title>
</head>
<body>
     <div>
         <p>Bar Chart</p>
         <object type="image/svg+xml" data="{{image_url}}">
         </object>
     </div>
</body>
</html>

Here is my project structure

enter image description here

As you can see the file histo_visual.svg does exists in the static folder.So when I run the program and try to access the /viz endpoint, I get the below error

127.0.0.1 - - [10/Apr/2018 15:08:59] "GET /viz HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2018 15:08:59] "GET /home/souvik/PycharmProjects/ServiceHandler/static/ HTTP/1.1" 404 -

Below is the page displayed

enter image description here

Why does it give 404 not found error when the file exists?I have even gone to the directory and run the file through a browser and it shows me the expected visualization.Then what is going wrong?

davidism
  • 121,510
  • 29
  • 395
  • 339
Souvik Ray
  • 2,899
  • 5
  • 38
  • 70

1 Answers1

2

When you're accessing the image through a web server, the image url must be relative to the web root. You're using the full file path of the image, but this is not accessible to the application in a web context.

Flask has a neat way of generating URLs for static files:

@app.route("/viz")
def viz():
    img_url = url_for('static', filename='histo_visual.svg')
    return render_template('app.html', image_url=img_url)

or alternatively, simply render this directly in the Jinja template:

<object type="image/svg+xml" data="{{ url_for('static', filename='histo_visual.svg') }}">
         </object>
Matt Healy
  • 18,033
  • 4
  • 56
  • 56