0

I am using flask and AWS to deploy my website, and I need to show a random picture from my directory (pictures are named "1.jpg" with images ranging from 1 to 56) every time the service is executed. This is my current code:

import os
import random

@application.route('/predict',methods=['POST'])
def predict():
    web = str(random.choice(list(range(1,56)))) + '.jpg'
    return render_template('result.html', img = web)

And my HTML code is:

<img src="static/{{img}}" width="850" height="500"/>

The program returns the HTML but shows a blank white big box instead of the image. However, if I fix the image to, let say, "31.jpg", the image works.

<img src="static/31.jpg" width="850" height="500"/>

The same problem persists in my local machine.

  • Have you checked to make sure web actually is holds a valid string such as '31.jpg' what happens if you try to print it? – CrawfordBenjamin Sep 02 '20 at 22:04
  • This question lacks info on what `src="static/{{img}}"` actually renders to. Also you should use your browser's dev-tools Network tab to confirm that the resource is actually loading (and not a 404). It's likely that the URL needs a proceeding slash, essentially `src="/static/{{img}}"` – v25 Sep 02 '20 at 22:17
  • @CrawfordBenjamin when I render the html using a fix image '31.jpg' the image is shown properly. I don't think using numbers as names is the problem. – Juan Camilo Sep 02 '20 at 22:20
  • Oh I didn't think that was the issue. My guess is that the variable web isn't being assigned properly and therefore doesn't actually hold '31.jpg' Try printing it and see if it says what you think it should. – CrawfordBenjamin Sep 02 '20 at 22:25
  • 1
    Or maybe its not getting passed correctly? If you do inspect element or view page source what does that img tag say after the template loads? – CrawfordBenjamin Sep 02 '20 at 22:28

0 Answers0