使用Flask

时间:2017-06-23 18:42:20

标签: 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)

感谢。

1 个答案:

答案 0 :(得分:4)

首先,不要将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)

现在,前端。以下是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>

你可以看到Jinja语法与python非常相似(if / else,for .. in ..)。要使用变量,必须使用{{ }}将其包围。 HTML文件的作用是:

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

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