Python FastAPI + Celery + RabbitMQ 分布式图片水印处理系统

  1. FastAPI 服务器
  2. Celery 任务队列
  3. RabbitMQ 作为消息代理
  4. 定时任务处理

首先创建项目结构:

plaintext 复制代码
c:\Users\Administrator\Desktop\meitu\
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── celery_app.py
│   ├── tasks.py
│   └── config.py
├── requirements.txt
└── celery_worker.py
  1. 首先创建 requirements.txt:
plaintext:c:\Users\Administrator\Desktop\meitu\requirements.txt 复制代码
fastapi==0.104.1
uvicorn==0.24.0
celery==5.3.4
python-dotenv==1.0.0
requests==2.31.0
  1. 创建配置文件:
python:c:\Users\Administrator\Desktop\meitu\app\config.py 复制代码
from dotenv import load_dotenv
import os

load_dotenv()

# RabbitMQ配置
RABBITMQ_HOST = os.getenv("RABBITMQ_HOST", "localhost")
RABBITMQ_PORT = os.getenv("RABBITMQ_PORT", "5672")
RABBITMQ_USER = os.getenv("RABBITMQ_USER", "guest")
RABBITMQ_PASS = os.getenv("RABBITMQ_PASS", "guest")

# Celery配置
CELERY_BROKER_URL = f"amqp://{RABBITMQ_USER}:{RABBITMQ_PASS}@{RABBITMQ_HOST}:{RABBITMQ_PORT}//"
CELERY_RESULT_BACKEND = "rpc://"

# 定时任务配置
CELERY_BEAT_SCHEDULE = {
    'process-images-every-hour': {
        'task': 'app.tasks.process_images',
        'schedule': 3600.0,  # 每小时执行一次
    },
    'daily-cleanup': {
        'task': 'app.tasks.cleanup_old_images',
        'schedule': 86400.0,  # 每天执行一次
    }
}
  1. 创建 Celery 应用:
python:c:\Users\Administrator\Desktop\meitu\app\celery_app.py 复制代码
from celery import Celery
from app.config import CELERY_BROKER_URL, CELERY_RESULT_BACKEND, CELERY_BEAT_SCHEDULE

celery_app = Celery(
    'image_processing',
    broker=CELERY_BROKER_URL,
    backend=CELERY_RESULT_BACKEND,
    include=['app.tasks']
)

# 配置定时任务
celery_app.conf.beat_schedule = CELERY_BEAT_SCHEDULE
celery_app.conf.timezone = 'Asia/Shanghai'
  1. 创建任务文件:
python:c:\Users\Administrator\Desktop\meitu\app\tasks.py 复制代码
from app.celery_app import celery_app
from app.watermark import ImageWatermarker
import os
from datetime import datetime, timedelta

@celery_app.task
def add_watermark_task(image_path, text, position='center'):
    """异步添加水印任务"""
    watermarker = ImageWatermarker()
    try:
        result_path = watermarker.add_watermark(
            image_path=image_path,
            text=text,
            position=position
        )
        return {"status": "success", "output_path": result_path}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@celery_app.task
def process_images():
    """定时处理图片任务"""
    image_dir = "images/pending"
    if not os.path.exists(image_dir):
        return {"status": "error", "message": "Pending directory not found"}

    processed = 0
    for image in os.listdir(image_dir):
        if image.lower().endswith(('.png', '.jpg', '.jpeg')):
            add_watermark_task.delay(
                os.path.join(image_dir, image),
                "自动处理水印",
                'center'
            )
            processed += 1

    return {"status": "success", "processed": processed}

@celery_app.task
def cleanup_old_images():
    """清理旧图片任务"""
    output_dir = "images/processed"
    if not os.path.exists(output_dir):
        return {"status": "error", "message": "Output directory not found"}

    threshold_date = datetime.now() - timedelta(days=7)
    cleaned = 0

    for image in os.listdir(output_dir):
        image_path = os.path.join(output_dir, image)
        if os.path.getctime(image_path) < threshold_date.timestamp():
            os.remove(image_path)
            cleaned += 1

    return {"status": "success", "cleaned": cleaned}
  1. 创建 FastAPI 应用:
python:c:\Users\Administrator\Desktop\meitu\app\main.py 复制代码
from fastapi import FastAPI, File, UploadFile, BackgroundTasks
from fastapi.responses import JSONResponse
import os
from app.tasks import add_watermark_task
from app.celery_app import celery_app

app = FastAPI(title="图片水印处理服务")

@app.post("/upload/")
async def upload_image(
    file: UploadFile = File(...),
    text: str = "水印文本",
    position: str = "center"
):
    # 保存上传的文件
    file_path = f"images/uploads/{file.filename}"
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    
    with open(file_path, "wb") as buffer:
        content = await file.read()
        buffer.write(content)
    
    # 创建异步任务
    task = add_watermark_task.delay(file_path, text, position)
    
    return JSONResponse({
        "status": "success",
        "message": "图片已上传并加入处理队列",
        "task_id": task.id
    })

@app.get("/task/{task_id}")
async def get_task_status(task_id: str):
    task = celery_app.AsyncResult(task_id)
    if task.ready():
        return {"status": "completed", "result": task.result}
    return {"status": "processing"}

@app.get("/tasks/scheduled")
async def get_scheduled_tasks():
    return {"tasks": celery_app.conf.beat_schedule}
  1. 创建 Celery worker 启动文件:
python:c:\Users\Administrator\Desktop\meitu\celery_worker.py 复制代码
from app.celery_app import celery_app

if __name__ == '__main__':
    celery_app.start()

使用说明:

  1. 首先安装依赖:
bash 复制代码
pip install -r requirements.txt
  1. 确保 RabbitMQ 服务已启动

  2. 启动 FastAPI 服务器:

bash 复制代码
uvicorn app.main:app --reload
  1. 启动 Celery worker:
bash 复制代码
celery -A celery_worker.celery_app worker --loglevel=info
  1. 启动 Celery beat(定时任务):
bash 复制代码
celery -A celery_worker.celery_app beat --loglevel=info

这个系统提供以下功能:

  1. 通过 FastAPI 接口上传图片并异步处理水印
  2. 使用 Celery 处理异步任务队列
  3. 使用 RabbitMQ 作为消息代理
  4. 支持定时任务:
    • 每小时自动处理待处理图片
    • 每天清理一周前的旧图片
  5. 支持任务状态查询
  6. 支持查看计划任务列表

API 端点:

  • POST /upload/ - 上传图片并创建水印任务
  • GET /task/{task_id} - 查询任务状态
  • GET /tasks/scheduled - 查看计划任务列表
相关推荐
0wioiw02 分钟前
Ubuntu基础(Python虚拟环境和Vue)
linux·python·ubuntu
xiao5kou4chang6kai412 分钟前
Python-GEE遥感云大数据分析与可视化(如何建立基于云计算的森林监测预警系统)
python·数据分析·云计算·森林监测·森林管理
presenttttt19 分钟前
用Python和OpenCV从零搭建一个完整的双目视觉系统(四)
开发语言·python·opencv·计算机视觉
Bug退退退12341 分钟前
RabbitMQ 幂等性
分布式·rabbitmq
木头左3 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
quant_19864 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
失败又激情的man9 小时前
python之requests库解析
开发语言·爬虫·python
打酱油的;9 小时前
爬虫-request处理get
爬虫·python·django
{⌐■_■}11 小时前
【Kafka】登录日志处理的三次阶梯式优化实践:从同步写入到Kafka多分区批处理
数据库·分布式·mysql·kafka·go
qq_5298353511 小时前
RabbitMQ的消息可靠传输
分布式·rabbitmq