I have the following dict object:
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": "cn=active,ou=groups,dc=example,dc=com",
"is_staff": "cn=staff,ou=groups,dc=example,dc=com",
"is_superuser": "cn=superuser,ou=groups,dc=example,dc=com"
}
I want to define elements of it from variables:
# Load environmental variables here
hostname = os.environ['AUTH_LDAP_SERVER']
binduser = os.environ['AUTH_LDAP_BIND_USER']
bindgroup = os.environ['AUTH_LDAP_BIND_GROUP']
dc1 = os.environ['AUTH_LDAP_BIND_DC1']
dc2 = os.environ['AUTH_LDAP_BIND_DC2']
bindpassword = os.environ['AUTH_LDAP_PASSWORD']
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": "cn=active,{bindgroup},dc={dc1),dc={dc2}",
"is_staff": "cn=staff,{bindgroup},dc={dc1},dc={dc2}",
"is_superuser": "cn=administrators,{bindgroup},dc={dc1},dc={dc2}"
}
How can I insert the variables into the dict?
All you need to do is add an f
in front of the strings you want formatted. Documentation on f-strings .
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": f"cn=active,{bindgroup},dc={dc1},dc={dc2}",
"is_staff": f"cn=staff,{bindgroup},dc={dc1},dc={dc2}",
"is_superuser": f"cn=administrators,{bindgroup},dc={dc1},dc={dc2}"
}
Also, I would use os.getenv
to avoid KeyError's.
In python 3.6+ you have f-strings .
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": f"cn=active,{bindgroup},dc={dc1},dc={dc2}",
"is_staff": f"cn=staff,{bindgroup},dc={dc1},dc={dc2}",
"is_superuser": f"cn=administrators,{bindgroup},dc={dc1},dc={dc2}"
}
If you're using python 3.5 or older you can use format
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": "cn=active,{},dc={},dc={}".format(bindgroup, dc1, dc2),
"is_staff": "cn=staff,{},dc={},dc={}".format(bindgroup, dc1, dc2),
"is_superuser": "cn=administrators,{},dc={},dc={}".format(bindgroup, dc1, dc2)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.