SoFunction
Updated on 2024-11-13

How to do multiple environment configurations in a Python project (environment variables using .env files)

01 Demand scenarios

In Python projects, environment variables are usually configured using the.envfile to carry out, but sometimes, one of our Python projects needs to distinguish between different runtime environments, such as local development environment, test environment, and development environment. In this article, we will talk about how to do the configuration of multiple environments.

Suppose we have three environments:dev, test, proThe environment variables of the local development environment, test environment, and production environment are the same. They correspond to local development environments, test environments, and production environments, and some of these environments have the same environment variables, while others are specific to each environment.

02 Create separate .env files

Create four.envdocuments, respectively:

  • .env Storing common environment variables
  • . Stores environment variables specific to the development environment.
  • . Corresponding test environment
  • . Corresponding to the production environment

03 Specify the current environment

One way to do this is by editing the Linux~/.bashrcfile to set environment variables:

vim /root/.bashrc
# Write: ENV_STATE=test
# Refresh after save and exit
source ~/.bashrc

If you are using the., can be set up like this:

# .
...
workflow:
  rules:
    - if: $CI_COMMIT_BRANCH == 'dev' # Test environment runner
      variables:
        DEPLOY_VARIABLE_TAG: "..."
        ENV_STATE: "test"  # Add this line to add the environment status as test
      when: always
    - if: $CI_COMMIT_BRANCH == 'main' # Production environment runner
      variables:
        DEPLOY_VARIABLE_TAG: "..."
        ENV_STATE: "pro"  # Add this line to add the environment status as pro
      when: always
    - when: never  # In addition to the above two cases never
...

deploy:
  ...
  script:
	# Add environment variable configuration to the docker run command
    - docker run ... -e ENV_STATE=$ENV_STATE ...
...

04 Load the corresponding environment variable file in the code

Where environment variables need to be loaded, use thedotenvto load environment variables.

(It is recommended to centralize the management of environment variables in a single file, and here I have created a new one specifically for this purpose)file for importing environment variables)

""""""
import os
import dotenv

# First get the current state of the environment (recorded in . ) If it is not available, the dev environment will be used by default.
env_state = ("ENV_STATE", "dev")
# Load generic environment variables first
dotenv.load_dotenv()
# Load environment variables for specific environments
# If you can't get the corresponding file in the first parameter, you need to write it as an absolute path. Use Path(__file__) to get the path.
# The second parameter, override=True, indicates that the value of a specific environment variable will be overridden when an environment variable with the same name already exists.
dotenv.load_dotenv(f".env.{env_state}", override=True)

P.S. How .env files are written to environment variables

We often use environment variables to differentiate between development and production environments in our vue projects.

vue-cliarrive at (a decision, conclusion etc) :
=='development'
vitecenter
=='development'

Sometimes we can also configure our environment variables, e.g. by adding the .env file to the root path
or. Or To distinguish between development and production environments, how do we write the environment variables we configure?

Organization of Ideas

Simply put, all we need to do is write the required environment variables under this object

  • Read the .env file in the root directory and parse it into object-parser
  • Iterate over objects and write to environment variables --writeEnv

realization

Create a new .env file in the project root directory

port=8080
url=10.10.0.0

Read file

const path = require("path");
const fs = require("fs");
function readFile (){
    const  parserPath= ((),'/.env')
    return (parserPath, "utf-8");
};

parse a file

function parse = (str){
  const obj = {};
  // prot=8080 url=10.10.0.0
  ("\n").forEach((item) => {
    if (item) {
      const [key, value] = ("=");
      obj[key] = value;
    }
  });
  return obj;
};

Write to environment variables

function writeEnv(obj) {
  (obj).forEach(function (key) {
    if (!(, key)) {
      [key] = obj[key];
    }
  });
}
writeEnv(parse(readFile())) //Execution
() 

Results Showcase

The console is shown below:

summarize

to this article on how to do multi-environment configuration in Python project is introduced to this article, more related Python project multi-environment configuration content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!