AppBoot:像 Django 一样使用 FastAPI

App Boot

开发 AppBoot 的背景是我一直没能寻找到满意的 FastAPI 项目模板。相比之下,Django 的项目结构和开发方式一直深得我心,因此我决定创建一个类似 Django 的 FastAPI 项目模板。

AppBoot 完全采用异步模式,内置 SQLAlchemy 2.0,开箱即用,旨在提供熟悉且高效的开发体验。

技术栈

  • Python 3.9+
  • FastAPI
  • SQLAlchemy 2.0+
  • Pydantic 支持v1和v2
  • Uvicorn

快速开始

启动新项目

shell 复制代码
# 创建项目目录
mkdir mysite
cd mysite
# 创建虚拟环境以在本地隔离包依赖
python3 -m venv env
source env/bin/activate  # Windows 使用 `env\\Scripts\\activate`
# 安装 appboot 和 aiosqlite 到虚拟环境中
pip install appboot aiosqlite
# 使用单个应用程序设置新项目
appboot startproject mysite .  # 注意尾随的 '.' 字符
# 启动服务器,应用运行在 http://127.0.0.1:8000
python manage.py runserver

新建APP polls

shell 复制代码
python manage.py startapp polls

创建数据库 Model

polls/models.py 中定义 Question 模型。

python 复制代码
from datetime import datetime
from sqlalchemy.orm import Mapped
from appboot import models

class Question(models.Model):
    question_text: Mapped[str]
    pub_date: Mapped[datetime]

创建 Schema

polls/schema.py 中定义 QuestionSchema

python 复制代码
from appboot.schema import ModelSchema
from polls.models import Question

class QuestionSchema(ModelSchema):
    class Meta:
        model = Question

编写 CRUD API

polls/views.py 中编写 CRUD API。

python 复制代码
from fastapi import APIRouter, Depends
from appboot.db import create_tables
from appboot.params import QuerySchema, QueryDepends, PaginationResult
from polls.models import Question
from polls.schema import QuestionSchema

router = APIRouter(dependencies=[Depends(create_tables)])

@router.post('/questions/', response_model=QuestionSchema)
async def create_question(question: QuestionSchema):
    return await question.create()

@router.get('/questions/', response_model=PaginationResult[QuestionSchema])
async def query_questions(query: QuerySchema = QueryDepends()):
    return await query.query_result(Question.objects.clone())

@router.get('/questions/{question_id}', response_model=QuestionSchema)
async def get_question(question_id: int):
    return await Question.objects.get(question_id)

@router.put('/questions/{question_id}', response_model=QuestionSchema)
async def update_question(question_id: int, question: QuestionSchema):
    instance = await Question.objects.get(question_id)
    return await question.update(instance)

@router.delete('/questions/{question_id}', response_model=QuestionSchema)
async def delete_question(question_id: int):
    instance = await Question.objects.get(question_id)
    return await instance.delete()

配置 API 路由规则

mysite/urls.py 中配置 API 路由。

python 复制代码
from fastapi import APIRouter
from polls.views import router

root_router = APIRouter()
root_router.include_router(router, prefix='/polls', tags=['polls'])

测试 API

shell 复制代码
python manage.py runserver

现在可以通过浏览器直接访问我们的 API 文档,URL 为 http://127.0.0.1:8000/docs/

创建复杂查询的 QuerySchema

polls/schema.py 中创建 QuestionQuerySchema 以进行复杂查询。

python 复制代码
from typing import Optional
from appboot.params import QuerySchema
from appboot.filters import EqField, ContainsField

class QuestionQuerySchema(QuerySchema):
    ids: Optional[list[int]] = EqField(None, alias='pk', columns='id')  # 按 ID 列表查询 Question
    question_text: Optional[str] = ContainsField(None)  # question_text 字段模糊查询

polls/views.py 文件中将 QuerySchema 替换为 QuestionQuerySchema,然后在浏览器中刷新文档页面,你会看到question列表接口增加了两个新的查询参数。

尝试示例

访问 Examples 获取完整示例,如果你觉得这个项目对你有帮助或有趣,请点赞支持一下!你的支持是我们继续改进和发展的动力。感谢你的关注!!!

相关推荐
哈里谢顿9 分钟前
Django QuerySet 懒加载与缓存机制源码级拆解文档
django
自学不成才1 小时前
深度复盘:一次flutter应用基于内存取证的黑盒加密破解实录并完善算法推理助手
c++·python·算法·数据挖掘
徐先生 @_@|||2 小时前
Palantir Foundry 五层架构模型详解
开发语言·python·深度学习·算法·机器学习·架构
深蓝电商API2 小时前
Scrapy爬虫限速与并发控制最佳实践
爬虫·python·scrapy
Derrick__12 小时前
淘宝MD5爬虫
爬虫·python
薛定谔的猫19822 小时前
llama-index Embedding 落地到 RAG 系统
开发语言·人工智能·python·llama-index
nimadan124 小时前
**手机小说扫榜工具2025推荐,精准追踪榜单动态与题材风向
python·智能手机
编程武士4 小时前
Python 各版本主要变化速览
开发语言·python
傻啦嘿哟4 小时前
Python中的@property:优雅控制类成员访问的魔法
前端·数据库·python
sky17205 小时前
VectorStoreRetriever 三种搜索类型
python·langchain