Ejemplo n.º 1
0
def test_empty_dict_on_file_not_found_error(mock_load_settings):
    # Arrange
    mock_load_settings.side_effect = FileNotFoundError()

    # Act
    json_settings = importer_json_file_settings(BaseSettings())

    # Assert
    assert json_settings == dict()
Ejemplo n.º 2
0
def test_json_file_settings(mock_load_settings):
    # Arrange
    mock_load_settings.return_value = DEFAULT_MOCK_SETTINGS

    # Act
    settings = importer_json_file_settings(BaseSettings())

    # Assert
    assert settings == DEFAULT_FILTERED_JSON_SETTINGS
Ejemplo n.º 3
0
def test_json_file_settings_remove_unknown_settings(mock_load_settings):
    # Arrange
    mock_settings = deepcopy(DEFAULT_MOCK_SETTINGS)
    mock_settings.update({"unknown": "property"})
    mock_load_settings.return_value = mock_settings

    # Act
    settings = importer_json_file_settings(BaseSettings())

    # Assert
    assert settings == DEFAULT_FILTERED_JSON_SETTINGS
def _validate(ctx: click.Context, param, value, settings_obj: BaseSettings,
              settings_class_type: SettingsClassType):
    if not value:
        return list()
    if not isinstance(value, Sequence):
        value = [value]
    config_map = {}
    for config_file in value:
        config_file = Path(config_file).resolve()
        try:
            config_map[str(config_file)] = load_dict_from_file(config_file)
        except DictLoadError as e:
            click.echo(
                f"{e.message}\nContext:\n{e.document}\nPosition = {e.position},"
                f" line number = {e.line_number}, column_number = {e.column_number}"
            )
            ctx.abort()

    target_config_dict = settings_obj.dict()
    new_settings_obj: BaseSettings = None
    for config_file, config_dict in config_map.items():
        try:
            dict_deep_update(target_config_dict,
                             cast(Dict[object, object], config_dict))
        except RecursionError as e:
            click.echo(
                f"Error reading {config_file}.\nData structure depth exceeded.\n{e}"
            )
            ctx.abort()
        except ValueError as e:
            click.echo(f"{e}")
            ctx.abort()

        try:
            new_settings_obj = settings_class_type.parse_obj(
                target_config_dict)
        except ValidationError as e:
            click.echo(f"Validation error for config file {config_file}.\n{e}")
            ctx.abort()

    ctx.default_map = new_settings_obj.dict()
    return new_settings_obj
Ejemplo n.º 5
0
def entry(
        path: str,
        request: Request,
        principal: str = Depends(get_current_principal),
        root_tree: pydantic.BaseSettings = Depends(get_root_tree),
):
    path_parts = [segment for segment in path.split("/") if segment]
    entry = root_tree.authenticated_as(principal)
    try:
        # Traverse into sub-tree(s).
        for segment in path_parts:
            try:
                unauthenticated_entry = entry[segment]
            except (KeyError, TypeError):
                raise NoEntry(path_parts)
            if hasattr(unauthenticated_entry, "authenticated_as"):
                with record_timing(request.state.metrics, "acl"):
                    entry = unauthenticated_entry.authenticated_as(principal)
            else:
                entry = unauthenticated_entry
        return entry
    except NoEntry:
        raise HTTPException(status_code=404,
                            detail=f"No such entry: {path_parts}")
Ejemplo n.º 6
0
        "https://localhost.tiangolo.com",
        "http://localhost",
        "http://localhost:8080",
    ]

    # --- debug -----
    debug: bool = False

    # ---  CORS ---

    # ---- JWT -----

    jwt_secret_key: str = Field(..., env='JWT_SECRET_KEY')
    jwt_algo: str = Field(..., env='JWT_ALGORITHM')

    # --- EMail ----

    # --- project name ---

    project_name: str = Field("FastApi_project", env='PROJECT_NAME')

    class Config:
        # change the default prefix if you want to change defaults to no prefix, i.e. ""
        env_prefix = 'my_prefix_'
        # need to check its not taking the absolute path
        env_file = "/home/sheggam/Desktop/fast_api_template/.env"


if __name__ == "__main__":
    print(BaseSettings().dict())
Ejemplo n.º 7
0
from pydantic import BaseSettings
# noinspection PyUnresolvedReferences
from .application import Bali
from .cache import cache
from .db import db

_settings = BaseSettings()


def initialize(settings):
    # update basic settings
    if not hasattr(settings, 'ENABLED_RPC_LOGGING'):
        settings.Config.__setattr__(settings, 'ENABLED_RPC_LOGGING', False)

    # load custom settings
    global _settings
    _settings = settings

    # initialize db connections, default enabled db
    # can be disabled by `DISABLE_DB_CONNECTION` settings
    if getattr(settings, 'DISABLE_DB_CONNECTION', False):
        if not hasattr(settings, 'SQLALCHEMY_DATABASE_URI'):
            raise Exception(
                'Initialized db connection without `SQLALCHEMY_DATABASE_URI` setting'
            )

        db.connect(settings.SQLALCHEMY_DATABASE_URI)

    # initialize cache connections, default enabled db
    # can be disabled by `DISABLED_DB_CONNECTION` settings
    # cache prefix can be custom by `CACHE_PREFIX`