~2m2:05:44
Tech With Tim

Learn Fast API With This ONE Project

2025年10月30日

Read: ~2m · You save: 124 min

使用一个项目学习 FastAPI

使用 FastAPI 构建功能齐全的 Web 应用程序!从基础到身份验证、数据库和媒体上传。真实项目中的分步指南。

本文介绍如何使用 FastAPI 框架开发照片和视频分享应用程序的后端。该项目涵盖了 API 创建的完整周期,包括基本数据操作、数据库连接、文件上传处理和用户身份验证的实现。假定您具备 Python 语言的基础知识。

引言

项目的目标是为允许用户上传和查看照片和视频的应用程序创建一个功能齐全的 API。在开发过程中,我们将探讨 Web 应用程序和 API 的关键概念,以及使用现代工具进行实现的实际方面。

Web 应用程序和 API 的基本概念

URL、路径和端点

URL(统一资源定位符) 是网络资源的地址。它由几个部分组成:

  • 方案: 数据传输协议(例如 http、https)。
  • 域名: 服务器名称或 IP 地址(例如 example.com)。
  • 路径: 指示服务器上的特定资源或页面(例如 /users/profile)。路径定义了 端点 — 客户端访问的 API 入口点。

查询参数

查询参数在 URL 的问号 (?) 之后添加,用于过滤或细化数据。它们是键值对,用和号 (&) 分隔。 示例:/posts?category=technology&sort=date

请求和响应结构

客户端(例如,Web 浏览器或移动应用程序)和服务器之间的交互通过请求和响应进行。

请求:

  • 方法(HTTP 方法): 定义客户端希望对资源执行的操作。主要方法:
    • GET:检索数据。
    • POST:创建新资源。
    • PUT/PATCH:更新现有资源。
    • DELETE:删除资源。
  • 路径: API 端点。
  • 标头: 包含请求的元数据,例如内容类型、身份验证信息(例如,JWT 令牌)。
  • 正文: 包含发送到服务器的数据(例如,表单数据、JSON 对象)。与 POST、PUT、PATCH 方法一起使用。

响应:

  • 状态码: 一个三位数的数字,指示请求处理的结果。最常见的:
    • 200 OK:请求成功。
    • 201 Created:资源已成功创建。
    • 204 No Content:请求成功,但响应正文为空。
    • 400 Bad Request:客户端请求无效。
    • 401 Unauthorized:需要身份验证。
    • 403 Forbidden:禁止访问。
    • 404 Not Found:未找到资源。
    • 500 Internal Server Error:服务器端错误。
  • 标头: 响应元数据,例如内容类型。
  • 正文: 服务器返回的数据(通常为 JSON 格式)。

项目设置和依赖项安装

要开始,您需要初始化项目并安装必要的库。建议使用 uv 包管理器(或 pip)。

  1. 初始化项目:

    uv init .
    

    此命令会创建一个 pyproject.toml 文件来管理项目依赖项。

  2. 安装依赖项:

    uv add fastapi uvicorn python-dotenv sqlalchemy fastapi-users imagekit-io aiosqlite
    
    • fastapi:主框架。
    • uvicorn:用于运行 FastAPI 应用程序的 ASGI 服务器。
    • python-dotenv:用于从 .env 文件加载环境变量。
    • sqlalchemy:用于数据库操作的 ORM。
    • fastapi-users:用于快速实现用户身份验证的库。
    • imagekit-io:用于与 ImageKit 服务集成以处理媒体文件的 SDK。
    • aiosqlite:用于与 SQLite 交互的异步驱动程序。
  3. 环境变量: 在项目根目录中创建一个 .env 文件来存储敏感数据,例如 ImageKit API 密钥。

    IMAGEKIT_PRIVATE_KEY=your_private_key
    IMAGEKIT_PUBLIC_KEY=your_public_key
    IMAGEKIT_URL_ENDPOINT=your_url_endpoint
    

    您需要在 ImageKit 上注册并获取相应的密钥。

FastAPI 基础

创建应用程序实例

应用程序的主文件(例如 app/main.py 或 app/app.py)以导入 FastAPI 并创建应用程序实例开始。

# app/app.py
from fastapi import FastAPI

app = FastAPI()

定义端点

端点使用与 HTTP 方法对应的装饰器来定义。

