I set the django project settings and added values to environment variables at my local ubuntu mashine and AWS Ubuntu server using .bashrc file at the root folder.
...
export DEBUG="True"
...
settings.py
...
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = os.environ.get('DEBUG', False)
...
At local all working good, but at production server values are not importing. Why doesn't it work on both machines? How do I set up production?
Im running production server using asgi server daphne, accordingly this tutorial
upd
asgi.py
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
application = get_default_application()
So, what I usually do is: I have a script which runs when Django is setup and creates a .env file with some values.
project_setup.py
import os
import random
import string
def write_dot_env_file(env_file):
settings = get_settings()
with open(env_file, 'w') as f:
for k, v in settings.items():
f.write(f'{k.upper()}={v}\n')
def get_settings():
return {
'SECRET_KEY': generate_secret_key(),
'DEBUG': True,
'ALLOWED_HOSTS': '*',
}
def generate_secret_key():
specials = '!@#$%^&*(-_=+)'
chars = string.ascii_lowercase + string.digits + specials
return ''.join(random.choice(chars) for _ in range(50))
def main():
env_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
if not os.path.isfile(env_file):
write_dot_env_file(env_file)
else:
pass
if __name__ == '__main__':
main()
Then on my manage.py and wsgi.py just before Django setting the path of the settings you do:
manage.py
#!/usr/bin/env python
import os
import sys
from project_setup import main as project_setup_main
if __name__ == '__main__':
project_setup_main()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yoursettings')
...
And that's it. When Django runs it'll create a .env file for you with the minimum requirements. Or you can just create the function generate_secret_key inside your settings.py and use it as a default for your SECRET_KEY declaration, like: SECRET_KEY = os.environ.get('SECRET_KEY', get_secret_key())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With