Cấu hình multi settings Django

Cấu hình cho phép triển khai Django với nhiều cấu hình khác nhau

Cấu trúc cũ của project:

project/
 |-- project/
 |    |-- __init__.py
 |    |-- settings.py
 |    |-- urls.py
 |    +-- wsgi.py
 +-- manage.py

Cấu trúc multi setting django

Chỉnh sửa cấu trúc thư mục

project/
 |-- project/
 |    |-- __init__.py
 |    |-- settings/         <--
 |    |    |-- __init__.py  <-- Khởi tạo thư mục
 |    |    +-- base.py      <-- Khởi tại file base settings
 |    |-- urls.py
 |    +-- wsgi.py
 +-- manage.py
  • base.py: Cung cấp các setting thông thường cho tất cả môi trường

Thêm mới các env

Các file setting thông dụng - development.py - production.py - staging.py

project/
 |-- project/
 |    |-- __init__.py
 |    |-- settings/
 |    |    |-- __init__.py
 |    |    |-- base.py
 |    |    |-- development.py
 |    |    |-- production.py
 |    |    +-- staging.py
 |    |-- urls.py
 |    +-- wsgi.py
 +-- manage.py

Tổ chức cấu hình

settings/base.py

"""
Django settings for project project.

Generated by 'django-admin startproject' using Django 2.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8%f@_cwa_w_ol_b5g7y44-=hc@76he@jzb^1)^^ahv%v4#3jj0'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [    
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'authen.apps.AuthenConfig',
]

.....

STATIC_URL = '/static/'

AUTH_USER_MODEL = 'authen.User'

settings/development.py

from .base import *

DEBUG = True

INSTALLED_APPS += [
    'debug_toolbar',
]

MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ]

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

DEBUG_TOOLBAR_CONFIG = {
    'JQUERY_URL': '',
}

settings/development.py

from .base import *

DEBUG = False

ALLOWED_HOSTS = ['mysite.com', ]

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mailgun.org'
EMAIL_PORT = 587
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
EMAIL_USE_TLS = True

Chạy project lựa chọn env

python manage.py runserver --settings=mysite.settings.development

python manage.py migrate --settings=mysite.settings.production

Chạy manager.py mặc định

Với yêu cầu chạy env theo dạng:

python manage.py migrate
python manage.py runserver

Truy cập manage.py

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') # <-- Change here!
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

Sửa lại

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.production') # <-- Change here!
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

Xử lý bài toán mỗi env có sự khác biệt về venv python

Tách file requirements.txt thành thư mục, khi sử dụng env nào pip install lại venv tương tự

└── requirements
    ├── base.txt
    ├── local.txt
    ├── production.txt
    └── test.txt

Debug in vscode

{
    "name": "Python: Django Production",
    "type": "python",
    "request": "launch",
    "pythonPath": "${workspaceFolder}/src/env/bin/python",
    "program": "${workspaceFolder}/src/project/manage.py",
    "console": "integratedTerminal",
    "args": [
        "runserver",
        "--noreload",
        "--nothreading",
        "--settings=project.settings.production"
    ],
    "django": true
},
{
    "name": "Python: Django Test",
    "type": "python",
    "request": "launch",
    "pythonPath": "${workspaceFolder}/src/env/bin/python",
    "program": "${workspaceFolder}/src/project/manage.py",
    "console": "integratedTerminal",
    "args": [
        "runserver",
        "--noreload",
        "--nothreading",
        "--settings=project.settings.testing"
    ],
    "django": true
},

Nguồn

https://blog.apptension.com/2017/11/09/django-settings-for-multiple-environments/

https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html

https://medium.com/@ayarshabeer/django-best-practice-settings-file-for-multiple-environments-6d71c6966ee2