# app/app.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}
  • @app.get("/"):定义根路径上的 GET 端点。
  • @app.get("/items/{item_id}"):定义带有路径参数 item_id 的 GET 端点。FastAPI 会自动将 item_id 转换为 int 并执行验证。
  • q: str | None = None:定义一个可选的字符串类型查询参数 q。

运行应用程序

应用程序使用 uvicorn ASGI 服务器运行。创建一个 main.py 文件来启动服务器。

# main.py
import uvicorn
from app.app import app # 从 app/app.py 导入 FastAPI 实例

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)

运行:

uvicorn main:app --reload

或

uv run main.py

自动文档

FastAPI 根据代码自动生成交互式 API 文档。

  • Swagger UI:/docs
  • ReDoc:/redoc

创建 API:核心功能

数据模型和模式(Pydantic)

Pydantic 用于定义数据模式,从而实现传入和传出数据的验证。

# app/schemas.py
from pydantic import BaseModel
from typing import Optional

class PostBase(BaseModel):
    title: str
    content: str

class PostCreate(PostBase):
    pass

class Post(PostBase):
    id: int # 如果使用 UUID,则为 UUID

    class Config:
        orm_mode = True # 用于与 SQLAlchemy 模型配合使用

路径和查询参数

  • 路径参数: URL 的动态部分。
    @app.get("/posts/{post_id}")
    async def get_post(post_id: int):
        # 根据 ID 获取帖子的逻辑
        return {"post_id": post_id}
    
  • 查询参数: ? 之后的可选或必需参数。
    @app.get("/posts")
    async def get_posts(limit: int = 10, skip: int = 0):
        # 获取帖子列表并进行过滤的逻辑
        return {"limit": limit, "skip": skip}
    

请求正文

要通过请求正文发送数据(例如,在创建帖子时),请使用 Pydantic 模式。

# app/app.py
from fastapi import FastAPI
from app.schemas import PostCreate, Post
from typing import List

app = FastAPI()

# 临时数据存储(将被数据库替换)
posts_db = {}
post_id_counter = 1

@app.post("/posts", response_model=Post)
async def create_post(post: PostCreate):
    global post_id_counter
    new_post = Post(id=post_id_counter, title=post.title, content=post.content)
    posts_db[post_id_counter] = new_post
    post_id_counter += 1
    return new_post

输出数据类型化

指定返回类型有助于改进文档和验证。

# app/app.py
from app.schemas import PostCreate, Post
from typing import List

# ... (之前的代码)

@app.post("/posts", response_model=Post)
async def create_post(post: PostCreate):
    # ... (创建帖子的逻辑)
    return new_post

@app.get("/posts", response_model=List[Post])
async def get_all_posts():
    return list(posts_db.values())

数据库集成(SQLAlchemy & AsyncIO)

使用 SQLite 数据库和异步访问来持久化存储数据。

数据库设置

创建一个 app/db.py 文件来设置连接和数据模型。

# app/db.py
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.ext.asyncio import async_sessionmaker
from datetime import datetime
import uuid

DATABASE_URL = "sqlite+aiosqlite:///./test.db"

# 创建异步引擎
engine = create_async_engine(DATABASE_URL, echo=True)

# 创建异步会话工厂
AsyncSessionLocal = async_sessionmaker(
    autocommit=False,
    autoflush=False,
    class_=AsyncSession
)

# 声明式模型基类
Base = declarative_base()

# 帖子数据模型
class Post(Base):
    __tablename__ = "posts"

    id = Column(Integer, primary_key=True, index=True) # 或 UUID
    title = Column(String, index=True)
    content = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    user_id = Column(Integer, ForeignKey("users.id")) # 与用户的关联
    file_url = Column(String) # ImageKit URL
    file_type = Column(String) # 'image' 或 'video'
    file_name = Column(String) # ImageKit 文件名

    user = relationship("User", back_populates="posts")

# 用户数据模型(用于 FastAPI-Users)
class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True) # 或 UUID
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)
    is_superuser = Column(Boolean, default=False)
    is_verified = Column(Boolean, default=False)

    posts = relationship("Post", back_populates="user")

# 获取异步会话的函数
async def get_async_session() -> AsyncSession:
    async with AsyncSessionLocal() as session:
        yield session

# 创建表的函数
async def create_db_tables():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

# 用于 FastAPI-Users
from fastapi import Depends
from fastapi_users.db import SQLAlchemyUserDatabase

