2017年9月13日 星期三

[Django] Settings

 Python   Django  



Introduction


We are going to create multiple settings for different environments.


Environment

Python 3.6.2
Django 1.11.5



Implement



First, create a new folder named settings and move the settings.py to it and rename settings.py to base.py.

Also create the following files,

1.  __init__.py
2.  dev.py
3.  prod.py

 


Update the BASE_DIR

base.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))



Settings by different environment

Move these settings from base.py to both dev.py and prod.py

 SECRET_KEY = 'XXXXXXXXXXXXXXXX'
 DEBUG = True
 ALLOWED_HOSTS = []


dev.py

 from .base import *
 SECRET_KEY = 'XXXXXXXXXXXXX'
 DEBUG = True
 ALLOWED_HOSTS = ['*']



prod.py

 from .base import *

 SECRET_KEY = 'XXXXXXXXXXXXXXXX'
 DEBUG = False
 ALLOWED_HOSTS = ['localhost', '127.0.0.1']

PS. The allowed hosts must be updated when deploying to production.


Run django with different settings

Open manage.py and change the default DJANGO_SETTINGS_MODULE.

 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "venv.settings.dev")

Where venv is your virtualenv name.


Or you can change directly by the following command.

$  export DJANGO_SETTINGS_MODULE"="venv.settings.dev"


After start the application, the specified settings is used.






Github





Reference






沒有留言:

張貼留言