-3

I need to access sub directories which contains images show that i can show it in HTML. How can i do this.

MyFlask Directory

Am building am image scraper. In above image I have shown my Flask directory. The name images is constant name where as the sub flder name is dynamic, it is the name of the search term i give.

This is my results.HTML

In above the {{results}} gives my dynamic name of the folder which is the search term.

davidism
  • 121,510
  • 29
  • 395
  • 339
Learner
  • 25
  • 5

1 Answers1

2

url_for provides the path to a previously defined route. I'm guessing that you did not create a route for delivering these images. You can either:

move the images-folder to your static folder

This way you can access them via

<img src="{{ url_for('static', filename='images/programming/jpg_0.jpg') }}">

or create an image-route, like

import os
from flask import send_file

@app.route('/getImage/<string:imgName>')
def getImage(imgName)
    filePath = 'ABSOLUTE_PATH'
    return send_file(os.path.join(filePath, imgName))

You can then access the images via

<img src="{{ url_for('getImage', imgName='jpg_0.jpg') }}">

You should also think about letting your static files being served directly by a web server like nginx or Apache.

Kruspe
  • 626
  • 6
  • 19
  • Hi Thanks for the amazing reply. This is starting to make sense for me as did not have idea of how URL_For works. Could you please help me with this. Here the ABSOLUTE PATH should also contain my dynamic search term right? For Ex: - filePath = "./images/Programming/jpg_0.jpg'. How will I pass Programming, from URL_For? – Learner Sep 16 '20 at 03:33
  • For the pure purpose of delivering images, I would just move them into you `static`-folder. Just create a directory called `static` in the same folder where you created your `templates`-directory. – Kruspe Sep 16 '20 at 14:16
  • `filePath` would be the path where you images are stored. The simplest would be (Windows) `C:\\Users\\User\\ ... \\images\\Programming` or (Linux) `/home/user/ ... /images/Programming`. You could also call this route with a second parameter to determine the correct filePath. You should maybe read the following: https://pythonise.com/series/learning-flask/sending-files-with-flask, https://stackabuse.com/serving-static-files-with-flask – Kruspe Sep 16 '20 at 14:20