async def get_user_db(session: AsyncSession = Depends(get_async_session)):
    yield SQLAlchemyUserDatabase(session, User)

与 FastAPI 集成

使用 lifespan 在应用程序启动时自动创建表。

# app/app.py
from fastapi import FastAPI, Depends, HTTPException, File, UploadFile, Form
from app.schemas import PostCreate, Post, UserCreate, UserRead, UserUpdate # 导入用户模式
from app.db import Post as PostModel, User as UserModel, get_async_session, create_db_tables, get_user_db # 导入数据库模型
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
from sqlalchemy import select
from contextlib import asynccontextmanager
from typing import List, Optional
import shutil
import os
import uuid

# ImageKit 导入
from imagekitio import ImageKit
from imagekitio.models.models import UploadFileRequestOptions
from dotenv import load_dotenv

load_dotenv() # 加载环境变量

# 初始化 ImageKit
imagekit = ImageKit(
    private_key=os.getenv("IMAGEKIT_PRIVATE_KEY"),
    public_key=os.getenv("IMAGEKIT_PUBLIC_KEY"),
    url_endpoint=os.getenv("IMAGEKIT_URL_ENDPOINT")
)

# --- 用户身份验证 (FastAPI-Users) ---
from fastapi_users import FastAPIUsers, BaseUserManager, UUID_ID
from fastapi_users.authentication import (
    AuthenticationBackend,
    BearerTransport,
    JWTStrategy,
)
from fastapi_users.db import SQLAlchemyUserDatabase

# JWT 密钥(应安全且存储在 .env 中)
SECRET = os.getenv("JWT_SECRET_KEY", "your_super_secret_key_here") # 建议生成随机密钥

# 用户管理器
class UserManager(BaseUserManager[UUID_ID, UserModel]):
    reset_password_token_secret = SECRET
    verification_token_secret = SECRET

async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
    yield UserManager(user_db)

# 令牌传输(Bearer Token)
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")

# JWT 策略
def get_jwt_strategy() -> JWTStrategy:
    return JWTStrategy(secret=SECRET, lifetime_seconds=3600) # 令牌有效期为 1 小时

# 身份验证后端
auth_backend = AuthenticationBackend(
    name="jwt",
    transport=bearer_transport,
    get_strategy=get_jwt_strategy,
)

fastapi_users = FastAPIUsers[UserModel, UUID_ID](
    get_user_manager, auth_backend
)

# 获取当前活动用户
current_active_user = fastapi_users.current_user(active=True)

# --- 应用程序生命周期上下文管理器 ---
@asynccontextmanager
async def lifespan(app: FastAPI):
    await create_db_tables() # 启动时创建表
    yield

app = FastAPI(lifespan=lifespan)

# --- 包含身份验证路由 ---
app.include_router(
    fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
)
app.include_router(
    fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"]
)
app.include_router(
    fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"]
)
app.include_router(
    fastapi_users.get_verify_router(), prefix="/auth", tags=["auth"]
)
app.include_router(
    fastapi_users.get_users_router(), prefix="/users", tags=["users"]
)

# --- API 端点 ---

# 获取当前用户(受保护的端点)
@app.get("/users/me", response_model=UserRead)
async def read_users_me(current_user: UserModel = Depends(current_active_user)):
    return current_user

# 获取所有帖子(受保护的端点)
@app.get("/feed", response_model=List[Post])
async def get_feed(
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user) # 需要身份验证
):
    # 查询帖子及其用户信息
    stmt = select(PostModel).order_by(PostModel.created_at.desc())
    result = await session.execute(stmt)
    posts = result.scalars().all()

    # 格式化响应,包含用户信息和所有者状态
    posts_data = []
    for post in posts:
        is_owner = (post.user_id == current_user.id)
        posts_data.append({
            "id": post.id,
            "title": post.title,
            "content": post.content,
            "created_at": post.created_at,
            "user_id": post.user_id,
            "file_url": post.file_url,
            "file_type": post.file_type,
            "file_name": post.file_name,
            "is_owner": is_owner,
            "user_email": post.user.email if post.user else "Unknown"
        })
    return posts_data

