4

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()
Jekson
  • 2,892
  • 8
  • 44
  • 79
  • What you should do is set a `.env` file with those values and push that to AWS. And remember to put it on `.gitignore` – Higor Rossato Aug 19 '19 at 15:04
  • what do you mean by "server values are not importing"? Do you use `os.environ['DEBUG']` to import it in your settings? Do you get an error? Are the values wrong? Also, how do you run your production django? gunicorn? uWSGI? Which user is defined in the gunicorn process? – dirkgroten Aug 19 '19 at 15:09
  • @HigorRossato I created `.env` file at the same folder with settings.py , added values and reboot server, but nothing – Jekson Aug 19 '19 at 15:10
  • @dirkgroten I've completed the question. I got an SECRET_KEY error. I run production using asgi server daphne – Jekson Aug 19 '19 at 15:13
  • but you haven't told us how you run django on your production server – dirkgroten Aug 19 '19 at 15:16
  • @dirkgroten wrote in the previous comment and completed the question – Jekson Aug 19 '19 at 15:20
  • Can you try `echo $SECRET_KEY` on terminal to check if env var is indeed available? – Aniket Sinha Aug 19 '19 at 15:34
  • @AniketSinha yes, returning right values – Jekson Aug 19 '19 at 15:35
  • 1
    Env variables are present but not passed to your server. I've encountered this while using apache2/wsgi server. I solved it by adding vars to `/etc/apache2/envvars`. Is there something similar in asgi? Can you show content of `asgi.py`? – Aniket Sinha Aug 19 '19 at 15:52
  • @AniketSinha the question has been updated – Jekson Aug 19 '19 at 16:20

1 Answers1

2

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())

Higor Rossato
  • 1,996
  • 1
  • 10
  • 15
  • 1
    Higor, thanks for your advice, but adding a .env file doesn't work in my case. I tried to add it to the root of the project and to the folder with manage.py and to the folder with settings.py and asgi.py. – Jekson Aug 19 '19 at 15:30
  • Why it doesn't work? Technically it should work and you placed in the correct place, in the root of your project. – Higor Rossato Aug 20 '19 at 07:26
  • Well, you have to source the `.env` file somewhere too, no? You could modify `project_setup_main` to also set the environ if it isn't already set... – DylanYoung May 05 '21 at 00:27