当前位置:实例文章 » 其他实例» [文章]文件夹图片批量上传到数据库

文件夹图片批量上传到数据库

发布人:shili8 发布时间:2025-02-08 19:10 阅读次数:0

**文件夹图片批量上传到数据库**

在实际项目中,经常会遇到需要批量上传大量图片的需求。例如,在一个社交媒体平台上,用户可能会上传数千张照片作为他们的个人资料或分享给朋友们。在这种情况下,使用传统的单个图片上传方式显然是不合适的,因为它不仅耗时,而且还可能导致数据库负载过重。

因此,我们需要一种高效、批量化的方法来处理这些图片。这里我们将介绍如何利用 Python 和 Flask 来实现一个文件夹图片批量上传到数据库的系统。

### **依赖和环境**

* Python3.7+
* Flask2.x* SQLAlchemy1.4.x* Pillow8.x### **项目结构**

bashproject/
app.pymodels.pyschemas.pyutils.pyrequirements.txtconfig.pytemplates/
index.htmlstatic/
style.cssimages/
image1.jpgimage2.jpg...


### **配置和依赖安装**

首先,我们需要在 `config.py` 中定义我们的数据库连接信息:

# config.pyclass Config:
 SQLALCHEMY_DATABASE_URI = 'sqlite:///example.db'
 SQLALCHEMY_TRACK_MODIFICATIONS = False


然后,在 `requirements.txt` 中列出我们所需的依赖:

Flask==2.0.1SQLAlchemy==1.4.30Pillow==8.3.2


最后,使用 pip 安装这些依赖:

bashpip install -r requirements.txt


### **模型定义**

在 `models.py` 中,我们需要定义一个用于存储图片的模型。这里我们使用 SQLAlchemy 来定义这个模型:

# models.pyfrom sqlalchemy import Column, Integer, String, DateTimefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerfrom config import ConfigBase = declarative_base()

class Image(Base):
 __tablename__ = 'images'

 id = Column(Integer, primary_key=True)
 name = Column(String(100), nullable=False)
 path = Column(String(200), nullable=False)

 def __repr__(self):
 return f"Image('{self.name}', '{self.path}')"


### **批量上传逻辑**

在 `utils.py` 中,我们需要实现一个用于批量上传图片的函数:

# utils.pyimport osfrom PIL import Image as PilImagefrom config import Configfrom models import Base, sessiondef batch_upload_images(folder_path):
 """
 Batch upload images from a folder to the database.

 Args:
 folder_path (str): The path of the folder containing images.
 """

 # Create the engine and bind it to the current thread engine = sessionmaker(bind=Config.SQLALCHEMY_DATABASE_URI)()

 # Create all tables in the engine. This is equivalent to "Create Table"
 # statements in raw SQL.
 Base.metadata.create_all(engine)

 # Get a session from the engine session = engine # Iterate over each file in the folder for filename in os.listdir(folder_path):
 # Check if it's an image file if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
 # Open the image using Pillow img = PilImage.open(os.path.join(folder_path, filename))

 # Get the image dimensions and create a new Image object width, height = img.size name = os.path.splitext(filename)[0]
 path = os.path.join(folder_path, filename)

 # Create a new Image object and add it to the session image = Image(name=name, path=path)
 session.add(image)

 # Commit the changes session.commit()


### **Flask API**

在 `app.py` 中,我们需要创建一个 Flask 应用程序来处理 HTTP 请求:

# app.pyfrom flask import Flask, request, jsonifyfrom config import Configfrom models import Base, sessionfrom utils import batch_upload_imagesapp = Flask(__name__)
app.config.from_object(Config)

@app.route('/upload', methods=['POST'])
def upload_image():
 """
 Upload an image to the database.

 Args:
 folder_path (str): The path of the folder containing images.
 """

 # Get the folder path from the request body folder_path = request.json.get('folder_path')

 # Call the batch_upload_images function batch_upload_images(folder_path)

 return jsonify({'message': 'Image uploaded successfully'}),200if __name__ == '__main__':
 app.run(debug=True)


### **测试**

最后,我们需要测试我们的 Flask 应用程序:

bashpython -m unittest test_app.py


这将运行所有的测试用例。

### **总结**

在本文中,我们介绍了如何使用 Python 和 Flask 来实现一个文件夹图片批量上传到数据库的系统。我们定义了一个用于存储图片的模型,实现了一个用于批量上传图片的函数,并创建了一个 Flask 应用程序来处理 HTTP 请求。最后,我们测试了我们的 Flask 应用程序。

希望这篇文章对你有所帮助!

相关标签:oracle数据库
其他信息

其他资源

Top