# 上传文件(照片/视频)并创建帖子(受保护的端点)
@app.post("/upload", response_model=Post)
async def upload_file(
    file: UploadFile = File(...),
    caption: str = Form(...),
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user) # 需要身份验证
):
    # 生成唯一文件名
    file_extension = os.path.splitext(file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"

    # 上传文件到 ImageKit
    try:
        upload_result = imagekit.upload_file(
            file=file.file,
            file_name=unique_filename,
            options=UploadFileRequestOptions(
                use_unique_file_name=True,
                tags=["backend_upload"],
                folder="uploads" # 可选:ImageKit 中的文件夹
            )
        )
        file_url = upload_result.url
        file_type = "video" if file.content_type.startswith("video/") else "image"
        file_name = upload_result.name

        # 在数据库中创建新帖子
        new_post = PostModel(
            title=caption, # 使用 caption 作为标题
            content=caption, # 或者可以添加单独的内容字段
            user_id=current_user.id,
            file_url=file_url,
            file_type=file_type,
            file_name=file_name
        )
        session.add(new_post)
        await session.commit()
        await session.refresh(new_post)

        # 返回帖子数据,包括 URL 和用户信息
        return {
            "id": new_post.id,
            "title": new_post.title,
            "content": new_post.content,
            "created_at": new_post.created_at,
            "user_id": new_post.user_id,
            "file_url": new_post.file_url,
            "file_type": new_post.file_type,
            "file_name": new_post.file_name,
            "user_email": current_user.email # 添加当前用户的电子邮件
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"File upload failed: {e}")

# 删除帖子(受保护的端点)
@app.delete("/posts/{post_id}", response_model=dict)
async def delete_post(
    post_id: int,
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user) # 需要身份验证
):
    # 从数据库获取帖子
    stmt = select(PostModel).where(PostModel.id == post_id)
    result = await session.execute(stmt)
    post = result.scalars().first()

    if not post:
        raise HTTPException(status_code=404, detail="Post not found")

    # 检查权限:只有帖子的作者才能删除它
    if post.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="You do not have permission to delete this post")

    # 从数据库删除帖子
    await session.delete(post)
    await session.commit()

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

# --- 用户附加模式 ---
# 这些模式继承自标准的 FastAPI-Users 模式,但可以根据需要进行扩展。
from fastapi_users import schemas

class UserRead(schemas.BaseUser[uuid.UUID]):
    email: str
    is_active: bool = True
    is_superuser: bool = False
    is_verified: bool = False
    id: uuid.UUID # 确保 ID 与数据库模型中的类型匹配

class UserCreate(schemas.BaseUserCreate):
    password: str
    email: str
    is_active: bool = True
    is_superuser: bool = False
    is_verified: bool = False

class UserUpdate(schemas.BaseUserUpdate):
    password: Optional[str] = None
    email: Optional[str] = None
    is_active: Optional[bool] = None
    is_superuser: Optional[bool] = None
    is_verified: Optional[bool] = None

# 更新 Post 模型以包含用户信息和所有者状态
class PostWithUser(Post):
    user_id: Optional[int] # 或 UUID
    file_url: str
    file_type: str
    file_name: str
    is_owner: bool
    user_email: str

# 更新 get_feed 端点以返回 PostWithUser
@app.get("/feed", response_model=List[PostWithUser])
async def get_feed(
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user)
):
    stmt = select(PostModel).order_by(PostModel.created_at.desc())
    result = await session.execute(stmt)
    posts = result.scalars().all()

    posts_data = []
    for post in posts:
        is_owner = (post.user_id == current_user.id)
        posts_data.append(PostWithUser(
            id=post.id,
            title=post.title,
            content=post.content,
            created_at=post.created_at,
            user_id=post.user_id,
            file_url=post.file_url,
            file_type=post.file_type,
            file_name=post.file_name,
            is_owner=is_owner,
            user_email=post.user.email if post.user else "Unknown"
        ))
    return posts_data

