在Django命令行或vscode launch.json中指定一个.env文件



目前我有一个Django项目在VS Code中运行。当前使用单个.env文件连接到SQL Server数据库。

环境/.env

DATABASE_URL=mssql://USER_NAME:PASSWORD@SERVER_NAME/DATABASE_NAME

settings.py

import environ

env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)

BASE_DIR = Path(__file__).resolve().parent.parent
ENVIRONMENT_DIR = os.path.join(BASE_DIR, "environments")
environ.Env.read_env(os.path.join(ENVIRONMENT_DIR, '.env'))
env = environ.Env()
...
DATABASES = {
"default": env.db_url(),
}
}

__.vscode/launch.json

在VS Code中运行,启动配置如下:

{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": [
"runserver",
],
"django": true
},
]
}

问题是,是否有可能使用不同的多环境文件连接到多个不同的环境?比如:

  • dev.env
  • test.env
  • prod.env

然后让VS Code从launch.json运行一个特定的。env。

来源:

https://django-environ.readthedocs。Io/
https://django-environ.readthedocs.io/en/latest/tips.html#multiple-env-files
https://djangostars.com/blog/configuring-django-settings-best-practices/

看起来你可以根据这个问题指定环境变量- https://github.com/microsoft/vscode-python/issues/6986.

因此需要修改如下:

.vscode/launch.json

{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": [
"runserver",
],
"env": {
"ENVIRONMENT_FILE": "dev.env"
},
"django": true
},
]
}

settings.py

BASE_DIR = Path(__file__).resolve().parent.parent
ENVIRONMENT_DIR = os.path.join(BASE_DIR, "environments")
ENVIRONMENT_FILE = os.environ.get("ENVIRONMENT_FILE", default=".env")
ENVIRONMENT_FILE_FULL_PATH = os.path.join(ENVIRONMENT_DIR, ENVIRONMENT_FILE)
environ.Env.read_env(ENVIRONMENT_FILE_FULL_PATH)
env = environ.Env()

相关内容

  • 没有找到相关文章

最新更新