对象存储s3:-对象存储系统 MVP 原型设计 (FastAPI + SQLite) - # 依赖项:获取数据库会话

📅 2026-12-01 👤 拼多多助力营销技巧 📂 赚钱项目 👁️ 524 次阅读

下面是一个完整的对象存储系统 MVP 原型实现,使用 FastAPI 作为后端框架,SQLite 作为元数据存储,本地文件系统作为对象存储。

设计思路

核心功能

存储桶(Bucket)管理对象(Object)上传/下载/删除对象列表查看基础元数据管理

架构设计

#mermaid-svg-EVCoZ3fwIvvvv1Yz{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .error-icon{fill:#552222;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .marker{fill:#333333;stroke:#333333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .marker.cross{stroke:#333333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz p{margin:0;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .cluster-label text{fill:#333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .cluster-label span{color:#333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .cluster-label span p{background-color:transparent;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .label text,#mermaid-svg-EVCoZ3fwIvvvv1Yz span{fill:#333;color:#333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .node rect,#mermaid-svg-EVCoZ3fwIvvvv1Yz .node circle,#mermaid-svg-EVCoZ3fwIvvvv1Yz .node ellipse,#mermaid-svg-EVCoZ3fwIvvvv1Yz .node polygon,#mermaid-svg-EVCoZ3fwIvvvv1Yz .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .rough-node .label text,#mermaid-svg-EVCoZ3fwIvvvv1Yz .node .label text,#mermaid-svg-EVCoZ3fwIvvvv1Yz .image-shape .label,#mermaid-svg-EVCoZ3fwIvvvv1Yz .icon-shape .label{text-anchor:middle;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .rough-node .label,#mermaid-svg-EVCoZ3fwIvvvv1Yz .node .label,#mermaid-svg-EVCoZ3fwIvvvv1Yz .image-shape .label,#mermaid-svg-EVCoZ3fwIvvvv1Yz .icon-shape .label{text-align:center;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .node.clickable{cursor:pointer;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .arrowheadPath{fill:#333333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-EVCoZ3fwIvvvv1Yz .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-EVCoZ3fwIvvvv1Yz .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-EVCoZ3fwIvvvv1Yz .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .cluster text{fill:#333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .cluster span{color:#333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-EVCoZ3fwIvvvv1Yz rect.text{fill:none;stroke-width:0;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .icon-shape,#mermaid-svg-EVCoZ3fwIvvvv1Yz .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .icon-shape p,#mermaid-svg-EVCoZ3fwIvvvv1Yz .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .icon-shape rect,#mermaid-svg-EVCoZ3fwIvvvv1Yz .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-EVCoZ3fwIvvvv1Yz .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-EVCoZ3fwIvvvv1Yz .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-EVCoZ3fwIvvvv1Yz :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}客户端FastAPI 应用SQLite 数据库本地文件系统存储元数据表对象文件

数据结构

存储桶(Bucket): 容器,用于组织对象对象(Object): 存储的实际文件,包含元数据元数据: 文件名、大小、类型、创建时间等

完整实现代码

项目结构

object_storage_mvp/

├── app/

│ ├── __init__.py

│ ├── main.py # FastAPI 主应用

│ ├── database.py # 数据库连接

│ ├── models.py # SQLAlchemy 模型

│ ├── schemas.py # Pydantic 模型

│ ├── crud.py # 数据库操作

│ ├── storage.py # 文件存储操作

│ └── config.py # 配置管理

├── storage/ # 对象存储目录

├── requirements.txt

└── README.md

代码实现

1. requirements.txt

fastapi==0.103.1

uvicorn==0.23.2

sqlalchemy==2.0.20

python-multipart==0.0.6

python-dotenv==1.0.0

pydantic==2.3.0

2. app/config.py

import os

from pydantic_settings import BaseSettings

class Settings(BaseSettings):

# 数据库配置

DATABASE_URL: str = "sqlite:///./object_storage.db"

# 存储配置

STORAGE_PATH: str = "./storage"

MAX_FILE_SIZE: int = 10 * 1024 * 1024 # 10MB

# 应用配置

APP_NAME: str = "Object Storage MVP"

DEBUG: bool = True

class Config:

env_file = ".env"

settings = Settings()

# 确保存储目录存在

os.makedirs(settings.STORAGE_PATH, exist_ok=True)

3. app/database.py

from sqlalchemy import create_engine

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import sessionmaker

from .config import settings

# 创建数据库引擎

engine = create_engine(

settings.DATABASE_URL,

connect_args={"check_same_thread": False} # SQLite 多线程支持

)

# 创建会话工厂

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 声明基类

Base = declarative_base()

# 依赖项:获取数据库会话

def get_db():

db = SessionLocal()

try:

yield db

finally:

db.close()

4. app/models.py

from sqlalchemy import Column, Integer, String, BigInteger, DateTime, ForeignKey

from sqlalchemy.orm import relationship

from .database import Base

import datetime