# 更新 upload_file 端点以返回 PostWithUser
@app.post("/upload", response_model=PostWithUser)
async def upload_file(
    file: UploadFile = File(...),
    caption: str = Form(...),
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user)
):
    file_extension = os.path.splitext(file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"

    try:
        upload_result = imagekit.upload_file(
            file=file.file,
            file_name=unique_filename,
            options=UploadFileRequestOptions(
                use_unique_file_name=True,
                tags=["backend_upload"],
                folder="uploads"
            )
        )
        file_url = upload_result.url
        file_type = "video" if file.content_type.startswith("video/") else "image"
        file_name = upload_result.name

        new_post = PostModel(
            title=caption,
            content=caption,
            user_id=current_user.id,
            file_url=file_url,
            file_type=file_type,
            file_name=file_name
        )
        session.add(new_post)
        await session.commit()
        await session.refresh(new_post)

        return PostWithUser(
            id=new_post.id,
            title=new_post.title,
            content=new_post.content,
            created_at=new_post.created_at,
            user_id=new_post.user_id,
            file_url=new_post.file_url,
            file_type=new_post.file_type,
            file_name=new_post.file_name,
            is_owner=True, # 新帖子始终属于当前用户
            user_email=current_user.email
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"File upload failed: {e}")

# 更新 Post 模型以包含 ForeignKey 和 relationship
# 在 app/db.py 中:
# 在 Post 类中添加:
# user_id = Column(Integer, ForeignKey("users.id"))
# user = relationship("User", back_populates="posts")
# 在 User 类中添加:
# posts = relationship("Post", back_populates="user")
# 确保 User 和 Post 继承自 Base 并具有相应的字段。
# 还需要更新 Pydantic 模式(PostCreate、Post、UserRead、UserCreate、UserUpdate)
# 并确保它们与 SQLAlchemy 模型匹配。

使用 ImageKit 上传文件

与 ImageKit 集成可以轻松管理媒体文件。

  1. 初始化 ImageKit: 在 app/app.py 中,导入并初始化 ImageKit 客户端,使用 .env 中的密钥。

  2. 处理上传: /upload 端点从表单接收 UploadFile 和 caption。文件上传到 ImageKit,然后获取的 URL 与帖子和用户信息一起保存在数据库中。

    # 在 app/app.py 中
    from fastapi import File, UploadFile, Form
    # ... (其他导入)
    
    @app.post("/upload", response_model=PostWithUser)
    async def upload_file(
        file: UploadFile = File(...),
        caption: str = Form(...),
        session: AsyncSession = Depends(get_async_session),
        current_user: UserModel = Depends(current_active_user)
    ):
        # ... (将文件上传到 ImageKit 并保存到数据库的逻辑)
        pass
    

媒体文件转换

ImageKit 允许通过 URL 直接对图像和视频应用转换。例如,调整大小、添加文本、应用效果。

带转换的 URL 示例: https://ik.imagekit.io/your_public_key/your_file_name.jpg?tr=w-300,h-200,fo-auto

身份验证和授权(FastAPI-Users)

FastAPI-Users 使用 JWT(JSON Web Tokens)简化了用户身份验证的实现。

JWT 概念

JWT 是一种通过 JSON 对象在各方之间安全地传输信息的标准。它由三个部分组成:标头、有效负载和签名。令牌使用服务器的密钥进行签名,这允许验证其真实性。

FastAPI-Users 设置

  1. 用户模型: 在 app/db.py 中定义一个继承自 SQLAlchemyUserTable 并包含必要字段(电子邮件、密码、角色)的 User 模型。
  2. 用户模式: 在 app/schemas.py 中创建 UserRead、UserCreate、UserUpdate 模式。
  3. 用户管理器和身份验证后端: 在 app/app.py 中配置 UserManager、BearerTransport、JWTStrategy 和 AuthenticationBackend。
  4. 包含路由: 使用 app.include_router() 添加标准的身份验证路由(注册、登录、密码重置)。

保护端点

要保护端点,请将 Depends(current_active_user) 依赖项添加到端点函数。如果用户未经验证,请求将被拒绝。

# app/app.py
from fastapi_users import FastAPIUsers, BaseUserManager, UUID_ID
from fastapi_users.authentication import (
    AuthenticationBackend,
    BearerTransport,
    JWTStrategy,
)
from fastapi_users.db import SQLAlchemyUserDatabase

# ... (模型和模式定义)

# 获取当前活动用户
current_active_user = fastapi_users.current_user(active=True)

@app.get("/protected-route")
async def protected_route(current_user: UserModel = Depends(current_active_user)):
    return {"message": f"Hello, {current_user.email}!"}

授权(权限检查)

删除帖子时,需要确保当前用户是帖子的作者。

# app/app.py
@app.delete("/posts/{post_id}", response_model=dict)
async def delete_post(
    post_id: int,
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user)
):
    # ... (获取帖子)
    if post.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="You do not have permission to delete this post")
    # ... (删除帖子)

前端(Streamlit)

