Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why images can be shown only if they are in `static` folder?

Tags:

python

html

flask

I'm building a image recognition Flask project. And I want the image shown on the web page. Here is the structure of my project:

enter image description here

As you can see, static,templates and upload are in the same folder. If I save the image into static folder (which is generated by the VS2015 flask project) and write the result.html like this:

<!doctype html>
<h3>{{ outcome_info }}</h3>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="utf-8">
    <title>Flood Classifier</title>
</head>
<body> 
    <img src="{{url_for('static', filename=thename)}}">
</body>
</html>

The image would shown successfully when this Python function is called:

@app.route('/classify', methods=['POST','GET'])
def classify():
    global image
    image = np.expand_dims(image, axis = 0)
    result = model.predict(image)
    if result[0][0] == 1:
        result = "flood"
    else:
        result = "no flood"
    return render_template('result.html', thename = imagename, outcome_info = result)

However, if I save the image file into upload (which is created by myself), and just change the folder name in result.html like this:

<!doctype html>
<h3>{{ outcome_info }}</h3>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="utf-8">
    <title>Flood Classifier</title>
</head>
<body> 
    <img src="{{url_for('upload', filename=thename)}}">
</body>
</html>

The image would not shown when call that Python function. Do the images must be saved into static folder or there is something that I misunderstand?

like image 809
YQ.Wang Avatar asked Jun 13 '18 07:06

YQ.Wang


2 Answers

you can use this configuration:

from flask import Flask
app = Flask(__name__, static_url_path = "/upload", static_folder = "upload")

Then you can access your images as follows:

<img src='/upload/image1.jpg' width="200" height="85">

check this answer for more details: Cannot show image from STATIC_FOLDER in Flask template

like image 56
K P Avatar answered Oct 20 '22 11:10

K P


I think you misunderstand how url_for works.

The first parameter is endpoint, endpoint is roughly a registered route handler. And static is a built-in route handler which handles all requests to http://yourserver/static/xxxx.

When you set static_folder, you set the flask to serve all files under that folder through route static. You can also override this default route by setting static_url_path.

doc

like image 35
Sraw Avatar answered Oct 20 '22 11:10

Sraw