本文介绍: FastAPI 库(Python 的 Web 框架基本使用指南(二)

核心功能

定义路由

FastAPI 中定义路由方式主要有两种,一种是使用 FastAPI 应用实例方法(例如 app.get()),一种是使用装饰器(例如 @app.get()),它们的用法和作用略有不同。

路由分组

路径参数

声明路径参数

fastapi.Path(校验路径参数)

在 FastAPI 中,fastapi.Path 是一个用于声明路径参数的类,它提供了更多的参数配置选项,允许定义路径参数的类型默认值校验规则等。使用 fastapi.Path 可以更精细地控制路径参数的行为

常用可选传参数:

查询参数

声明查询参数

fastapi.Query校验查询参数)

请求体 与 响应模型

依赖注入

异常处理

文件上传

拓展:上传文件

Request (请求对象

  • request 对象

    FastAPI 可以在路由处理函数中使用 fastapi.Request 模型来获取请求的详细信息,如头部、查询参数等。

    from fastapi import FastAPI, Request
    
    @app.get("/user-agent/")
    def read_user_agent(request: Request):
        # 获取请求头
        headers = request.headers
        user_agent = headers.get("user-agent")
        return {"user_agent": user_agent}
    
  • 请求头部中的信息

    FastAPI 可以在路由处理函数中使用 fastapi.Header 模型来获取请求头部中的信息,例如 user_agent 等

    from fastapi import FastAPI, Header
    
    @app.get("/headers/")
    def read_headers(user_agent: str = Header(None)):
        return {"User-Agent": user_agent}
    

安全

拓展

访问 Fast API 接口文档

FastAPI 项目的基本目录结构

my_project/
├── app/                                
│   ├── apis/
│   │   ├── __init__.py
│   │   ├── auth.py
│   │   ├── items.py
│   │   └── users.py
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py
│   │   ├── security.py
│   │   └── sqlalchemy.py
│   ├── db/
│   │   ├── __init__.py
│   │   └── base.py
│   ├── main.py
│   └── models/
│       ├── __init__.py
│       ├── item.py
│       └── user.py
├── docker-compose.yml
├── Dockerfile
├── README.md
└── requirements.txt

此外,还可以根据项目需要添加其他目录和文件,例如静态文件目录、测试目录、文档目录等。但是,无论怎样组织FastAPI项目结构,都需要保证代码清晰明了、易于维护。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注