FastAPI学习大纲

FastAPI是一个现代的、快速的(高性能的)、基于标准Python类型的Web框架,用于构建APIs。它基于标准的Python类型提示,并且它的主要优点是速度、类型安全以及自动的API文档生成。

如果您要使用FastAPI,以下是一些必须了解的关键点及相关命令:

  1. 安装:

    pip install fastapi[all]
    pip install uvicorn
    
    • fastapi[all]:安装FastAPI及其所有依赖。
    • uvicorn:ASGI服务器,用于运行FastAPI应用。
  2. 创建一个基础API:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {
          
          "Hello": "World"}
    

    解析: 在这个简单的例子中,我们初始化了一个FastAPI应用,并定义了一个端点。当用户GET请求根路径(/)时,它将返回{"Hello": "World"}

  3. 运行应用:

    uvicorn your_filename:app --reload
    

    解析: 使用uvicorn来运行你的FastAPI应用。your_filename:app指的是你的Python文件名和FastAPI应用实例的名字。--reload使得在开发环境中代码更改后自动重启。

  4. 路径参数和查询参数:

    @app.get("/items/{item_id}")
    def read_item(item_id: int, q: str = None):
        return {
          
          "item_id": item_id, "q": q}
    

    解析: item_id是一个路径参数,q是一个查询参数。FastAPI会自动验证类型,并在文档中展示。

  5. 请求体:
    从Pydantic模型中导入数据结构,并使用它来验证请求体。

    from pydantic import BaseModel
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
    
    @app.post("/items/")
    def create_item(item: Item):
        return item
    

    解析: 使用Pydantic模型,可以自动验证请求数据、序列化和反序列化,且FastAPI会自动生成相关的API文档。

  6. 自动API文档:
    访问 /docs 以查看自动生成的Swagger界面,或访问 /redoc 以查看Redoc界面。

【提醒】以上只是FastAPI的一些基础内容。该框架还提供了许多高级功能,如依赖注入、安全性和OAuth2、事件钩子等。为了充分利用FastAPI,建议深入阅读其官方文档。

  1. 依赖注入:

    FastAPI 使用一个非常强大的依赖注入系统。它允许你很容易地管理和控制数据库连接、配置等。

    示例:

    def get_db():
        db = "Some DB connection"
        try:
            yield db
        finally:
            db.close()
    
    @app.get("/items/")
    def read_items(db=Depends(get_db)):
        return {
          
          "items": "Items from " + db}
    

    解析: get_db 是一个依赖函数,每次请求时都会调用它。read_items 依赖于 get_db 函数,所以 get_db 会先执行。

  2. 安全性:

    FastAPI 提供了多种安全和身份验证选项,包括基于密码的身份验证、OAuth2、Bearer tokens 等。

    示例 (使用HTTP Basic认证):

    from fastapi import Depends, HTTPException
    from fastapi.security import HTTPBasic, HTTPBasicCredentials
    
    security = HTTPBasic()
    
    def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
        if credentials.username != "alice" or credentials.password != "password":
            raise HTTPException(status_code=400, detail="Incorrect email or password")
        return credentials.username
    
    @app.get("/users/me")
    def read_current_user(username: str = Depends(get_current_user)):
        return {
          
          "username": username}
    

    解析: 这个示例中使用了HTTP Basic身份验证。如果用户名和密码不匹配,它会返回一个HTTP 400错误。

  3. OAuth2:

    OAuth2 是一个授权框架,FastAPI 提供了对其的支持。

    示例 (使用Password模式):

    from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
    
    oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
    
    @app.post("/token")
    def login(form_data: OAuth2PasswordRequestForm = Depends()):
        if form_data.username != "alice" or form_data.password != "password":
            raise HTTPException(status_code=400, detail="Incorrect username or password")
        return {
          
          "access_token": form_data.username, "token_type": "bearer"}
    
    @app.get("/users/me")
    def read_current_user(token: str = Depends(oauth2_scheme)):
        return {
          
          "token": token}
    

    解析: 用户需要首先通过 /token 端点使用其用户名和密码获取令牌,然后该令牌可以用于后续的请求。

  4. 事件钩子:

    FastAPI 提供了事件“钩子”或回调,允许在应用启动和关闭时执行代码。

    示例:

    @app.on_event("startup")
    async def startup_event():
        app.state.database = "Some database connection"
    
    @app.on_event("shutdown")
    async def shutdown_event():
        app.state.database.close()
    

    解析: 在应用启动时,startup_event 函数会被调用,并且可以设置应用状态,例如数据库连接。同样,在应用关闭时,shutdown_event 函数会被调用,可以用来关闭资源,例如数据库连接。

这些只是FastAPI特性的简短概述。要充分理解和利用它们,建议查阅FastAPI的官方文档,它为每个特性提供了详细的解释和示例。

猜你喜欢

转载自blog.csdn.net/m0_57021623/article/details/133146826
今日推荐