使用flask实现图片的查看、翻页操作、分类和上传

本实验使用flask制作一个图像的分类上传界面,首先介绍一下使用方法。

一、使用简介

页面如下

1、首先打开‘index.html’文件,在select标签中添加分类类别。注意:value值应和标签文本一样。

 

将需要分类的图片全部粘贴进images文件夹中。

 

 运行‘classify.py’文件。

点击下方链接

出现以下界面在地址栏后输入第几张图片,如需要定位到第5张图片

点击上一张可以切换图片。

 

点击上传按钮即可上传到对应文件夹。

 提示上传成功

此时文件夹已创建,且该图片已上传。

如果改图片已上传至此文件夹,会提示上传失败。

 此外,点击上一张下一张即可切换图片,直接在地址栏输入第几张图片也可以。

二、classify.py

import os
import shutil
from flask import Flask, render_template, request
import settings
app = Flask(__name__)
app.config.from_object(settings)
id = 0
@app.route('/<int:id>', methods=['POST', 'GET'])
def index(id):
    root_dir = os.path.abspath(os.path.dirname(__file__))
    img_path = root_dir + '/static' + '/images'  # 图片文件存储在static文件夹下的images文件夹内
    files = os.listdir(img_path)  # 获取图片文件名字
    # print(root_dir)
    # print(img_path)
    # print(type(files[0]))  # 输出一个列表,1.jpg,2.jpg
    # print(files[id])
    i = len(files)
    if id == len(files) + 1:
        id = 1
    file = "/static/images/" + files[id - 1]
    print(file)
    filename = files[id - 1]
    print(filename)
    if request.method == 'POST':
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        f = os.path.join(basepath, 'static/images', files[id - 1])  # 获取原图片路径
        val = request.form.get('sel')  # 获取图片将要分类到的文件夹名称
        print(val)
        sub_path = os.path.join(basepath, 'static/', val)  # 获取该图片将要分类到的文件夹路径
        if os.path.exists(sub_path) is False:
            os.makedirs(sub_path)
        sub_files = os.listdir(sub_path)
        # 如果图片已经存在在该文件夹下,提示上传失败
        for sub_file in sub_files:
            if files[id-1] == sub_file:
                return render_template('index_re.html', file=file, id=id, i=i, filename=filename, val=val)

        upload_path = os.path.join(basepath, 'static/', val+'/', files[id - 1])
        print(upload_path)

        # 复制图片
        shutil.copy(f, upload_path)
        return render_template('index_ok.html', file=file, id=id, i=i, filename=filename, val=val)
    return render_template('index.html', file=file, id=id, i=i, filename=filename)


if __name__ == '__main__':
    app.run()

三、index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" />
</head>
<body>
    <h1>图像分类</h1>
    <p>当前是第{{ id }}张图片,图片名为{{ filename }}</p>
    <img src="{{ file }}" width="400" height="400" alt="你的图片被外星人劫持了~~"/>
        <div class="select_beforePage_button">
        {% if id !=1 %}
            <a href="{{ url_for('index', id=id - 1) }}"><span aria-hidden="true">&larr;</span> 上一张</a>
            {% endif %}
        </div>
        <div class="select_nextPage_button">
        {% if id !=i %}
            <a href="{{ url_for('index', id=id + 1) }}" style="">下一张<span aria-hidden="true">&rarr;</span></a>
        {% endif %}
        </div>
    <br>
    <form action="" enctype='multipart/form-data' method="POST">
        <br>
        选择图片类别
        <select id="sel" name="sel" style="width: 150px;">
            <option value="花">花</option>
            <option value="猫">猫</option>
            <option value="风景">风景</option>
            <option value="狗">狗</option>
            <option value="车">车</option>
            <option value="鸟">鸟</option>
        </select>
        <input type="submit" value="上传" class="button" style="margin-top:15px;"/>
        <br>
        <br>
        {% block load %}
        {% endblock %}

    </form>
</body>
</html>

四、index_ok.html

{% extends 'index.html' %}
        {% block load %}
            <span id="ok">上传成功!上传至文件夹:"{{ val }}"</span>
        {% endblock %}

五、index_re.html

{% extends 'index.html' %}
{% block load %}
            <span id="ok">上传失败!该图片已在该文件夹中</span>
{% endblock %}

六、style.css

h1 {
    color:black;
    text-align:center;
}
p {
    font-family:"Times New Roman";
    font-size:20px;
}

.select_beforePage_button{
    position: fixed;/*固定位置*/
			}
.select_nextPage_button{
    position: fixed;/*固定位置*/
    margin-left: 350px;
			}

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Flask实现页可以使用 Flask-Pagination 扩展,该扩展可以轻松地将分页功能集成到 Flask 应用程序中。下面是一个使用 Flask-Pagination 实现页的示例代码: ```python from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy from flask_paginate import Pagination, get_page_parameter app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) content = db.Column(db.Text) @app.route('/') def index(): page = request.args.get(get_page_parameter(), type=int, default=1) per_page = 10 posts = Post.query.paginate(page, per_page) pagination = Pagination(page=page, total=posts.total, per_page=per_page, css_framework='bootstrap4') return render_template('index.html', posts=posts.items, pagination=pagination) if __name__ == '__main__': app.run(debug=True) ``` 在上述代码中,我们首先定义了一个 `Post` 模型来表示我们的博客文章。然后,在 `/` 路由函数中,我们使用 `paginate` 方法来获取指定页数的文章列表。我们还通过 `Pagination` 类来创建分页控件。最后,我们将文章列表和分页控件递给模板进行渲染。 相关问题: 1. 如何使用 Flask-Pagination 扩展实现分页功能? 2. 分页的作用是什么?为什么要使用分页? 3. Flask-Pagination 支持哪些 CSS 框架? 4. 如何在模板中渲染分页控件?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值