在django-environ中使用嵌套的dict(或json)?

chhkpiq4  于 2023-01-18  发布在  Go
关注(0)|答案(1)|浏览(118)

我有一个嵌套的dict格式,我想在一个环境中设置它。
它看起来像这样:

DEPARTMENTS_INFORMATION={
    "Pants": {
        "name": "Pants Department",
        "email": "pants@department.com",
        "ext": "x2121"
    },
    "Shirts": {
        "name": "Shirt Department",
        "email": "shirts@department.com",
        "ext": "x5151"
    },
    "Socks": {
        "name": "Sock Department",
        "email": "socks@department.com",
        "ext": " "
    }
}

我使用django-environ来实现这个目的,并尝试这样使用它:
DEPARTMENTS = env.dict("DEPARTMENTS_INFORMATION", default={})
但它给了我这个错误:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
我不知道如何使嵌套字典成为一个环境变量-任何帮助感谢!

rkue9o1l

rkue9o1l1#

您可以创建2个文件:
file.env(你必须在一行中写入dict)

DEPARTMENTS_INFORMATION={"Pants": {"name": "Pants Department","email": "pants@department.com","ext": "x2121"},"Shirts": {"name": "Shirt Department","email": "shirts@department.com","ext": "x5151"},"Socks": {"name": "Sock Department","email": "socks@department.com","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)

希望这个有用。

相关问题