How to manage local vs production settings in Django?

前端 未结 22 2087
别跟我提以往
别跟我提以往 2020-11-22 15:00

What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but s

22条回答
  •  情书的邮戳
    2020-11-22 15:18

    I differentiate it in manage.py and created two separate settings file: local_settings.py and prod_settings.py.

    In manage.py I check whether the server is local server or production server. If it is a local server it would load up local_settings.py and it is a production server it would load up prod_settings.py. Basically this is how it would look like:

    #!/usr/bin/env python
    import sys
    import socket
    from django.core.management import execute_manager 
    
    ipaddress = socket.gethostbyname( socket.gethostname() )
    if ipaddress == '127.0.0.1':
        try:
            import local_settings # Assumed to be in the same directory.
            settings = local_settings
        except ImportError:
            import sys
            sys.stderr.write("Error: Can't find the file 'local_settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file local_settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
            sys.exit(1)
    else:
        try:
            import prod_settings # Assumed to be in the same directory.
            settings = prod_settings    
        except ImportError:
            import sys
            sys.stderr.write("Error: Can't find the file 'prod_settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file prod_settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
            sys.exit(1)
    
    if __name__ == "__main__":
        execute_manager(settings)
    

    I found it to be easier to separate the settings file into two separate file instead of doing lots of ifs inside the settings file.

提交回复
热议问题