通用图片/附件管理插件,支持 Django 和 FastAPI
Project description
ChewyAttachment
🚀 通用文件/附件管理服务 - 支持 Django & FastAPI 双框架
📖 简介
ChewyAttachment 是一个通用的文件/附件管理插件,提供开箱即用的文件上传、下载、删除功能。支持作为独立的 Django 应用或 FastAPI 可插拔模块运行,适合个人自托管场景,可被多个业务系统复用。
✨ 核心特性
- 🔄 双框架支持: 同时支持 Django 和 FastAPI
- 📁 完整功能: 文件上传、下载、删除、列表查询
- 🔐 简化权限: 基于 owner_id 的权限模型,支持 public/private 访问级别
- 🎯 认证解耦: 通过外部注入 user_id 实现认证解耦
- 📝 Markdown 友好: 返回 Markdown 格式的文件引用链接
- 🗄️ 轻量存储: SQLite + 本地文件系统,数据库仅存元信息
- 🔌 即插即用: 独立于具体业务表的通用数据模型
- 🎨 RESTful API: 标准化的 API 设计
📦 安装
# 使用 pip 安装
pip install chewy-attachment
# 安装 Django 支持
pip install chewy-attachment[django]
# 安装 FastAPI 支持
pip install chewy-attachment[fastapi]
# 安装全部功能(开发)
pip install chewy-attachment[dev]
# 或从源码安装
git clone https://github.com/cone387/ChewyAttachment.git
cd ChewyAttachment
pip install -e .
🚀 快速开始
Django 集成
- 添加到 INSTALLED_APPS
# settings.py
INSTALLED_APPS = [
# ...
'chewy_attachment.django_app',
]
# ChewyAttachment 配置
CHEWY_ATTACHMENT = {
"STORAGE_ROOT": BASE_DIR / "media" / "attachments",
}
- 配置 URL
# urls.py
from django.urls import path, include
urlpatterns = [
# ...
path('api/attachments/', include('chewy_attachment.django_app.urls')),
]
- 运行迁移
python manage.py migrate
FastAPI 集成
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from chewy_attachment.fastapi_app.router import router as attachment_router
from chewy_attachment.fastapi_app.models import Base
from chewy_attachment.fastapi_app.dependencies import get_current_user_id
app = FastAPI()
# 数据库配置
engine = create_engine("sqlite:///./attachments.db")
SessionLocal = sessionmaker(bind=engine)
Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# 自定义用户认证
async def custom_get_user_id() -> int:
# 实现你的用户认证逻辑
return 1 # 示例
# 挂载路由
app.include_router(
attachment_router,
prefix="/api/attachments",
dependencies=[Depends(get_db)]
)
# 覆盖默认的用户认证依赖
app.dependency_overrides[get_current_user_id] = custom_get_user_id
📚 API 文档
Django API
上传文件
POST /api/attachments/files/
Content-Type: multipart/form-data
参数:
- file: 文件对象 (必须)
- is_public: boolean (可选, 默认: false)
- owner_id: string (可选, 由认证系统自动填充)
返回示例:
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"original_name": "example.jpg",
"mime_type": "image/jpeg",
"size": 102400,
"owner_id": "123",
"is_public": false,
"created_at": "2026-01-14 10:30:00",
"preview_url": "/api/attachments/files/550e8400-e29b-41d4-a716-446655440000/preview/"
}
注意:
preview_url返回相对路径,根据实际路由配置动态生成。
获取文件列表
GET /api/attachments/files/
查询参数:
- page: 页码 (默认: 1)
- page_size: 每页数量 (默认: 20, 最大: 100)
返回示例:
{
"count": 100,
"next": "http://localhost:8000/api/attachments/files/?page=2",
"previous": null,
"results": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"original_name": "example.jpg",
"mime_type": "image/jpeg",
"size": 102400,
"owner_id": "123",
"is_public": true,
"created_at": "2026-01-14 10:30:00",
"preview_url": "/api/attachments/files/550e8400-e29b-41d4-a716-446655440000/preview/"
}
]
}
获取文件详情
GET /api/attachments/files/{attachment_id}/
返回示例:
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"original_name": "example.jpg",
"mime_type": "image/jpeg",
"size": 102400,
"owner_id": "123",
"is_public": true,
"created_at": "2026-01-14 10:30:00",
"preview_url": "/api/attachments/files/550e8400-e29b-41d4-a716-446655440000/preview/"
}
预览文件
GET /api/attachments/files/{attachment_id}/preview/
在浏览器中直接预览文件(inline 模式),图片会直接显示。
下载文件
GET /api/attachments/files/{attachment_id}/content/
强制下载文件(attachment 模式)。
删除文件
DELETE /api/attachments/files/{attachment_id}/
FastAPI API
上传文件
POST /api/attachments/files/
Content-Type: multipart/form-data
参数:
- file: 文件对象 (必须)
- is_public: boolean (可选, 默认: false)
获取文件列表
GET /api/attachments/files/
查询参数:
- page: 页码 (默认: 1)
- page_size: 每页数量 (默认: 20, 最大: 100)
返回示例:
{
"total": 100,
"page": 1,
"page_size": 20,
"items": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"original_name": "example.jpg",
"mime_type": "image/jpeg",
"size": 102400,
"owner_id": "123",
"is_public": true,
"created_at": "2026-01-14T10:30:00",
"preview_url": "/api/attachments/files/550e8400-e29b-41d4-a716-446655440000/preview"
}
]
}
获取文件详情
GET /api/attachments/files/{attachment_id}
预览文件
GET /api/attachments/files/{attachment_id}/preview
下载文件
GET /api/attachments/files/{attachment_id}/content
删除文件
DELETE /api/attachments/files/{attachment_id}
🔐 权限模型
- Public 文件: 所有人可读,仅所有者可删除
- Private 文件: 仅所有者可读可删除
- Owner ID: 通过外部认证系统注入,实现认证解耦
📁 数据模型
class Attachment:
id: str # UUID 主键
original_name: str # 原始文件名
storage_path: str # 物理存储路径
mime_type: str # MIME 类型
size: int # 文件大小(字节)
owner_id: str # 所有者 ID
is_public: bool # 访问级别
created_at: datetime # 创建时间
🛠️ 配置选项
Django 配置
# settings.py
# ChewyAttachment 配置
CHEWY_ATTACHMENT = {
# 存储根目录 (必须)
"STORAGE_ROOT": BASE_DIR / "media" / "attachments",
# 自定义表名 (可选, 默认: "chewy_attachment_files")
# "TABLE_NAME": "my_custom_attachments",
# 时间格式 (可选, 默认: "%Y-%m-%d %H:%M:%S")
# "DATETIME_FORMAT": "%Y-%m-%d %H:%M:%S",
# 自定义权限类 (可选)
# "PERMISSION_CLASSES": [
# "chewy_attachment.django_app.permissions.IsAuthenticatedForUpload",
# "chewy_attachment.django_app.permissions.IsOwnerOrPublicReadOnly",
# ],
}
配置说明:
STORAGE_ROOT: 文件存储的物理路径(必须配置)TABLE_NAME: 数据库表名,默认chewy_attachment_filesDATETIME_FORMAT: API 返回的时间字段格式PERMISSION_CLASSES: 自定义 DRF 权限类列表
自定义权限类示例
# myapp/permissions.py
from rest_framework import permissions
from chewy_attachment.django_app.models import Attachment
from chewy_attachment.core.permissions import PermissionChecker
class CustomAttachmentPermission(permissions.BasePermission):
"""
自定义附件权限类
示例: 管理员可以访问所有文件,普通用户只能访问自己的文件
"""
def has_object_permission(self, request, view, obj: Attachment):
# 管理员拥有所有权限
if request.user and request.user.is_staff:
return True
# 使用核心权限检查器
user_context = Attachment.get_user_context(request)
file_metadata = obj.to_file_metadata()
if request.method in permissions.SAFE_METHODS:
return PermissionChecker.can_view(file_metadata, user_context)
if request.method == "DELETE":
return PermissionChecker.can_delete(file_metadata, user_context)
return False
# settings.py
CHEWY_ATTACHMENT = {
"STORAGE_ROOT": BASE_DIR / "media" / "attachments",
"PERMISSION_CLASSES": [
"chewy_attachment.django_app.permissions.IsAuthenticatedForUpload",
"myapp.permissions.CustomAttachmentPermission",
],
}
FastAPI 配置
from chewy_attachment.core.storage import FileStorage
# 自定义存储路径
storage = FileStorage(base_path="/custom/path/media")
📂 项目结构
ChewyAttachment/
├── chewy_attachment/
│ ├── core/ # 核心功能模块
│ │ ├── schemas.py # 数据模式
│ │ ├── storage.py # 文件存储
│ │ ├── permissions.py # 权限控制
│ │ └── utils.py # 工具函数
│ ├── django_app/ # Django 应用
│ │ ├── models.py # Django 模型
│ │ ├── views.py # Django 视图
│ │ ├── serializers.py # DRF 序列化器
│ │ └── urls.py # URL 配置
│ └── fastapi_app/ # FastAPI 应用
│ ├── models.py # SQLAlchemy 模型
│ ├── router.py # API 路由
│ ├── crud.py # CRUD 操作
│ └── dependencies.py # 依赖注入
├── examples/ # 示例项目
│ ├── django_example/ # Django 示例
│ └── fastapi_example/ # FastAPI 示例
└── pyproject.toml # 项目配置
🧪 运行测试
# 安装测试依赖
pip install pytest pytest-django pytest-asyncio
# 运行 Django 测试
pytest chewy_attachment/django_app/tests/
# 运行 FastAPI 测试
pytest chewy_attachment/fastapi_app/tests/
📝 示例代码
查看 examples/ 目录获取完整的示例项目:
运行 Django 示例
# 克隆项目(如果还没有)
git clone https://github.com/cone387/ChewyAttachment.git
cd ChewyAttachment
# 使用 uv 安装依赖(会自动创建 .venv 虚拟环境)
uv sync
# 进入 Django 示例目录
cd examples/django_example
# 运行迁移
uv run python manage.py migrate
# 创建超级用户(可选)
uv run python manage.py createsuperuser
# 启动开发服务器
uv run python manage.py runserver
# 访问
# - API: http://localhost:8000/api/attachments/
# - Admin: http://localhost:8000/admin/
运行 FastAPI 示例
# 克隆项目(如果还没有)
git clone https://github.com/cone387/ChewyAttachment.git
cd ChewyAttachment
# 使用 uv 安装依赖(会自动创建 .venv 虚拟环境)
uv sync
# 启动 FastAPI 应用
uv run python examples/fastapi_example/main.py
# 访问
# - API: http://localhost:8000/api/attachments/
# - Docs: http://localhost:8000/docs
# - ReDoc: http://localhost:8000/redoc
🤝 贡献
欢迎提交 Issue 和 Pull Request!
📄 License
MIT License
👤 作者
- GitHub: @cone387
🔗 相关链接
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file chewy_attachment-0.3.2.tar.gz.
File metadata
- Download URL: chewy_attachment-0.3.2.tar.gz
- Upload date:
- Size: 25.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8f7737a01b24073f12ff2642f4d4e780fa37368ca1eafc17a35e53124a5a3642
|
|
| MD5 |
4ea7452eecd9895f12bea14e898cd9de
|
|
| BLAKE2b-256 |
3c876325b078f6c9fcb48ca635aeb9049377d52d2a1d506eb5b361a70fbcc4aa
|
File details
Details for the file chewy_attachment-0.3.2-py3-none-any.whl.
File metadata
- Download URL: chewy_attachment-0.3.2-py3-none-any.whl
- Upload date:
- Size: 34.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8771a1a4e935a227b98489fa94003ebcb82849d057efb43e3e65844722d87c86
|
|
| MD5 |
50ff68beb88b2866235e4ece21635866
|
|
| BLAKE2b-256 |
12ceb7b8269547bde2bbfb43e27f180f3043857c66132aab586b02e1f2e3cf6d
|