Ejemplo n.º 1
0
def settings():
    mode = 'TRAVIS' if os.environ.get('TRAVIS') else 'TEST'
    os.environ['DYNA%s_HOSTNAME' % mode] = 'host.com'
    os.environ['DYNA%s_PORT' % mode] = '@int 5000'
    os.environ['DYNA%s_VALUE' % mode] = '@float 42.1'
    os.environ['DYNA%s_ALIST' % mode] = '@json ["item1", "item2", "item3"]'
    os.environ['DYNA%s_ADICT' % mode] = '@json {"key": "value"}'
    os.environ['DYNA%s_DEBUG' % mode] = '@bool true'
    os.environ['PROJECT1_HOSTNAME'] = 'otherhost.com'
    sets = LazySettings(
        LOADERS_FOR_DYNACONF=[
            'dynaconf.loaders.env_loader',
            'dynaconf.loaders.redis_loader'
        ],
        DYNACONF_NAMESPACE="DYNA%s" % mode
    )
    sets.configure()
    return sets
Ejemplo n.º 2
0
def test_no_reload_on_single_env(tmpdir, mocker):
    tmpfile = tmpdir.join("settings.toml")
    tmpfile.write(TOML)

    same_env_validator = Validator("VERSION",
                                   is_type_of=int,
                                   env="development")
    other_env_validator = Validator("NAME", must_exist=True, env="production")

    settings = LazySettings(ENV_FOR_DYNACONF="DEVELOPMENt",
                            SETTINGS_FILE_FOR_DYNACONF=str(tmpfile))
    using_env = mocker.patch.object(settings, "from_env")

    settings.validators.register(same_env_validator)
    settings.validators.validate()
    using_env.assert_not_called()

    settings.validators.register(other_env_validator)
    settings.validators.validate()
    using_env.assert_any_call("production")
    assert using_env.call_count == 1
Ejemplo n.º 3
0
def test_set_new_merge_issue_241_1(tmpdir):
    data = {
        "default": {
            "name": "Bruno",
            "colors": ["red", "green"],
            "data": {
                "links": {
                    "twitter": "rochacbruno",
                    "site": "brunorocha.org"
                }
            },
        }
    }
    toml_loader.write(str(tmpdir.join("settings.toml")), data, merge=False)
    settings = LazySettings(environments=True, settings_file="settings.toml")
    assert settings.NAME == "Bruno"
    assert settings.COLORS == ["red", "green"]
    assert settings.DATA.links == {
        "twitter": "rochacbruno",
        "site": "brunorocha.org",
    }
Ejemplo n.º 4
0
def test_envless_mode_with_prefix(tmpdir):
    data = {
        "prefix_foo": "bar",
        "hello": "world",
        "prefix_default": 1,
        "prefix_databases": {
            "default": {
                "port": 8080
            }
        },
    }
    toml_loader.write(str(tmpdir.join("settings.toml")), data)

    settings = LazySettings(
        settings_file="settings.toml",
        filter_strategy=PrefixFilter("prefix"))  # already the default
    assert settings.FOO == "bar"
    with pytest.raises(AttributeError):
        settings.HELLO
    assert settings.DEFAULT == 1
    assert settings.DATABASES.default.port == 8080
Ejemplo n.º 5
0
def test_validator_custom_message(tmpdir):
    """Assert custom message is being processed by validator."""
    tmpfile = tmpdir.join("settings.toml")
    tmpfile.write(TOML)

    settings = LazySettings(environments=True,
                            SETTINGS_FILE_FOR_DYNACONF=str(tmpfile),
                            silent=True)

    custom_msg = "You cannot set {name} to {value} in env {env}"
    settings.validators.register(
        Validator("MYSQL_HOST", eq="development.com", env="DEVELOPMENT"),
        Validator("MYSQL_HOST", ne="development.com", env="PRODUCTION"),
        Validator("VERSION", ne=1, messages={"operations": custom_msg}),
    )

    with pytest.raises(ValidationError) as error:
        settings.validators.validate()

    assert custom_msg.format(name="VERSION", value="1",
                             env="DEVELOPMENT") in str(error)
