Distributing Django projects with unique SECRET_KEYs

前端 未结 10 948
长发绾君心
长发绾君心 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:12

    Carles Barrobés made an excellent answer but it is incomplete, here is my version for python 3 with the missing function to work.

    from django.core.management.utils import get_random_secret_key
    
    def generate_secret_key (filepath):
        secret_file = open(filepath, "w")
        secret = "SECRET_KEY= " + "\""+ get_random_secret_key() + "\"" + "\n"
        secret_file.write(secret)
        secret_file.close()
    
    try:
        from .secret_key import SECRET_KEY
    except ModuleNotFoundError:
    
        SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
        generate_secret_key(os.path.join(SETTINGS_DIR, 'secret_key.py'))
        from .secret_key import SECRET_KEY
    

    Take notice that I changed the ImportError for ModuleNotFoundError and creates the python file secret_key.py to gather the SECRET_KEY like a variable instead to parse a txt file.

提交回复
热议问题