class Bucket(Base):

__tablename__ = "buckets"

id = Column(Integer, primary_key=True, index=True)

name = Column(String(255), unique=True, index=True, nullable=False)

created_at = Column(DateTime, default=datetime.datetime.utcnow)

objects = relationship("Object", back_populates="bucket")

class Object(Base):

__tablename__ = "objects"

id = Column(Integer, primary_key=True, index=True)

bucket_id = Column(Integer, ForeignKey("buckets.id"), nullable=False)

object_key = Column(String(255), unique=True, index=True, nullable=False)

original_filename = Column(String(255))

size = Column(BigInteger)

content_type = Column(String(100))

storage_path = Column(String(512))

created_at = Column(DateTime, default=datetime.datetime.utcnow)

bucket = relationship("Bucket", back_populates="objects")

5. app/schemas.py

from pydantic import BaseModel

from datetime import datetime

from typing import Optional, List

# Bucket 模式

class BucketCreate(BaseModel):

name: str

class BucketResponse(BaseModel):

id: int

name: str

created_at: datetime

class Config:

orm_mode = True

# Object 模式

class ObjectCreate(BaseModel):

bucket_name: str

class ObjectResponse(BaseModel):

id: int

bucket_id: int

object_key: str

original_filename: Optional[str]

size: Optional[int]

content_type: Optional[str]

storage_path: Optional[str]

created_at: datetime

class Config:

orm_mode = True

class ObjectListResponse(BaseModel):

bucket: str

objects: List[ObjectResponse]

class UploadResponse(BaseModel):

message: str

object_key: str

url: str

6. app/storage.py

import os

import uuid

from pathlib import Path

from fastapi import UploadFile, HTTPException

from .config import settings

def save_file(file: UploadFile, bucket_name: str) ->tuple:

"""保存上传的文件到存储目录"""

# 验证文件大小

file.file.seek(0, os.SEEK_END)

file_size = file.file.tell()

file.file.seek(0)

if file_size > settings.MAX_FILE_SIZE:

raise HTTPException(

status_code=413,

detail=f"File too large. Max size is {settings.MAX_FILE_SIZE // (1024*1024)}MB"

)

# 创建存储目录

bucket_dir = Path(settings.STORAGE_PATH) / bucket_name

bucket_dir.mkdir(exist_ok=True)

# 生成唯一文件名

file_ext = Path(file.filename).suffix

object_key = f"{uuid.uuid4().hex}{file_ext}"

storage_path = bucket_dir / object_key

# 保存文件

with open(storage_path, "wb") as buffer:

buffer.write(file.file.read())

return object_key, storage_path, file_size 拼多多帮助力入口

def get_file_path(bucket_name: str, object_key: str) ->Path:

"""获取文件路径"""

return Path(settings.STORAGE_PATH) / bucket_name / object_key

def delete_file(bucket_name: str, object_key: str):

"""删除文件"""

file_path = get_file_path(bucket_name, object_key)

if file_path.exists():

file_path.unlink()

7. app/crud.py

from sqlalchemy.orm import Session

from . import models, schemas

from .storage import save_file, delete_file, get_file_path

from fastapi import HTTPException

import os

# Bucket CRUD 操作

def create_bucket(db: Session, bucket_name: str):

db_bucket = models.Bucket(name=bucket_name)

db.add(db_bucket)

db.commit()

db.refresh(db_bucket)

return db_bucket

def get_bucket_by_name(db: Session, bucket_name: str):

return db.query(models.Bucket).filter(models.Bucket.name == bucket_name).first()

def list_buckets(db: Session):

return db.query(models.Bucket).all()

# Object CRUD 操作

def create_object(

db: Session,

bucket_name: str,

file: UploadFile,

content_type: str = None

):

# 获取或创建存储桶

bucket = get_bucket_by_name(db, bucket_name)

if not bucket:

bucket = create_bucket(db, bucket_name)

# 保存文件

object_key, storage_path, file_size = save_file(file, bucket_name)

# 创建对象记录

db_object = models.Object(

bucket_id=bucket.id,

object_key=object_key,

original_filename=file.filename,

size=file_size,

content_type=content_type or file.content_type,

storage_path=str(storage_path)

)

db.add(db_object)

db.commit()

db.refresh(db_object)

return db_object

def get_object(db: Session, bucket_name: str, object_key: str):

bucket = get_bucket_by_name(db, bucket_name)

if not bucket:

return None

return db.query(models.Object).filter(

models.Object.bucket_id == bucket.id,

models.Object.object_key == object_key

).first()

def list_objects(db: Session, bucket_name: str):

bucket = get_bucket_by_name(db, bucket_name)

if not bucket:

return []

return db.query(models.Object).filter(

models.Object.bucket_id == bucket.id

).all()

def delete_object(db: Session, bucket_name: str, object_key: str):

# 获取对象

obj = get_object(db, bucket_name, object_key)

if not obj:

return False

# 删除文件