Ejemplo n.º 6
0
def test_config_aliases(tmpdir):
    data = {
        "hello": {
            "name": "Bruno",
            "passwd": 1234
        },
        "awesome": {
            "passwd": 5678
        },
    }
    toml_loader.write(str(tmpdir.join("blarg.toml")), data, merge=False)

    settings = LazySettings(
        envvar_prefix="BRUCE",
        core_loaders=["TOML"],
        loaders=["dynaconf.loaders.env_loader"],
        default_env="hello",
        env_switcher="BRUCE_ENV",
        prelaod=[],
        settings_file=["blarg.toml"],
        includes=[],
        ENV="awesome",
        environments=True,
    )

    assert settings.NAME == "Bruno"
    assert settings.PASSWD == 5678

    assert settings.ENVVAR_PREFIX_FOR_DYNACONF == "BRUCE"
    assert settings.CORE_LOADERS_FOR_DYNACONF == ["TOML"]
    assert settings.LOADERS_FOR_DYNACONF == ["dynaconf.loaders.env_loader"]
    assert len(settings._loaders) == 1
    assert settings.DEFAULT_ENV_FOR_DYNACONF == "hello"
    assert settings.ENV_SWITCHER_FOR_DYNACONF == "BRUCE_ENV"
    assert settings.PRELOAD_FOR_DYNACONF == []
    assert settings.SETTINGS_FILE_FOR_DYNACONF == ["blarg.toml"]
    assert settings.INCLUDES_FOR_DYNACONF == []
    assert settings.ENV_FOR_DYNACONF == "awesome"
    assert settings.current_env == "awesome"
Ejemplo n.º 7
0
def test_lowercase_read_mode(tmpdir):
    """
    Starting on 3.0.0 lowercase keys are enabled by default
    """
    data = {
        "foo": "bar",
        "hello": "world",
        "default": 1,
        "databases": {
            "default": {
                "port": 8080
            }
        },
    }
    toml_loader.write(str(tmpdir.join("settings.toml")), data)

    # settings_files mispelled.. should be `settings_file`
    settings = LazySettings(settings_files="settings.toml")

    assert settings.FOO == "bar"
    assert settings.foo == "bar"
    assert settings.HELLO == "world"
    assert settings.hello == "world"
    assert settings.DEFAULT == 1
    assert settings.default == 1
    assert settings.DATABASES.default.port == 8080
    assert settings.databases.default.port == 8080

    assert "foo" in settings
    assert "FOO" in settings

    # test __dir__
    results = dir(settings)
    assert "foo" in results
    assert "FOO" in results

    results = dir(settings.databases)
    assert "default" in results
    assert "DEFAULT" in results
Ejemplo n.º 8
0
def test_cast_before_validate(tmpdir):
    tmpfile = tmpdir.join("settings.toml")
    TOML = """
    name = 'Bruno'
    colors = ['red', 'green', 'blue']
    """
    tmpfile.write(TOML)
    settings = LazySettings(
        settings_file=str(tmpfile),
        silent=True,
        lowercase_read=True,
        validators=[
            Validator("name", len_eq=5),
            Validator("name", len_min=1),
            Validator("name", len_max=5),
            Validator("colors", len_eq=3),
            Validator("colors", len_eq=3),
            Validator("colors", len_eq=24, cast=str),
        ],
    )
    assert settings.name == "Bruno"
    assert settings.colors == ["red", "green", "blue"]
Ejemplo n.º 9
0
def test_set_new_merge_issue_241_2(tmpdir):
    data = {
        "default": {
            "name": "Bruno",
            "colors": ["red", "green"],
            "data": {
                "links": {
                    "twitter": "rochacbruno",
                    "site": "brunorocha.org"
                }
            },
        }
    }
    toml_loader.write(str(tmpdir.join("settings.toml")), data, merge=False)

    data = {
        "dynaconf_merge": True,
        "default": {
            "colors": ["blue"],
            "data": {
                "links": {
                    "github": "rochacbruno.github.io"
                }
            },
        },
    }
    toml_loader.write(str(tmpdir.join("settings.local.toml")),
                      data,
                      merge=False)

    settings = LazySettings()
    assert settings.NAME == "Bruno"
    assert settings.COLORS == ["red", "green", "blue"]
    assert settings.DATA.links == {
        "twitter": "rochacbruno",
        "site": "brunorocha.org",
        "github": "rochacbruno.github.io",
    }
Ejemplo n.º 10
0
def test_preload(tmpdir):
    data = {
        "default": {
            "data": {
                "links": {"twitter": "rochacbruno", "site": "brunorocha.org"}
            }
        }
    }
    toml_loader.write(str(tmpdir.join("preload.toml")), data, merge=False)

    data = {
        "dynaconf_merge": True,
        "default": {"data": {"links": {"github": "rochacbruno.github.io"}}},
    }
    toml_loader.write(
        str(tmpdir.join("main_settings.toml")), data, merge=False
    )

    data = {
        "dynaconf_merge": True,
        "default": {
            "data": {"links": {"mastodon": "mastodon.social/@rochacbruno"}}
        },
    }
    toml_loader.write(str(tmpdir.join("included.toml")), data, merge=False)

    settings = LazySettings(
        PRELOAD_FOR_DYNACONF=["preload.toml"],
        SETTINGS_FILE_FOR_DYNACONF="main_settings.toml",
        INCLUDES_FOR_DYNACONF=["included.toml"],
    )

    assert settings.DATA.links == {
        "twitter": "rochacbruno",
        "site": "brunorocha.org",
        "github": "rochacbruno.github.io",
        "mastodon": "mastodon.social/@rochacbruno",
    }