可以使用 Streamlit 库创建一个简单的前端来演示 API 的工作。Streamlit 允许使用 Python 快速创建交互式 Web 应用程序。

  1. 安装 Streamlit:

    uv add streamlit
    
  2. 创建前端文件: 创建一个 frontend.py 文件,其中包含与 API 交互的代码(发送身份验证请求、文件上传、获取信息流)。前端代码通常包括:

    • 会话状态管理(存储 JWT 令牌)。
    • 用于发送带有标头中令牌的 HTTP 请求的函数。
    • 用于注册、登录、文件上传、显示信息流的界面。
  3. 运行 Streamlit:

    uv run streamlit run frontend.py
    

结论

所开发的应用展示了使用 FastAPI 构建现代 Web API 的综合方法。它包括请求处理、数据库交互、安全的用户身份验证以及与外部服务集成以处理媒体文件。生成的 API 是构建可扩展且可靠的 Web 应用程序的基础。

视频概述

视频概述和最终项目的演示。

  • 演示照片/视频应用程序。
  • 能够登录、查看 Feed、上传内容。
  • 使用 Streamlit 作为前端。

Web 应用程序架构与理论

解释 Web 应用程序架构和核心理论概念。

  • URL、域、路径(端点)的概念。
  • 查询参数的作用。
  • 请求(request)和响应(response)的结构。
  • HTTP 方法:GET、POST、PUT、DELETE。
  • HTTP 状态码(200、404 等)。

项目设置与安装

设置开发环境并安装必要的依赖项。

  • 使用 uv 管理依赖项。
  • 安装 fastapi、python-dotenv、fastapi-users、sqlalchemy、imagekitio、uvicorn。
  • 创建 .env 文件存储密钥。

FastAPI 设置与基础

创建基本的 FastAPI 应用程序并设置第一个端点。

  • 创建 FastAPI 实例。
  • 定义带有 GET 方法的 /hello-world 端点。
  • 返回 JSON 响应。
  • 使用 uvicorn 启动服务器。
  • 使用 /docs 进行自动文档生成。

GET 与帖子获取

处理用于获取数据的端点,包括路径参数和查询参数。

  • 创建 /posts 端点以获取所有帖子。
  • 使用路径参数(例如 /post/{id})获取特定帖子。
  • 处理错误(HTTPException 404)。
  • 使用查询参数(例如 limit)进行过滤。

请求体与 POST

使用 Pydantic 模型实现创建新条目的 POST 端点。

  • 使用 Pydantic 定义数据模式(PostCreate)。
  • 通过请求体接收数据。
  • FastAPI 的自动数据验证。
  • 创建新帖子并返回它。

数据库连接

连接到 SQLite 数据库并定义数据模型。

  • 使用 SQLAlchemy 进行 ORM。
  • 配置异步引擎 create_async_engine。
  • 定义带有 id、caption、url、file_type、file_name、created_at 字段的 Post 模型。
  • 配置应用程序生命周期(lifespan)以创建表。

图像与视频上传 (ImageKit)

使用 ImageKit 实现文件(图像和视频)上传。

  • 与 ImageKit 集成以存储和处理媒体。
  • 创建临时文件进行上传。
  • 使用 imagekitio 的 upload_file。
  • 将文件 URL 和元数据保存到数据库。
  • 处理上传错误。

删除帖子

实现从数据库删除条目的功能。

  • 创建 DELETE 端点 /post/{post_id}。
  • 从路径参数获取帖子 ID。
  • 在数据库中查找帖子。
  • 删除帖子并确认操作。

用户身份验证与 JWT 令牌

使用 JWT 和 FastAPI Users 设置用户身份验证。

  • 使用 fastapi-users 进行用户管理。
  • 配置 JWT 策略和身份验证后端。
  • 定义 User 模型以及与 Post 的关系。
  • 创建注册、登录、登出端点。

端点保护

保护 API 端点,使其仅供已验证的用户访问。

  • 使用 Depends(current_active_user) 保护端点。
  • 删除帖子时检查访问权限。
  • 在 Feed 中显示用户信息。
  • 使用 Streamlit 作为前端。

Streamlit 前端

使用 Streamlit 创建简单的用户界面与 API 交互。

  • 使用 Streamlit 创建 UI。
  • 在会话中管理 JWT 令牌。
  • 实现登录、注册、文件上传和 Feed 显示逻辑。
  • 使用 ImageKit 显示带转换的图像。