delete_file(bucket_name, object_key)

# 删除数据库记录

db.delete(obj)

db.commit()

return True

8. app/main.py

from fastapi import FastAPI, UploadFile, File, Depends, HTTPException, Response

from fastapi.responses import FileResponse

from sqlalchemy.orm import Session

from . import crud, models, schemas, database, storage

from .database import get_db

from .config import settings

import os

app = FastAPI(title=settings.APP_NAME)

# 创建数据库表

models.Base.metadata.create_all(bind=database.engine)

@app.post("/buckets/", response_model=schemas.BucketResponse)

def create_bucket(bucket: schemas.BucketCreate, db: Session = Depends(get_db)):

db_bucket = crud.get_bucket_by_name(db, bucket.name)

if db_bucket:

raise HTTPException(status_code=400, detail="Bucket already exists")

return crud.create_bucket(db, bucket.name)

@app.get("/buckets/", response_model=list[schemas.BucketResponse])

def list_buckets(db: Session = Depends(get_db)):

return crud.list_buckets(db)

@app.post("/buckets/{bucket_name}/objects/", response_model=schemas.UploadResponse)

async def upload_object(

bucket_name: str,

file: UploadFile = File(...),

db: Session = Depends(get_db)

):

# 验证存储桶是否存在

bucket = crud.get_bucket_by_name(db, bucket_name)

if not bucket:

# 自动创建存储桶

bucket = crud.create_bucket(db, bucket_name)

# 保存对象

db_object = crud.create_object(db, bucket_name, file)

# 生成访问URL

url = f"/buckets/{bucket_name}/objects/{db_object.object_key}"

return {

"message": "File uploaded successfully",

"object_key": db_object.object_key,

"url": url

}

@app.get("/buckets/{bucket_name}/objects/{object_key}", response_class=FileResponse)

def download_object(bucket_name: str, object_key: str, db: Session = Depends(get_db)):

obj = crud.get_object(db, bucket_name, object_key)

if not obj:

raise HTTPException(status_code=404, detail="Object not found")

file_path = storage.get_file_path(bucket_name, object_key)

if not file_path.exists():

raise HTTPException(status_code=404, detail="File not found on disk")

return FileResponse(

path=file_path,

filename=obj.original_filename,

media_type=obj.content_type

)

@app.get("/buckets/{bucket_name}/objects/", response_model=schemas.ObjectListResponse)

def list_objects(bucket_name: str, db: Session = Depends(get_db)):

bucket = crud.get_bucket_by_name(db, bucket_name)

if not bucket:

raise HTTPException(status_code=404, detail="Bucket not found")

objects = crud.list_objects(db, bucket_name)

return {

"bucket": bucket_name,

"objects": objects

}

@app.delete("/buckets/{bucket_name}/objects/{object_key}")

def delete_object(bucket_name: str, object_key: str, db: Session = Depends(get_db)):

success = crud.delete_object(db, bucket_name, object_key)

if not success:

raise HTTPException(status_code=404, detail="Object not found")

return {"message": "Object deleted successfully"}

@app.get("/")

def read_root():

return {

"message": f"Welcome to {settings.APP_NAME}",

"version": "0.1.0",

"endpoints": [

{"method": "POST", "path": "/buckets/", "description": "Create a new bucket"},

{"method": "GET", "path": "/buckets/", "description": "List all buckets"},

{"method": "POST", "path": "/buckets/{bucket_name}/objects/", "description": "Upload an object"},

{"method": "GET", "path": "/buckets/{bucket_name}/objects/{object_key}", "description": "Download an object"},

{"method": "GET", "path": "/buckets/{bucket_name}/objects/", "description": "List objects in a bucket"},

{"method": "DELETE", "path": "/buckets/{bucket_name}/objects/{object_key}", "description": "Delete an object"}

]

}

使用说明

1. 安装依赖

pip install -r requirements.txt

2. 运行应用

uvicorn app.main:app --reload

3. API 端点

POST /buckets/ - 创建存储桶GET /buckets/ - 列出所有存储桶POST /buckets/{bucket_name}/objects/ - 上传对象GET /buckets/{bucket_name}/objects/{object_key} - 下载对象GET /buckets/{bucket_name}/objects/ - 列出存储桶中的对象DELETE /buckets/{bucket_name}/objects/{object_key} - 删除对象

4. 测试示例

创建存储桶

curl -X POST "http://localhost:8000/buckets/" \

-H "Content-Type: application/json" \

-d '{"name": "my-bucket"}'

上传文件

curl -X POST "http://localhost:8000/buckets/my-bucket/objects/" \

-F "file=@/path/to/your/file.jpg"

下载文件

curl -o downloaded.jpg "http://localhost:8000/buckets/my-bucket/objects/{object_key}"

列出存储桶中的对象

curl "http://localhost:8000/buckets/my-bucket/objects/"

删除对象

curl -X DELETE "http://localhost:8000/buckets/my-bucket/objects/{object_key}"

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