Ejemplo n.º 11
0
def test_config_aliases(tmpdir):
    data = {
        "hello": {
            "name": "Bruno",
            "passwd": 1234
        },
        "awesome": {
            "passwd": 5678
        },
    }
    toml_loader.write(str(tmpdir.join("blarg.toml")), data, merge=False)

    settings = LazySettings(
        ENVVAR_PREFIX="BRUCE",
        CORE_LOADERS=["TOML"],
        LOADERS=["dynaconf.loaders.env_loader"],
        DEFAULT_ENV="hello",
        ENV_SWITCHER="BRUCE_ENV",
        PRELOAD=[],
        SETTINGS_FILE=["blarg.toml"],
        INCLUDES=[],
        ENV="awesome",
    )

    assert settings.NAME == "Bruno"
    assert settings.PASSWD == 5678

    assert settings.ENVVAR_PREFIX_FOR_DYNACONF == "BRUCE"
    assert settings.CORE_LOADERS_FOR_DYNACONF == ["TOML"]
    assert settings.LOADERS_FOR_DYNACONF == ["dynaconf.loaders.env_loader"]
    assert len(settings._loaders) == 1
    assert settings.DEFAULT_ENV_FOR_DYNACONF == "hello"
    assert settings.ENV_SWITCHER_FOR_DYNACONF == "BRUCE_ENV"
    assert settings.PRELOAD_FOR_DYNACONF == []
    assert settings.SETTINGS_FILE_FOR_DYNACONF == ["blarg.toml"]
    assert settings.INCLUDES_FOR_DYNACONF == []
    assert settings.ENV_FOR_DYNACONF == "awesome"
    assert settings.current_env == "awesome"
Ejemplo n.º 12
0
def test_set_new_merge_issue_241_4(tmpdir):
    data = {
        "name": "Bruno",
        "colors": ["red", "green"],
        "data": {
            "links": {"twitter": "rochacbruno", "site": "brunorocha.org"}
        },
    }
    toml_loader.write(str(tmpdir.join("settings.toml")), data, merge=False)

    data = {"data__links__telegram": "t.me/rochacbruno"}
    toml_loader.write(
        str(tmpdir.join("settings.local.toml")), data, merge=False
    )

    settings = LazySettings(settings_file="settings.toml")
    assert settings.NAME == "Bruno"
    assert settings.COLORS == ["red", "green"]
    assert settings.DATA.links == {
        "twitter": "rochacbruno",
        "site": "brunorocha.org",
        "telegram": "t.me/rochacbruno",
    }
Ejemplo n.º 13
0
def test_set_new_merge_issue_241_3(tmpdir):
    data = {
        "name": "Bruno",
        "colors": ["red", "green"],
        "data": {
            "links": {"twitter": "rochacbruno", "site": "brunorocha.org"}
        },
    }
    toml_loader.write(str(tmpdir.join("settings.toml")), data, merge=False)

    data = {
        "name": "Tommy Shelby",
        "colors": {"dynaconf_merge": ["yellow", "pink"]},
        "data": {"links": {"site": "pb.com"}},
    }
    toml_loader.write(
        str(tmpdir.join("settings.local.toml")), data, merge=False
    )

    settings = LazySettings(settings_file="settings.toml")
    assert settings.NAME == "Tommy Shelby"
    assert settings.COLORS == ["red", "green", "yellow", "pink"]
    assert settings.DATA.links == {"site": "pb.com"}
Ejemplo n.º 14
0
def test_set_explicit_merge_token(tmpdir):
    data = {
        "a_list": [1, 2],
        "b_list": [1],
        "a_dict": {
            "name": "Bruno"
        },
    }
    toml_loader.write(str(tmpdir.join("settings.toml")), data, merge=False)
    settings = LazySettings(settings_file="settings.toml")
    assert settings.A_LIST == [1, 2]
    assert settings.B_LIST == [1]
    assert settings.A_DICT == {"name": "Bruno"}
    assert settings.A_DICT.name == "Bruno"

    settings.set("a_list", [3], merge=True)
    assert settings.A_LIST == [1, 2, 3]

    settings.set("b_list", "@merge [2]")
    assert settings.B_LIST == [1, 2]

    settings.set("b_list", "@merge [3, 4]")
    assert settings.B_LIST == [1, 2, 3, 4]

    settings.set("b_list", "@merge 5")
    assert settings.B_LIST == [1, 2, 3, 4, 5]

    settings.set("b_list", "@merge 6.6")
    assert settings.B_LIST == [1, 2, 3, 4, 5, 6.6]

    settings.set("b_list", "@merge false")
    assert settings.B_LIST == [1, 2, 3, 4, 5, 6.6, False]

    settings.set("b_list", "@merge foo,bar")
    assert settings.B_LIST == [1, 2, 3, 4, 5, 6.6, False, "foo", "bar"]

    settings.set("b_list", "@merge zaz")
    assert settings.B_LIST == [1, 2, 3, 4, 5, 6.6, False, "foo", "bar", "zaz"]

    settings.set("a_dict", "@merge {city='Guarulhos'}")
    assert settings.A_DICT.name == "Bruno"
    assert settings.A_DICT.city == "Guarulhos"

    settings.set("a_dict", "@merge country=Brasil")
    assert settings.A_DICT.name == "Bruno"
    assert settings.A_DICT.city == "Guarulhos"
    assert settings.A_DICT.country == "Brasil"

    settings.set("new_key", "@merge foo=bar")
    assert settings.NEW_KEY == {"foo": "bar"}
