FastAPI简易使用指南

FastAPI是一个基于Python 3.6+的高性能Web框架,用于构建API。本文介绍了其安装、目录结构和模块解析,包括endpoints和core目录的示例。endpoints是处理HTTP请求的核心,而core目录用于存放应用程序的核心功能和配置。
摘要由CSDN通过智能技术生成


FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。

官中用户指南

https://fastapi.tiangolo.com/zh/tutorial/

安装

pip install "fastapi[all]"

目录结构

FastAPI没有固定的目录结构要求,但是通常建议将应用程序代码和配置分开,并使用模块化的方式组织代码。一种常见的目录结构如下:

app/
├── main.py
├── api/
│   ├── __init__.py
│   ├── endpoints/
│   │   ├── __init__.py
│   │   ├── item.py
│   │   └── user.py
│   └── models/
│       ├── __init__.py
│       ├── item.py
│       └── user.py
├── core/
│   ├── __init__.py
│   ├── config.py
│   └── security.py
├── db/
│   ├── __init__.py
│   └── repository.py
└── tests/
    ├── __init__.py
    ├── conftest.py
    └── test_main.py

其中:

  • main.py 是 FastAPI 应用程序的主入口点。
  • api/endpoints 目录包含所有 API 端点的代码文件。
  • api/models 目录包含数据模型的代码文件。
  • core 目录包含应用程序的核心功能,例如配置和安全性。
  • db 目录包含与数据库交互的相关代码文件。
  • tests 目录包含所有测试代码文件。

模块解析

用一个示例来解析各个模块
假设我们正在为一个商品列表 API 编写 endpoints,我们可以按照以下方式组织文件:

api/
└── endpoints/
    ├── __init__.py
    └── items.py

items.py 文件中,我们定义了用于处理商品 CRUD 操作的 endpoints。例如:

from fastapi import APIRouter

router = APIRouter()

@router.get("/items")
async def read_items():
    # return list of all items
    pass

@router.get("/items/{item_id}")
async def read_item(item_id: int):
    # return item by id
    pass

@router.post("/items"
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值