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

相关推荐
跟橙姐学代码26 分钟前
手把手教你玩转 multiprocessing,让程序跑得飞起
前端·python·ipython
LCS-3121 小时前
Python爬虫实战: 爬虫常用到的技术及方案详解
开发语言·爬虫·python
穷儒公羊1 小时前
第二章 设计模式故事会之策略模式:魔王城里的勇者传说
python·程序人生·设计模式·面试·跳槽·策略模式·设计规范
心本无晴.1 小时前
面向过程与面向对象
python
花妖大人1 小时前
Python用法记录
python·sqlite
站大爷IP1 小时前
用PyQt快速搭建桌面应用:从零到实战的实用指南
python
站大爷IP1 小时前
PyCharm:Python开发者的智慧工作台全解析
python
zhanghongyi_cpp1 小时前
linux的conda配置与应用阶段的简单指令备注
linux·python·conda
MThinker1 小时前
14.examples\01-Micropython-Basics\demo_yield.py 加强版
python·学习·智能硬件·micropython·canmv·k230
LiRuiJie2 小时前
基于LangChain + Milvus 实现RAG
python·langchain·milvus·rag