Distributing Django projects with unique SECRET_KEYs

前端 未结 10 953
长发绾君心
长发绾君心 2020-12-22 16:41

I have a Django project that I\'d like to distribute on a public repository like bitbucket or github. I\'d like it to be as easy to install as possible, so I\'m including t

10条回答
  •  轮回少年
    2020-12-22 17:10

    In this solution I use django-dotenv, which is one of the dependencies of my project, as listed in requirements.txt like django-dotenv==1.4.1. The advantage of this approach is you have a different .env file for each environment where the application is installed.

    Create the file utils.py in the same directory of settings.py with the following content:

    from django.utils.crypto import get_random_string
    
    def generate_secret_key(env_file_name):
        env_file = open(env_file_name, "w+")
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        generated_secret_key = get_random_string(50, chars)
        env_file.write("SECRET_KEY = '{}'\n".format(generated_secret_key))
        env_file.close()
    

    Then modify the settings.py file as follows:

    import dotenv
    from [project-folder-name] import utils
    ...
    try:
        SECRET_KEY = os.environ['SECRET_KEY']
    except KeyError:
        path_env = os.path.join(BASE_DIR, '.env')
        utils.generate_secret_key(path_env)
        dotenv.read_dotenv(path_env)
        SECRET_KEY = os.environ['SECRET_KEY']
    

    For those who don't use django-dotenv, all you have to do it to add it as a dependency and change the manage.py to load it at startup:

    import dotenv
    
    if __name__ == "__main__":
        dotenv.read_dotenv()
    

提交回复
热议问题