FastAPI知识摘要

  # 1.启动命令 uvicorn main:app --reload
  
  if __name_—— == '__main__':
    import uvicorn
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True)


  if __name__ == '__main__':
    import uvicorn
    import os 
    app_model_name = os.path.basename(__file__).replace(".py","")
    print(app_model_name)
    uvicorn.run(f"{app_model_name }:app", host="127.0.0.1", port =8000, reload=True)


  # 2.开启Debug模式
  from fastapi import FastAPI
  from fastapi.reponse import PlainTextResponse
  
  app = FastAPI(debug=True)
  @app.get("/")
  def index():
    1/0
    return PlainTextResponse*('.xxxxx')

  # 3.关闭交互式文档访问
  from fastapi import FastAPI
  app = FastAPI(
        doc_url=None,
        redoc_url=None,
        # 或者直接设置openapi_url=None
        openapi_url=None
  )
  
  # 4.全局异常/错误捕获
  exception_handlers参数主要用于捕获在执行业务逻辑处理过程中抛出的各种异常
  
  from fastapi import FastAPI
  from starlette.responses import JSONResponse

  async def exception_not_found(request, exc):
      return JSONResponse({
          "code": exc.status_code,
          "error": "没有定义这个请求地址",
          "status_code": exc.status_code
      })

  exception_handlers = {
      404: exception_not_found
  }

  app = FastAPI(exception_handlers= exception_handlers)

  # 5.API端点路由注册和匹配
     - 所有的注册路由都会统一保存到app.routes中,app.routes保存了所有的路由注册信息,可以使用print(app.routes)打印所有的注册的路由信息

  app = FastAPI(routes=None)
  @app.api_route(path="/index", methods=["GET", "POST"]
  async def index():
    return {"index":"index"}

  # 还可以直接使用FastAPI提供的app.add_api_route()来实现类似@app.api_route的功能
  app = FastAPI(routes=None)
  async def index():
    return {"index":"index"}
  
  app.add_api_route(path="/index2", endpoint=index, methods=["GET", "POST"]
  
  # 6. 路由注册方式
  app = FastAPI(routes=None)
  router_user = APIRouter(prefix="/user", tags=["用户模块"])
  router_order = APIRouter(prefix="/order", tags=["订单模块"])

  app.include_router(router_user)
  app.include_router(router_order)

    - 给路由配置多个HTTP请求方法
  router_user = APIRouter(prefix="/user", tags = ["用户模块"])
  
  @router_user.api_route("/user/api/login", methods=["GET","POST"])
  def user_api_route_login():
    return {"ok", "登录成功!"}

  # 7. 主从应用挂载
  from fastapi import FastAPI
  from fastapi.response import JSONResponse
  app = FastAPI(title='主应用', description="我是主应用文档的描述", version="v1.0.0")
  @app.get("/index", summary = "主页")
  async def index():
    return JSONResponse({"index":"我是主应用的接口"})


  subapp = FastAPI(title='主应用', description="我是子应用文档的描述", version="v1.0.0")
  @subapp.get('/index', summary='首页')
  async def index():
    return JSONResponse({"index":"我是子应用的接口"})

  # 主应用挂载子应用
  app.mount(path='/subapp', app = subapp, name = 'subapp')

  #8. 读取配置文件 
    1. 读取.ini文件
  [fastapi_config]
  host = 127.0.0.1
  debug = True
  title = "FastAPI"
  description = "FastAPI文档明细描述"
  version = v1.0.0

  [redis]
  ip = 127.0.0.1
  port = 6379
  password = 123456

  from fastapi import FastAPI
  import configparser

  config = configparser.ConfigParser()
  config.read('conf.ini', encoding='utf-8')

  app = FastAPI(
      debug=bool(config.get('fastapi_config', 'debug')),
      title=config.get('fastapi_config', 'title'),
      description=config.get('fastapi_config', 'description'),
      version=config.get('fastapi_config', 'version'),
  )
  -  2.读取.env文件 (安装读取环境变量的依赖包 pip install python-doten)
  DEBUG=true
  TITLE="FastAPI"
  DESCRIPTION="FastAPI文档明细描述--aa"
  VERSION="v1.0.0"

  定义类
  class Settings(BaseSettings):
    debug: bool = False
    title: str
    description: str
    version: str

    class Config:
        env_file = ".env"
        env_file_encoding = 'utf-8'

    #@field_validator("version", pre=True)
    @field_validator("version", mode="before")  # 使用 mode="before" 替代 pre=True
    def version_len_check(cls, v: str) -> Optional[str]:
        if v and len(v) == 0:
            return None
        return v

  @lru_cache()
  def get_settings():
  '''给配置添加上缓存'''
      return Settings()

  settings = Settings()
  print(settings.debug)
  print(settings.title)
  print(settings.description)
  print(settings.version)

  settings = Settings(_env_file='.env', _env_file_encoding='utf-8')
posted @ 2026-09-13 09:19  是17阿哥呀  阅读(8)  评论(0)    收藏  举报