首页 > 其他分享 >FastAPI系列:环境配置读取

FastAPI系列:环境配置读取

时间:2024-02-28 18:25:23浏览次数:22  
标签:系列 读取 settings FastAPI app get per env name

依赖包

pip install python-dotenv

使用

#.env文件
ADMIN_EMAIL="[email protected]"
APP_NAME="ChimichangApp"

# config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
    app_name: str = "Awesome API"
    admin_email: str
    items_per_user: int = 50

    class Config:
        # 前提已经创建好了.env文件,数据将会自动映射到该配置类中
        env_file = ".env" # 指定文件名
        env_file_encoding = 'utf-8' # 指定编码
        env_prefix = 'APP_' # 指定前缀

# 暴露一个对外的函数
@lru_cache()
def get_settings():
    return config.Settings()


# main.py
from config import get_settings

@app.get("/info")
async def info(settings: Annotated[Settings, Depends(get_settings)]): # 作用于依赖项
    return {
        "app_name": settings.app_name,
        "admin_email": settings.admin_email,
        "items_per_user": settings.items_per_user,
    }

标签:系列,读取,settings,FastAPI,app,get,per,env,name
From: https://www.cnblogs.com/weiweivip666/p/18041357

相关文章

  • FastAPI系列:后台任务进程
    注:后台任务应附加到响应中,并且仅在发送响应后运行用于将单个后台任务添加到响应中fromfastapiimportFastAPIfromfastapi.responsesimportJSONResponsefromstarlette.backgroundimportBackgroundTaskfrompydanticimportBaseModelapp=FastAPI()classUser(B......
  • FastAPI系列:中间件
    中间件介绍中间件是一个函数,它在每个请求被特定的路径操作处理之前,以及在每个响应返回之前工作装饰器版中间件1.必须使用装饰器@app.middleware("http"),且middleware_type必须为http2.中间件参数:request,call_next,且call_next它将接收request作为参数@app.middleware("h......
  • FastAPI系列:模型用法
    模型基本用法frompydanticimportBaseModelclassItem(BaseModel):#通过继承BaseModelname:strprice:floatis_offer:Union[bool,None]=None常用的模型属性和方法dict()#将数据模型的字段和值封装成字典json()#将数据模型的字段和值封装成json格......
  • FastAPI系列:上传文件File和UploadFile
    上传文件#file仅适用于小文件@app.post("/files/")asyncdefcreate_file(file:bytes|None=File(default=None)):ifnotfile:return{"message":"Nofilesent"}else:return{"file_size":len(file)}......
  • FastAPI系列:路径参数额外校验Path
    路径参数额外校验PathfromfastapiimportPathapp=FastAPI()@app.get('/items/{item_id}')asyncdefread_items(item_id:str=Path(default=None,max_length=3,min_length=1,title='theidofitemtoget')):"""def......
  • FastAPI系列:查询字符串参数
    单个查询字符串@app.get('/index/{username}')defindex(username:str,id:int):#id为查询字符串?id=5return{"message":"success","username":username,"id":id}可选的查询字符串参数@app.get('/items/{item_id}......
  • FastAPI系列:APIRouter实例的路由注册
    APIRouter实例的路由注册API端点路由注册大致分为3种:1.基于app实例对象提供的装饰器或函数进行注册2.基于FastAPI提供的APIRouter类的实例对象提供的装饰器或函数进行注册3.通过直接实例化APIRoute对象且添加的方式进行注册路由注册方式基于APIRouter的实例对象实现路由注册......
  • FastAPI系列:mount应用挂载
    mount应用挂载1.创建主app应用对象实例,注册所属的路由信息fromfastapiimportFastAPIfromfastapi.responseimportJSONResponseapp=FastAPI(title='主应用',description='主应用描述',version='v1.0.0')@app.get('/index',summary='首页')......
  • FastAPI系列:全局routes参数的使用
    全局routes参数的使用fromfastapiimportFastAPI,Requestfromfastapi.responseimportJSONResponsefromfastapi.routingimportAPIRouteasyncdeffastapi_index():returnJSONResponse({'index':'fastapi_index'})asyncdeffastapi_about()......
  • FastAPI系列:路由之节点元数据参数说明
    节点元数据参数说明#拿app.get()方法的参数来说明,其他的差不多类似defget(self,path:str,*,response_model:Optional[Type[Any]]=None,status_code:Optional[int]=None,tags:Optional[List[Union[str,Enum]]]......