使用Flask返回多个图像文件

M. *_* R. 3 python flask

首先,我进行了很多搜索,但仍未找到我的问题的直接答案。

我正在编写一个新程序,该程序接受图像,然后找到与其相似的图像,然后从数据库中提取图像名称。我使用python3中的Flask创建了一个简单的响应,将这些图像文件的名称作为JSON格式。我需要将这些图像及其名称显示为在Flask中带有响应的网页。主要的问题是图像的数量不是固定的,并且可能会有所不同,有时变为10,有时变为0。实际上,我不熟悉Flask或HTML,但是我需要这样做。这是我的示例代码,将图像名称作为数组进行响应:

from flask import Flask, jsonify, request, redirect, send_file
import numpy
import os
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_image():
    # Check if a valid image file was uploaded
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)

        file = request.files['file']

        if file.filename == '':
            return redirect(request.url)

        if file and allowed_file(file.filename):
            # The image file seems valid! Detect faces and return the result.
            return detect_faces_in_image(file)

    # If no valid image file was uploaded, show the file upload form:
    return '''
    <!doctype html>
    <title>Face System</title>
    <h1>Upload a picture and see if it's a picture of database!</h1>
    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="Upload">
    </form>
    '''


def detect_faces_in_image(file_stream):
    ...     #some coding to create the founded_file_names
    out=founded_file_names      #array of desired file names
    return jsonify(out)
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)
Run Code Online (Sandbox Code Playgroud)

谢谢。

Tra*_*son 5

首先,不要将HTML硬编码到您的python文件中。创建templates/目录,然后将所有这些html放入文件中,比如说homepage.html。然后,您可以使用return render_template('homepage.html')呈现html。


现在,主要问题。

主要问题是图像数量不固定并且可能会有所不同,有时变为10,有时变为0。

如果您使用烧瓶中随附的Jinja,那将不是问题。如果您不熟悉它,请参阅docs

查看您的代码,最好的方法是:在用户提交图像后,您可以显示另一个页面,说一说results.html(您应该将其放入templates/),然后在此处显示图片。

from flask import Flask, jsonify, request, redirect, send_file
import numpy
import os
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_image():
    # Check if a valid image file was uploaded
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)

        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)

        if file and allowed_file(file.filename):
            # The image file seems valid!
            # Get the filenames and pass the on to the results.html page
            return render_template(
                'results.html', results=detect_faces_in_image(file)
            )

    # If no valid image file was uploaded, show the file upload form:
    return render_template('homepage.html')


def detect_faces_in_image(file_stream):
    # .. do something here ...
    return file_names_found # list of the filenames, no need for JSON

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)
Run Code Online (Sandbox Code Playgroud)

现在,前端。这是一个大概的草稿results.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Results</title>
</head>
<body>
    {% if results %}
        <table>
            <tbody>
            {% for img_name in results %}
                <tr>
                    <td>{{ img_name }}</td>
                    <td><img src="/pathtoyourimg" alt="{{ img_name }}"></td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    {% else %}
        No results :(
    {% endif %}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

您可以看到Jinja语法与python非常相似(if / else,表示..中的..)。要使用变量,您必须将其括起来{{ }}。HTML文件的作用是:

  • 检查是否 results if an empty list
    • 如果是,则显示“无结果:(”
    • 如果不是,则显示一个html表。对于每个结果,我们将创建一行(<tr>),并在左侧显示名称,在右侧显示图像

您应该将所有图像存储static/在python脚本旁边的文件夹中。如果这样做,src="/pathtoyourimg"将成为src="static/{{ img_name }}"