Exemple #1
0
def set_settings(ctx, instance=None):
    """Pick correct settings instance and set it to a global variable."""

    global settings

    settings = None

    if instance is not None:
        if ctx.invoked_subcommand in ["init"]:
            raise click.UsageError(
                "-i/--instance option is not allowed for `init` command")
        sys.path.insert(0, ".")
        settings = import_settings(instance)
    elif "FLASK_APP" in os.environ:  # pragma: no cover
        with suppress(ImportError, click.UsageError):
            from flask.cli import ScriptInfo  # noqa
            from dynaconf import FlaskDynaconf

            flask_app = ScriptInfo().load_app()
            settings = FlaskDynaconf(flask_app, **flask_app.config).settings
            click.echo(
                click.style("Flask app detected",
                            fg="white",
                            bg="bright_black"))
    elif "DJANGO_SETTINGS_MODULE" in os.environ:  # pragma: no cover
        sys.path.insert(0, os.path.abspath(os.getcwd()))
        try:
            # Django extension v2
            from django.conf import settings  # noqa

            settings.DYNACONF.configure()
        except AttributeError:
            settings = LazySettings()

        if settings is not None:
            click.echo(
                click.style("Django app detected",
                            fg="white",
                            bg="bright_black"))

    if settings is None:

        if instance is None and "--help" not in click.get_os_args():
            if ctx.invoked_subcommand and ctx.invoked_subcommand not in [
                    "init",
            ]:
                warnings.warn(
                    "Starting on 3.x the param --instance/-i is now required. "
                    "try passing it `dynaconf -i path.to.settings <cmd>` "
                    "Example `dynaconf -i config.settings list` ")
                settings = legacy_settings
            else:
                settings = LazySettings(create_new_settings=True)
        else:
            settings = LazySettings()
Exemple #2
0
def import_settings(dotted_path):
    """Import settings instance from python dotted path.

    Last item in dotted path must be settings instace.

    Example: import_settings('path.to.settings')
    """
    if "." in dotted_path:
        module, name = dotted_path.rsplit(".", 1)
    else:
        raise click.UsageError(
            f"invalid path to settings instance: {dotted_path}")
    try:
        module = importlib.import_module(module)
    except ImportError as e:
        raise click.UsageError(e)
    try:
        return getattr(module, name)
    except AttributeError as e:
        raise click.UsageError(e)