When implementing an application, handling environment variables is a little troublesome, isn't it?
When implementing in Python, you can use a library called pydantic to set default values, cast to int types, or set values from .env
. You can easily implement processing such as reading. In this article, I will introduce those sample codes.
By the way, pydantic is not a library that only reads environment variables, but a library that can define classes using type annotations. For example, you can cast and validate json format data to classes. If you want to read all about other features, please read the following article.
Suppose the following environment variables are set:
#bash format
export REDIS_HOST_NAME=localhost
export REDIS_PORT=6379
If you use pydantic, you can read it with the following code.
from pydantic import BaseSettings
class Settings(BaseSettings):
redis_host_name: str
redis_port: int
settings = Settings()
print(settings.redis_host_name)
# => localhost
print(settings.redis_port)
# => 6379
print(type(settings.redis_port))
# => <class 'int'>
If the environment variable is not set, or if the typecast fails, a validation error will be issued.
pydantic.error_wrappers.ValidationError: 1 validation error for Settings
redis_port
value is not a valid integer (type=type_error.integer)
During development, you can use a file format called .env
to simplify setting environment variables. This is an article on node.js, but I think this is easy to understand.
Use .env file instead of environment variables (dotenv)
First, you also need to install python-dotenv with pip install python-dotenv
orpip install pydantic [dotenv]
.
Given the following .env
file,
.env
REDIS_HOST_NAME=localhost
REDIS_PORT=6379
You can load it with code like this:
from pydantic import BaseSettings
class Settings(BaseSettings):
redis_host_name: str
redis_port: int
class Config:
env_file = '.env'
settings = Settings()
With this, I think we have introduced useful functions related to environment variables that are often used in everyday development. If you want to know more, please read the corresponding item in the official document.
Settings management - pydantic
Recommended Posts