Get Django ALLOWED_HOSTS env. variable formated right in settings.py
Question:
I’m facing the following issue. My .env files contains a line like:
export SERVERNAMES="localhost domain1 domain2 domain3" <- exactly this kind of format
But the variable called SERVERNAMES
is used multiple times at multiple locations of my deployment so i can’t declare this as compatible list of strings that settings.py can use imidiatly. beside I don’t like to set multiple variables of .env for basically the same thing. So my question is how can I format my ALLOWED_HOSTS
to be compatible with my settings.py. Something like this does not seem to work it seems:
ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(',')
Thanks and kind regards
Answers:
Simply split your SERVERNAMES
variable using space as separator instead of comma
ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(' ')
The coma is making it a string
env = "localhost domain1 domain2 domain3"
envs = envs.split(',')
print(envs)
['localhost domain1 domain2 domain3']
Instead just split the string with space and python turns it into a list of strings
env = "localhost domain1 domain2 domain3"
envs = env.split() # By default `str.split()` splits upon spaces
print(envs)
['localhost', 'domain1', 'domain2', 'domain3']
You can also make use of the env.list command.
Put int your .env file:
ALLOWED_HOSTS=example.com,awesomedomain.com,stagingdomain.com
and in python use
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
I’m facing the following issue. My .env files contains a line like:
export SERVERNAMES="localhost domain1 domain2 domain3" <- exactly this kind of format
But the variable called SERVERNAMES
is used multiple times at multiple locations of my deployment so i can’t declare this as compatible list of strings that settings.py can use imidiatly. beside I don’t like to set multiple variables of .env for basically the same thing. So my question is how can I format my ALLOWED_HOSTS
to be compatible with my settings.py. Something like this does not seem to work it seems:
ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(',')
Thanks and kind regards
Simply split your SERVERNAMES
variable using space as separator instead of comma
ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(' ')
The coma is making it a string
env = "localhost domain1 domain2 domain3"
envs = envs.split(',')
print(envs)
['localhost domain1 domain2 domain3']
Instead just split the string with space and python turns it into a list of strings
env = "localhost domain1 domain2 domain3"
envs = env.split() # By default `str.split()` splits upon spaces
print(envs)
['localhost', 'domain1', 'domain2', 'domain3']
You can also make use of the env.list command.
Put int your .env file:
ALLOWED_HOSTS=example.com,awesomedomain.com,stagingdomain.com
and in python use
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")