def load(
    obj: dynaconf.LazySettings,
    env: str = None,
    silent: bool = True,
    key: str = None,
    filename: str = None,
) -> None:
    """
    Read and load in to `obj` a single key or all keys from ARTIQ datasets.

    If you would like different name mappings, they need to be specified
    in a settings file (either set as an environment variable TODO,
    or defaults to TODO).
    This defaults to connecting to an ARTIQ master instance on the local machine,
    but can be changed with the environment variable: TODO

    Args:
        obj (dynaconf.LazySettings): the settings instance
        env (str): settings current env (upper case) default='DEVELOPMENT'
        silent (bool): if errors should raise
        key (str): if defined load a single key, else load all from `env`
        filename (str): Custom filename to load (useful for tests)

    Returns:
        None

    """
    # pylint: disable=unused-argument
    # REQUIRED FILES:
    #   ? ARTIQ config settings (master IP address)??
    #   ? ARTIQ dataset mappings to variable names?? Env var?
    # Load data from your custom data source (file, database, memory etc)
    # use `obj.set(key, value)` or `obj.update(dict)` to load data
    # use `obj.logger.debug` to log your loader activities
    # use `obj.find_file('filename.ext')` to find the file in search tree
    # Return nothing

    port = 3250
    ip = "::1"
    # TODO: make ip, port, mapping_file to be dynamic-set

    mapping_file_path = pathlib.Path(obj.find_file("artiq_dataset_map.pyon"))
    if mapping_file_path.exists() and mapping_file_path.is_file():
        obj.logger.debug("Using key mapping file `%s`")
        key_to_dataset_map = pyon.decode(obj.read_file(mapping_file_path))
        dynaconf_keys = list(sorted(key_to_dataset_map.keys()))
        if key is not None and key in dynaconf_keys:
            dynaconf_keys = [key]
        elif key is not None:
            # TODO: handle silent
            raise KeyError(
                "Key {} not in ARTIQ mapping file {}".format(key, mapping_file_path)
            )
        try:
            artiq_datasets = artiq_connection.Client(
                ip, port, "master_dataset_db", timeout=10
            )
            dynaconf_values = list(artiq_datasets.get(k) for k in dynaconf_keys)
        finally:
            artiq_datasets.close_rpc()
        obj.update(dict(zip(dynaconf_keys, dynaconf_values)))
    else:
        # TODO
        if silent:
            obj.logger.debug("Key mapping file not found. Cannot load ARTIQ datasets")
        else:
            raise NotImplementedError(
                "Loading ARTIQ datasets without mapping file isn't handled"
            )

    obj._loaded_files.append(filename)  # pylint: disable=protected-access

    return
Ejemplo n.º 16
0
import pytest
from dynaconf import LazySettings
from dynaconf.loaders.yaml_loader import load, clean

settings = LazySettings(
    NAMESPACE_FOR_DYNACONF='EXAMPLE',
)


YAML = """
# the bellow is just to ensure `,` will not break string YAML
a: "a,b"
example:
  password: 99999
  host: server.com
  port: 8080
  service:
    url: service.com
    port: 80
    auth:
        password: qwerty
        test: 1234
development:
  password: 88888
  host: dev_server.com
"""

