-1

I am new to Python and Flask. I am facing issue trying serve an image:

I have image stored in the static folder and I need to send image path as json response, so that the users can see the image. I have tried os.path.abspath(), and it's giving me full path but still the image is not accessible using that path with localhost in the browser. The solution should also be usable with mobile app.

user3568303
  • 102
  • 4

1 Answers1

1

You might want to use url_for combined with your hostname, or localhost if you just want to see it yourself.

For example:

"localhost"+url_for('static', filename='image.png')

From The Flask quickstart quide:

To build a URL to a specific function you can use the url_for() function. It accepts the name of the function as first argument and a number of keyword arguments, each corresponding to the variable part of the URL rule.

About static files:

Static Files

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

To generate URLs for static files, use the special 'static' endpoint name:

url_for('static', filename='style.css') The file has to be stored on the filesystem as static/style.css.

If you have static IP and port open to external network, don't forget to use 0.0.0.0 as your hostname if you are trying to make your page visible to others too. You might also want to use a separate web server, as suggested in the Flask docs.

Hannes Karppila
  • 969
  • 2
  • 13
  • 31
  • thanks.. But my image is in static/upload folder and url_for() is throwing error when I am giving like this url_for('static/upload', filename='image.png') – user3568303 Jul 16 '16 at 17:23