• 2023.11.22使用flask做一个简单的图片浏览器


    2023.11.22使用flask做一个简单的图片浏览器

    功能:
    实现图片浏览(翻页)功能

    程序页面:
    在这里插入图片描述

    程序架构:
    在这里插入图片描述

    注意:在flask中常会使用src=“{{ url_for(‘static’, filename=‘images/’ + image) }}”,这段代码是在Flask框架中用于获取静态文件的URL的。在Flask中,静态文件通常存放在static文件夹中,比如CSS、JavaScript或者图片文件等。url_for(‘static’, filename=‘images/’ + image)这段代码会生成一个对应静态文件的URL,其中’static’是指定静态文件夹的名称,‘images/’ + image是指定文件夹中图片的路径。

    如果image是一个变量,那么在渲染模板的时候就会根据实际的image的值来生成对应的URL。这个URL可以在前端页面中引用,用于加载静态图片文件。

    注意静态文件夹如果要改变需要另外声明。

    main.py

    import os
    from flask import Flask, render_template, request
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/preview', methods=['POST'])
    def preview():
        image_name = request.form['image_name']
        image_dir = os.path.dirname(os.path.abspath(__file__)) + '/static/uploads'
        image_list = sorted(os.listdir(image_dir))
        current_index = image_list.index(image_name)
        prev_index = current_index - 1 if current_index > 0 else None
        next_index = current_index + 1 if current_index < len(image_list) - 1 else None
        prev_image_name = image_list[prev_index] if prev_index is not None else None
        next_image_name = image_list[next_index] if next_index is not None else None
        image_url = f'/static/uploads/{image_name}'
        return render_template('preview.html', image_name=image_name, image_url=image_url, prev_image_name=prev_image_name, next_image_name=next_image_name)
    
    if __name__ == '__main__':
        app.run(debug=True)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    preview.html

    
    
    
        Image Preview
        
        
        
    
    
        

    Image Preview: {{ image_name }}

    Preview
    {% if prev_image_name %} {% endif %}
    {% if next_image_name %} {% endif %}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    index.html

    
    
    
        Image Preview
    
    
        

    Enter Image Name

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    数字藏品市场持续火热,元宇宙电商-NFG系统是如何流通和溯源?
    机器学习与模式识别作业1----吸烟者分类
    大数据技术之Hive+Flume+Zookeeper+Kafka详解
    假期酒店价格一路涨价,专家称住便宜酒店的时代可能过去了
    08、SpringCloud之SpringBoot-Admin监控组件学习笔记
    GO环境变量配置
    哈夫曼树的定义、原理及哈夫曼编码
    灰度升级 TiDB Operator
    GitHub无法访问的解决方法
    Python爬虫实战-批量爬取豆瓣电影排行信息
  • 原文地址:https://blog.csdn.net/leigh_chen/article/details/134466896