YAML2 = """
example:
  # @float casting not needed, used only for testing
  secret: '@float 42'
Ejemplo n.º 17
0
import pytest

from dynaconf import LazySettings
from dynaconf.loaders.json_loader import load

settings = LazySettings(ENV_FOR_DYNACONF="PRODUCTION")


JSON = """
{
    "a": "a,b",
    "default": {
        "password": "******",
        "host": "server.com",
        "port": "@int 8080",
        "alist": ["item1", "item2", 23],
        "service": {
          "url": "service.com",
          "port": 80,
          "auth": {
            "password": "******",
            "test": 1234
          }
        }
    },
    "development": {
        "password": "******",
        "host": "devserver.com"
    },
    "production": {
        "password": "******",
Ejemplo n.º 18
0
import time
import json
import pymysql
import datetime as dt
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from functools import wraps
from dynaconf import LazySettings
# from common.config import SERVER_CONF
from yzy_server.database import apis as db_api
from yzy_server.database import models
from common.utils import build_result
from common import constants

settings = LazySettings(ROOT_PATH_FOR_DYNACONF=constants.BASE_DIR)
DATABASE_HOST = settings.get('HOST', '127.0.0.1')
DATABASE_PORT = settings.get('PORT', 3306)
DATABASE_USER = settings.get('USER', 'root')
DATABASE_PASSWORD = settings.get('PASSWORD', '123qwe,.')
DATABASE_NAME = settings.get('NAME', 'yzy_kvm_db')
engine = create_engine("mysql+mysqlconnector://{user}:{password}@{host}:{port}/{db_name}?charset=utf8".
                       format(**{"user": DATABASE_USER, "password": DATABASE_PASSWORD, "host": DATABASE_HOST,
                                 "port": DATABASE_PORT, "db_name": DATABASE_NAME}))
# engine = create_engine(
#     SERVER_CONF.addresses.get_by_default('sqlalchemy_database_uri',
#                                          'mysql+mysqlconnector://root:123qwe,.@localhost:3306/yzy_kvm_db?'))
logger = logging.getLogger(__name__)


def timefn(fn):
Ejemplo n.º 19
0
def test_post_load_hooks(clean_env, tmpdir):
    """Test post load hooks works

    This test uses 3 settings files

    PRELOAD = "plugin_folder/plugin.py"
    SETTINGS_FILE = "settings.py"
    HOOKFILES = ["plugin_folder/dynaconf_hooks.py", "dynaconf_hooks.py"]

    The hook file has a function called "post" which is called after
    loading the settings, that function accepts the argument `settings`
    which is a copy of the settings object, and returns a dictionary
    of settings to be merged.
    """

    # Arrange
    plugin_folder = tmpdir.mkdir("plugin_folder")
    plugin_folder.join("__init__.py").write('print("initing plugin...")')

    plugin_path = plugin_folder.join("plugin.py")
    plugin_hook = plugin_folder.join("dynaconf_hooks.py")
    settings_path = tmpdir.join("settings.py")
    settings_hook = tmpdir.join("dynaconf_hooks.py")

    to_write = {
        str(plugin_path): ["PLUGIN_NAME = 'DummyPlugin'"],
        str(settings_path): [
            "INSTALLED_APPS = ['admin']",
            "COLORS = ['red', 'green']",
            "DATABASES = {'default': {'NAME': 'db'}}",
            "BANDS = ['Rush', 'Yes']",
        ],
        str(plugin_hook): [
            "post = lambda settings: "
            "{"
            "'PLUGIN_NAME': settings.PLUGIN_NAME.lower(),"
            "'COLORS': '@merge blue',"
            "'DATABASES__default': '@merge PORT=5151',"
            "'DATABASES__default__VERSION': 42,"
            "'DATABASES__default__FORCED_INT': '@int 12',",
            "'BANDS': ['Anathema', 'dynaconf_merge']"
            "}",
        ],
        str(settings_hook): [
            "post = lambda settings: "
            "{"
            "'INSTALLED_APPS': [settings.PLUGIN_NAME],"
            "'dynaconf_merge': True,"
            "}"
        ],
    }

    for path, lines in to_write.items():
        with open(str(path),
                  "w",
                  encoding=default_settings.ENCODING_FOR_DYNACONF) as f:
            for line in lines:
                f.write(line)
                f.write("\n")

    # Act
    settings = LazySettings(preload=["plugin_folder.plugin"],
                            settings_file="settings.py")

    # Assert
    assert settings.PLUGIN_NAME == "dummyplugin"
    assert settings.INSTALLED_APPS == ["admin", "dummyplugin"]
    assert settings.COLORS == ["red", "green", "blue"]
    assert settings.DATABASES.default.NAME == "db"
    assert settings.DATABASES.default.PORT == 5151
    assert settings.DATABASES.default.VERSION == 42
    assert settings.DATABASES.default.FORCED_INT == 12
    assert settings.BANDS == ["Rush", "Yes", "Anathema"]
    assert settings._loaded_hooks[str(plugin_hook)] == {
        "post": {
            "PLUGIN_NAME": "dummyplugin",
            "COLORS": "@merge blue",
            "DATABASES__default": "@merge PORT=5151",
            "DATABASES__default__VERSION": 42,
            "DATABASES__default__FORCED_INT": "@int 12",
            "BANDS": ["Anathema", "dynaconf_merge"],
        }
    }
    assert settings._loaded_hooks[str(settings_hook)] == {
        "post": {
            "INSTALLED_APPS": ["dummyplugin"],
        }
    }
Ejemplo n.º 20
0
def test_validators(tmpdir):

    tmpfile = tmpdir.join("settings.toml")
    tmpfile.write(TOML)

    settings = LazySettings(
        ENV_FOR_DYNACONF="EXAMPLE",
        SETTINGS_FILE_FOR_DYNACONF=str(tmpfile),
        silent=True,
    )

    settings.validators.register(
        Validator("VERSION", "AGE", "NAME", must_exist=True),
        Validator("AGE", lte=30, gte=10),
        Validator("PROJECT", eq="hello_world"),
        Validator("PRESIDENT", env="DEVELOPMENT", ne="Trump"),
        Validator("SALARY", lt=1000000, gt=1000),
        Validator("DEV_SERVERS", must_exist=True, is_type_of=(list, tuple)),
        Validator("MYSQL_HOST", env="DEVELOPMENT", is_in=settings.DEV_SERVERS),
        Validator("MYSQL_HOST",
                  env="PRODUCTION",
                  is_not_in=settings.DEV_SERVERS),
        Validator("NAME", condition=lambda x: x in ("BRUNO", "MIKE")),
        Validator(
            "IMAGE_1",
            "IMAGE_2",
            env="development",
            must_exist=True,
            when=Validator("BASE_IMAGE",
                           must_exist=True,
                           env=settings.ENV_FOR_DYNACONF),
        ),
        Validator(
            "IMAGE_4",
            "IMAGE_5",
            env=("development", "production"),
            must_exist=True,
            when=Validator("BASE_IMAGE",
                           must_exist=False,
                           env=settings.ENV_FOR_DYNACONF),
        ),
        Validator(
            "PORT",
            must_exist=True,
            ne=8000,
            when=Validator("MYSQL_HOST", eq="localhost"),
        ),
        #
        Validator("ZERO", is_type_of=int, eq=0),
        Validator("FALSE", is_type_of=bool, eq=False),
    )

    assert settings.validators.validate() is None

    settings.validators.register(
        Validator("TESTVALUEZZ", env="development"),
        Validator("TESTVALUE", eq="hello_world"),
    )

    with pytest.raises(ValidationError):
        settings.validators.validate()

    with pytest.raises(TypeError):
        Validator("A", condition=1)

    with pytest.raises(TypeError):
        Validator("A", when=1)
Ejemplo n.º 21
0
def test_from_env_method(clean_env, tmpdir):
    data = {
        "default": {
            "a_default": "From default env"
        },
        "development": {
            "value": "From development env",
            "only_in_development": True,
        },
        "other": {
            "value": "From other env",
            "only_in_other": True
        },
    }
    toml_path = str(tmpdir.join("base_settings.toml"))
    toml_loader.write(toml_path, data, merge=False)
    settings = LazySettings(settings_file=toml_path, environments=True)
    settings.set("ARBITRARY_KEY", "arbitrary value")

    assert settings.VALUE == "From development env"
    assert settings.A_DEFAULT == "From default env"
    assert settings.ONLY_IN_DEVELOPMENT is True
    assert settings.ARBITRARY_KEY == "arbitrary value"
    assert settings.get("ONLY_IN_OTHER") is None

    # clone the settings object pointing to a new env
    other_settings = settings.from_env("other")
    assert other_settings.VALUE == "From other env"
    assert other_settings.A_DEFAULT == "From default env"
    assert other_settings.ONLY_IN_OTHER is True
    assert other_settings.get("ARBITRARY_KEY") is None
    assert other_settings.get("ONLY_IN_DEVELOPMENT") is None
    with pytest.raises(AttributeError):
        # values set programatically are not cloned
        other_settings.ARBITRARY_KEY
    with pytest.raises(AttributeError):
        # values set only in a specific env not cloned
        other_settings.ONLY_IN_DEVELOPMENT
    # assert it is cached not created twice
    assert other_settings is settings.from_env("other")

    # Now the same using keep=True
    other_settings = settings.from_env("other", keep=True)
    assert other_settings.VALUE == "From other env"
    assert other_settings.A_DEFAULT == "From default env"
    assert other_settings.ONLY_IN_OTHER is True
    assert other_settings.ONLY_IN_DEVELOPMENT is True
    assert settings.ARBITRARY_KEY == "arbitrary value"

    # assert it is created not cached
    assert other_settings is not settings.from_env("other")

    # settings remains the same
    assert settings.VALUE == "From development env"
    assert settings.A_DEFAULT == "From default env"
    assert settings.ONLY_IN_DEVELOPMENT is True
    assert settings.ARBITRARY_KEY == "arbitrary value"
    assert settings.get("ONLY_IN_OTHER") is None

    # additional kwargs
    data = {
        "default": {
            "a_default": "From default env"
        },
        "production": {
            "value": "From prod env",
            "only_in_prod": True
        },
        "other": {
            "value": "From other env",
            "only_in_other": True
        },
    }
    toml_path = str(tmpdir.join("other_settings.toml"))
    toml_loader.write(toml_path, data, merge=False)

    new_other_settings = other_settings.from_env(
        "production", keep=True, SETTINGS_FILE_FOR_DYNACONF=toml_path)

    # production values
    assert new_other_settings.VALUE == "From prod env"
    assert new_other_settings.ONLY_IN_PROD is True
    # keep=True values
    assert new_other_settings.ONLY_IN_OTHER is True
    assert new_other_settings.ONLY_IN_DEVELOPMENT is True
    assert settings.A_DEFAULT == "From default env"
Ejemplo n.º 22
0
 def init_app(self, app, **kwargs):
     """kwargs holds initial dynaconf configuration"""
     self.kwargs.update(kwargs)
     self.settings = self.dynaconf_instance or LazySettings(**self.kwargs)
     app.config = self.make_config(app)
     app.dynaconf = self.settings
Ejemplo n.º 23
0
from dynaconf import LazySettings

settings = LazySettings(envless_mode=True, lowercase_read=True)

assert settings.server == "foo.com"
assert settings.SERVER == "foo.com"
assert settings["SERVER"] == "foo.com"
assert settings["server"] == "foo.com"
assert settings("SERVER") == "foo.com"
assert settings("server") == "foo.com"
assert settings.get("SERVER") == "foo.com"
assert settings.get("server") == "foo.com"
Ejemplo n.º 24
0
Archivo: conf.py Proyecto: LVNIT/Karaka
from pathlib import Path

from dynaconf import LazySettings

# Tell dynaconf to search in folder of this conf.py file first
config = LazySettings(ROOT_PATH_FOR_DYNACONF=Path(__file__).parent,
                      CORE_LOADERS_FOR_DYNACONF=('TOML', ),
                      SETTINGS_FILE_FOR_DYNACONF=('settings.toml',
                                                  '.secrets.toml'))

config.DATABASES = {
    'default': {
        'engine': 'tortoise.backends.asyncpg',
        'credentials': {
            'host': None,
            'port': 0,
            'user': None,
            'password': None,
            'database': config.DB_NAME,
        }
    },
}
Ejemplo n.º 25
0
# coding: utf-8
from dynaconf import LazySettings, Validator

settings = LazySettings(ENV_FOR_DYNACONF='EXAMPLE', silent=True)

settings.validators.register(
    Validator('VERSION', 'AGE', 'NAME', must_exist=True),
    Validator(
        'AGE',
        lte=30,
        gte=10,
    ), Validator(
        'PROJECT',
        eq='hello_world',
    ), Validator(
        'PRESIDENT',
        env='DEVELOPMENT',
        ne='Trump',
    ), Validator('SALARY', lt=1000000, gt=1000),
    Validator('DEV_SERVERS', must_exist=True, is_type_of=(list, tuple)),
    Validator('MYSQL_HOST', env='DEVELOPMENT', is_in=settings.DEV_SERVERS),
    Validator('MYSQL_HOST', env='PRODUCTION', is_not_in=settings.DEV_SERVERS),
    Validator('NAME', condition=lambda x: x in ('BRUNO', 'MIKE')),
    Validator('IMAGE_1',
              'IMAGE_2',
              env='development',
              must_exist=True,
              when=Validator('BASE_IMAGE',
                             must_exist=True,
                             env=settings.ENV_FOR_DYNACONF)),
    Validator('IMAGE_4',
Ejemplo n.º 26
0
# -*- coding: utf-8 -*-
import multiprocessing
import os
from dynaconf import LazySettings
from common.utils import _ConfigParser
from common import constants

basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
settings = LazySettings(ROOT_PATH_FOR_DYNACONF=constants.BASE_DIR)


class BaseConfig:
    """
    生产配置
    """
    DEBUG = False

    _LOCALES = ['en_US', 'zh_Hans_CN']
    BABEL_DEFAULT_LOCALE = _LOCALES[0]
    SECRET_KEY = os.getenv('SECRET_KEY', 'a secret string')

    # 数据库配置
    DATABASE_HOST = settings.get('HOST', '127.0.0.1')
    DATABASE_PORT = settings.get('PORT', 3306)
    DATABASE_USER = settings.get('USER', 'root')
    DATABASE_PASSWORD = settings.get('PASSWORD', '123qwe,.')
    DATABASE_NAME = settings.get('NAME', 'yzy_kvm_db')
    # DATABASE_HOST = '127.0.0.1'
    # DATABASE_PORT = 3306
    # DATABASE_USER = '******'
    # DATABASE_PASSWORD = '******'
Ejemplo n.º 27
0
    #     return os.environ["APPDATA"]


def get_home():
    return os.path.join(get_user_home(), '.omc')


settings_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'settings.yaml')

module_setting_files = []
for finder, name, ispkg in pkgutil.iter_modules():
    if name.startswith('omc_'):
        resource_type = name.replace('omc_', '').lower()
        try:
            module_setting_file = pkg_resources.resource_filename(
                'omc_%(resource_type)s.config' % locals(), 'settings.yaml')
            if os.path.exists(module_setting_file):
                module_setting_files.append(module_setting_file)
        except Exception as error:
            pass

settings = LazySettings(
    # PRELOAD_FOR_DYNACONF=[os.path.join(os.environ['HOME'], '.omw', 'config', '*')]
    SETTINGS_FILE_FOR_DYNACONF=
    settings_file,  # <-- Loaded second (the main file)
    INCLUDES_FOR_DYNACONF=[
        *module_setting_files,
        os.path.join(get_home(), 'config', '*.yaml')
    ])
Ejemplo n.º 28
0
import sys
import json

from typing import Dict
from dynaconf import LazySettings

from opa.core.logger import log

config = LazySettings()

from opa.core.plugin import (
    HookDefinition,
    Hook,
    Driver,
    Setup,
    get_plugin_manager,
    get_util,
    get_component,
    get_instance,
    get_router,
    call_hook,
    call_hook_async,
)


def init_configuration():
    config.configure(
        ENV_SWITCHER_FOR_DYNACONF='ENV',
        ENVVAR_PREFIX_FOR_DYNACONF='OPA',
        ROOT_PATH_FOR_DYNACONF='/data/settings',
        ENVIRONMENTS_FOR_DYNACONF=True,
Ejemplo n.º 29
0
# -*- coding: utf-8 -*-
import os
from dynaconf import LazySettings
from common.utils import _ConfigParser
from common.constants import BASE_DIR

basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
settings = LazySettings(ROOT_PATH_FOR_DYNACONF=BASE_DIR)


class BaseConfig:
    """
    生产配置
    """
    DEBUG = False

    _LOCALES = ['en_US', 'zh_Hans_CN']
    BABEL_DEFAULT_LOCALE = _LOCALES[0]
    SECRET_KEY = os.getenv('SECRET_KEY', 'a secret string')

    # 数据库配置
    DATABASE_HOST = settings.get('HOST', '127.0.0.1')
    DATABASE_PORT = settings.get('PORT', 3306)
    DATABASE_USER = settings.get('USER', 'root')
    DATABASE_PASSWORD = settings.get('PASSWORD', '123qwe,.')
    DATABASE_NAME = settings.get('NAME', 'yzy_kvm_db')
    # DATABASE_HOST = '127.0.0.1'
    # DATABASE_PORT = 3306
    # DATABASE_USER = '******'
    # DATABASE_PASSWORD = '******'
    # DATABASE_NAME = 'yzy_kvm_db'
Ejemplo n.º 30
0
from dynaconf import LazySettings, Validator

from uptimer import ROOT_PATH

settings = LazySettings(
    DEBUG_LEVEL_FOR_DYNACONF="DEBUG",
    CORE_LOADERS_FOR_DYNACONF=["TOML", "ENV"],
    ENV_SWITCHER_FOR_DYNACONF="UPTIMER_ENV",
    ENVVAR_PREFIX_FOR_DYNACONF=False,
    LOADERS_FOR_DYNACONF=["dynaconf.loaders.env_loader"],
    ROOT_PATH_FOR_DYNACONF=ROOT_PATH,
    SETTINGS_FILE_FOR_DYNACONF="settings.toml,.secrets.toml",
)

settings.validators.register(
    # Ensure writer plugin exists
    Validator("WRITER_PLUGIN", must_exist=True),
    # Ensure reader plugin exists, but only when queue plugin does not
    Validator("READER_PLUGIN",
              must_exist=True,
              when=Validator("QUEUE_PLUGIN", eq="")),
)
settings.validators.validate()
Ejemplo n.º 31
0
from __future__ import annotations

from dynaconf import LazySettings
from dynaconf import Validator
from dynaconf.utils.parse_conf import Lazy

settings = LazySettings(
    environments=True,
    ENV="EXAMPLE",
    load_dotenv=True,
    settings_files="settings.py",
)

settings.validators.register(
    Validator("VERSION", "AGE", "NAME", must_exist=True),
    Validator("AGE", lte=30, gte=10),
    Validator("PROJECT", eq="hello_world"),
    Validator("PRESIDENT", env="DEVELOPMENT", ne="Trump"),
    Validator("SALARY", lt=1000000, gt=1000),
    Validator("DEV_SERVERS", must_exist=True, is_type_of=(list, tuple)),
    Validator("MYSQL_HOST", env="DEVELOPMENT", is_in=settings.DEV_SERVERS),
    Validator("MYSQL_HOST", env="PRODUCTION", is_not_in=settings.DEV_SERVERS),
    Validator("NAME", condition=lambda x: x in ("BRUNO", "MIKE")),
    Validator(
        "IMAGE_1",
        "IMAGE_2",
        env="development",
        must_exist=True,
        when=Validator("BASE_IMAGE",
                       must_exist=True,
                       env=settings.ENV_FOR_DYNACONF),