python - fastapi - 从 main.py 导入配置

标签 python python-3.x python-import fastapi

我是 fastapi 的新手,到目前为止真的很棒,但我很难找到一种干净的方法将我的应用程序配置导入另一个模块。
编辑:我需要能够在运行单元测试时更改配置
这是我的目录树:

/app
| __init__.py
| /router
| | __init__.py
| | my_router.py
| /test
| | test_api.py
| config.py
| main.py
这是我的main.py文件:
from functools import lru_cache

from fastapi import FastAPI

from .router import my_router
from . import config

app = FastAPI()

app.include_router(
    my_router.router,
    prefix="/r",
    tags=["my-router"],
)


@lru_cache()
def get_setting():
    return config.Settings(admin_email="admin@domain.com")


@app.get('/')
def hello():
    return 'Hello world'
这里是 router.py :
from fastapi import APIRouter

from ..main import get_setting

router = APIRouter()

@router.get('/test')
def get_param_list(user_id: int):
    config = get_setting()
    return 'Import Ok'
这是配置文件
from pydantic import BaseSettings


class Settings(BaseSettings):
    param_folder: str = "param"
    result_folder: str = "output"

    class Config:
        env_prefix = "APP_"
然后运行 ​​uvicorn app.main:app --reload我得到了:ERROR: Error loading ASGI app. Could not import module "app.main".我猜是因为一种循环导入。但是我不知道如何将我的配置传递给我的路由器?
谢谢你的帮助 :)

最佳答案

直接在 config.py 中设置 lru 缓存怎么样? .

from functools import lru_cache
from pydantic import BaseSettings


class Settings(BaseSettings):
    admin_email: str = "admin@example.com"
    param_folder: str = "param"
    result_folder: str = "output"

    class Config:
        env_prefix = "APP_"

@lru_cache()
def get_setting():
    return Settings()
my_router.py
from fastapi import APIRouter, Depends

from ..config import Settings, get_setting

router = APIRouter()

@router.get('/test')
def get_param_list(config: Settings = Depends(get_setting)):
    return config
test.py
from fastapi.testclient import TestClient

from . import config, main

client = TestClient(main.app)


def get_settings_override():
    return config.Settings(admin_email="testing_admin@example.com")


main.app.dependency_overrides[config.get_settings] = get_settings_override

def test_app():
    response = client.get("/r/test")
    data = response.json()
    assert data == config.Settings(admin_email="testing_admin@example.com")

关于python - fastapi - 从 main.py 导入配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62780646/

相关文章:

python - 从文本文件创建用户名

python - 带有 to_field 属性的 Django 外键字段的问题

python - 类型错误 : bad operand type for unary ~: 'float' while groupby and apply a function

python - 从内部代码使用 pip 升级软件包

python - 使用理解向列表添加元素

Python Twitter 工具同时搜索和流媒体

python - 将 pandas 数据帧转换为 json 或 dict,然后返回到具有非唯一列的 df

Python 子模块未导入

python - 使 python 代码兼容 2.7 和 3.6+ 版本 - 关于队列模块

python - python模块的动态加载