Exemple #1
0
    def from_object(self, obj):
        """Update the values from the given object.
        Objects are usually either modules or classes.

        Just the uppercase variables in that object are stored in the config.
        Example usage::

            from yourapplication import default_config
            app.config.from_object(default_config)

            or also:
            app.config.from_object('myproject.config.MyConfigClass')

        You should not use this function to load the actual configuration but
        rather configuration defaults. The actual config should be loaded
        with :meth:`from_pyfile` and ideally from a location not within the
        package because the package might be installed system wide.

        :param obj: an object holding the configuration
        """
        if isinstance(obj, str):
            obj = import_string(obj)
        for key in dir(obj):
            if key.isupper():
                self[key] = getattr(obj, key)
Exemple #2
0
def load_module_from_file_location(
    location: Union[bytes, str, Path], encoding: str = "utf8", *args, **kwargs
):  # noqa
    """Returns loaded module provided as a file path.

    :param args:
        Coresponds to importlib.util.spec_from_file_location location
        parameters,but with this differences:
        - It has to be of a string or bytes type.
        - You can also use here environment variables
          in format ${some_env_var}.
          Mark that $some_env_var will not be resolved as environment variable.
    :encoding:
        If location parameter is of a bytes type, then use this encoding
        to decode it into string.
    :param args:
        Coresponds to the rest of importlib.util.spec_from_file_location
        parameters.
    :param kwargs:
        Coresponds to the rest of importlib.util.spec_from_file_location
        parameters.

    For example You can:

        some_module = load_module_from_file_location(
            "some_module_name",
            "/some/path/${some_env_var}"
        )
    """
    if isinstance(location, bytes):
        location = location.decode(encoding)

    if isinstance(location, Path) or "/" in location or "$" in location:

        if not isinstance(location, Path):
            # A) Check if location contains any environment variables
            #    in format ${some_env_var}.
            env_vars_in_location = set(re_findall(r"\${(.+?)}", location))

            # B) Check these variables exists in environment.
            not_defined_env_vars = env_vars_in_location.difference(
                os_environ.keys()
            )
            if not_defined_env_vars:
                raise LoadFileException(
                    "The following environment variables are not set: "
                    f"{', '.join(not_defined_env_vars)}"
                )

            # C) Substitute them in location.
            for env_var in env_vars_in_location:
                location = location.replace(
                    "${" + env_var + "}", os_environ[env_var]
                )

        location = str(location)
        if ".py" in location:
            name = location.split("/")[-1].split(".")[
                0
            ]  # get just the file name without path and .py extension
            _mod_spec = spec_from_file_location(
                name, location, *args, **kwargs
            )
            assert _mod_spec is not None  # type assertion for mypy
            module = module_from_spec(_mod_spec)
            _mod_spec.loader.exec_module(module)  # type: ignore

        else:
            module = types.ModuleType("config")
            module.__file__ = str(location)
            try:
                with open(location) as config_file:
                    exec(  # nosec
                        compile(config_file.read(), location, "exec"),
                        module.__dict__,
                    )
            except IOError as e:
                e.strerror = "Unable to load configuration file (e.strerror)"
                raise
            except Exception as e:
                raise PyFileError(location) from e

        return module
    else:
        try:
            return import_string(location)
        except ValueError:
            raise IOError("Unable to load configuration %s" % str(location))
Exemple #3
0
def test_import_string_module():
    module = helpers.import_string("sanic.config")
    assert inspect.ismodule(module)
Exemple #4
0
def test_import_string_exception():
    with pytest.raises(ImportError):
        helpers.import_string("test.test.test")
Exemple #5
0
def test_import_string_class():
    obj = helpers.import_string("sanic.config.Config")
    assert isinstance(obj, Config)