Use a nested dict (or json) with django-environ?

Question:

I’ve got a nested dict format that I wanted to setup in an environment.

It looks like this:

DEPARTMENTS_INFORMATION={
    "Pants": {
        "name": "Pants Department",
        "email": "[email protected]",
        "ext": "x2121"
    },
    "Shirts": {
        "name": "Shirt Department",
        "email": "[email protected]",
        "ext": "x5151"
    },
    "Socks": {
        "name": "Sock Department",
        "email": "[email protected]",
        "ext": " "
    }
}

I am using django-environ for this and tried using it like this:

DEPARTMENTS = env.dict("DEPARTMENTS_INFORMATION", default={})

But it’s giving me this error:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

I’m not sure how to make the nested dictionary an environment variable – any help appreciated!

Asked By: UpDawg

||

Answers:

You can create 2 files:

file.env (you have to write the dict in one line)

DEPARTMENTS_INFORMATION={"Pants": {"name": "Pants Department","email": "[email protected]","ext": "x2121"},"Shirts": {"name": "Shirt Department","email": "[email protected]","ext": "x5151"},"Socks": {"name": "Sock Department","email": "[email protected]","ext": " "}}

main.py

import environ

#start the environ
env = environ.Env()

#load the env file
environ.Env.read_env("file.env")

#read the data
data = env.json("DEPARTMENTS_INFORMATION")

print(data)

Hope this helps.

Answered By: marick