[英]Django set environment variable via command line and use in Migrations
Following on from this question - Specify a.env file in Django in command line or vscode launch.json .从这个问题开始 - 在命令行或 vscode launch.json 中指定 Django 中的 a.env 文件。 So we have an environment file for dev, test, and production - which is specified in an environment variable
ENVIRONMENT_FILE
.所以我们有一个用于开发、测试和生产的环境文件——在环境变量
ENVIRONMENT_FILE
中指定。
The.env file holds the database connection information (connection strings). .env 文件保存数据库连接信息(连接字符串)。
However, I'm struggling to pass this information when running the migration command:但是,我在运行迁移命令时很难传递这些信息:
python manage.py migrate
I need to be able to specify which environment I want the migrations to run on.我需要能够指定我希望迁移在哪个环境上运行。
Is it possible to setup environment variables before migrations can be run?是否可以在运行迁移之前设置环境变量?
You can load in the environment variables in your settings.py
file.您可以在
settings.py
文件中加载环境变量。
If you have separate .env
files for separate environments, and it is managed by the ENVIRONMENT_FILE
variable, you can use something like python-dotenv to read your env files,如果您有用于不同环境的单独
.env
文件,并且它由ENVIRONMENT_FILE
变量管理,则可以使用python-dotenv 之类的东西来读取您的 env 文件,
import os
from dotenv import load_dotenv
load_dotenv(os.getenv("ENVIRONMENT_FILE", ".env"))
Then, if your env file looks like this然后,如果你的 env 文件看起来像这样
DATABASE_URL=some-url-over-here
you can access these anywhere in your django application using os.getenv('DATABASE_URL')
您可以使用
os.getenv('DATABASE_URL')
在 django 应用程序中的任何位置访问这些
You can set environment variables before you run the migration command.您可以在运行迁移命令之前设置环境变量。 In PowerShell you can do something like:
在 PowerShell 中,您可以执行以下操作:
$env:ENVIRONMENT_FILE='test.env'
python manage.py migrate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.