Skip to content

Enhancement: Command-line argument to load extra .env files #4211

@smac89

Description

@smac89

Summary

I have a situation where I would like to load multiple .env files when the application starts, but as it stands now, litestar does not provide such a feature.

So far, I've solved the problem for myself by creating a CLIPlugin:

from pathlib import Path
from typing import Any, override

from litestar.plugins import CLIPluginProtocol


class CLIPlugin(CLIPluginProtocol):
    """The purpose of this plugin is to add the --env-file option to the run command"""

    @override
    def on_cli_init(self, cli):
        from click import Option

        run_cmd = cli.commands.get("run")
        run_cmd.params.append(
            Option(
                ["--env-file", "env_files"], multiple=True, type=Path, help="Load environment variables from file(s)"
            )
        )

        original_callback = run_cmd.callback

        def wrapped_callback(*args: Any, env_files: tuple[Path] | None = (), **kwargs: Any):
            import dotenv

            for env_file in env_files:
                dotenv.load_dotenv(dotenv_path=env_file, override=True)
            return original_callback(*args, **kwargs)

        run_cmd.callback = wrapped_callback

However, I think it would be nice to have this feature as part of Litestar.

Basic Example

litestar run --env-file .env --env-file .env.prod

Drawbacks and Impact

No response

Unresolved questions

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementThis is a new feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions