我有以下文件读取
.env
文件:
from pydantic import BaseSettings, HttpUrl
class Settings(BaseSettings):
url: HttpUrl
class Config:
env_file = "config.env"
settings = Settings()
我需要做什么才能在开始时通过
config.env
?
所以
python -m uvicorn main:app --reload --env config.env
FastApi 或 Uvicorn 对此提供任何帮助吗?
从命令行,您可以将标志传递给 uvicorn
--env-file
而不是 --env
python -m uvicorn main:app --reload --env-file config.env
在 UVICORN 设置文档中了解更多相关信息此处
您可以使用 python-dotenv 从 config.env 传递所有环境。要传递自定义路径(来自):https://stackoverflow.com/a/50356056/14882170
import os
from dotenv import load_dotenv
# Get the path to the directory this file is in
BASEDIR = os.path.abspath(os.path.dirname(__file__))
# Connect the path with your '.env' file name
load_dotenv(os.path.join(BASEDIR, 'config.env'))
test_var = os.getenv("TEST_VAR")
print(test_var)
从here发布的文档中,您需要从Settings类中的.env类中调用变量。
配置.py
from pydantic import BaseSettings
class Settings(BaseSettings):
foo: str
class Config:
env_file = "config.env"
其中 config.env 有以下内容:
foo="bar"
然后将内容传递给由 lru_cache 装饰器包装的 get_settings 函数并返回这些值。
@lru_cache()
def get_settings():
return config.Settings()
之后,您可以将这些参数注入到fastapi应用程序的“/info”路径中:
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/info")
async def info(settings: config.Settings = Depends(get_settings)):
return {"foo": settings.foo}
完整的main.py应该是这样的:
from functools import lru_cache
from fastapi import Depends, FastAPI
import config
app = FastAPI()
@lru_cache()
def get_settings():
return config.Settings()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/info")
async def info(settings: config.Settings = Depends(get_settings)):
return {"foo": settings.foo}
然后只需启动您的应用程序,无需在命令中调用 env 文件:
python -m uvicorn main:app --reload
curl 输出应该是这样的:
curl http://127.0.0.1:8000/info
{"foo":"bar"}
因为这是您的自定义代码块,所以 uvicorn 或 starlette 不支持此功能。我认为你应该通过 Typer 自定义你的命令行。然后你可以通过命令行传递env文件。