momo's Blog.

Django为多个环境设置配置文件

字数统计: 1.2k阅读时长: 6 min
2021/11/05 Share

前言

在Django开发中, 每个部署环境是不一样的, 那我们如何去管理Django的配置文件呢?

新建配置文件

创建配置文件入口

在项目根目录新建 myproject/settings.py 当做我们的配置文件入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding: utf-8 -*-
import os

"""
请不要修改该文件
如果你需要对settings里的内容做修改,config/default.py 文件中 添加即可
"""


APP_ENVIRONMENT = os.environ.get('APP_ENV', 'development')
ENVIRONMENT = {
'development': 'dev',
'testing': 'stag',
'production': 'prod',
}.get(APP_ENVIRONMENT)
DJANGO_CONF_MODULE = 'config.{env}'.format(env=ENVIRONMENT)

try:
_module = __import__(DJANGO_CONF_MODULE, globals(), locals(), ['*'])
except ImportError as e:
raise ImportError("Could not import config '%s' (Is it on sys.path?): %s"
% (DJANGO_CONF_MODULE, e))

for _setting in dir(_module):
if _setting == _setting.upper():
locals()[_setting] = getattr(_module, _setting)

我们通过环境变量APP_ENV来判断我们需要的配置文件.

新建配置文件目录

新建myproject/config 目录, 并在目录下创建default.py

新建默认配置 default.py

default.py 中, 我们需要放置所有配置文件都共用的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# -*- coding: utf-8 -*-
"""
Django settings for opsbackend project.

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

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

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

import os
from datetime import timedelta

# 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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j@iaa0*r*dans#5oij09rjve(573brssgw3p=mf^r$bk78&+sp'

# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.api',
'rest_framework',
'corsheaders',
'apps.users',
'rest_framework_simplejwt.token_blacklist',
'django_filters',
'apps.hosts',
'channels',
'apps.business'
]

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'opsbackend.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'opsbackend.wsgi.application'

REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_RENDERER_CLASSES': [
'utils.http.CustomRenderer',
'rest_framework.renderers.BrowsableAPIRenderer'
],
'EXCEPTION_HANDLER': 'utils.http.custom_exception_handler'
}



# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# JWT 配置
SIMPLE_JWT = {
'ROTATE_REFRESH_TOKENS': False,
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=300),
}


# Channels
ASGI_APPLICATION = 'opsbackend.asgi.application'

新建开发环境配置dev.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# -*- coding: utf-8 -*-


# 本地开发环境
from config.default import *

RUN_MODE = 'DEVELOP'

DEBUG = True

ALLOWED_HOSTS = ['*']

# 本地开发数据库设置
# USE FOLLOWING SQL TO CREATE THE DATABASE NAMED APP_CODE
# SQL: CREATE DATABASE `framework_py` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; # noqa: E501
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
# APP本地静态资源目录

STATIC_URL = '/static/'

TEMPLATES[0]['DIRS'] += (
os.path.join(BASE_DIR, 'static', 'dist'),
)

# 设置静态路径的目录位置
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static", 'dist', "static"),
]



# 白名单, 域名请按照前段实际配置修改
CORS_ORIGIN_WHITELIST = [
'http://localhost:9528',
]
# 允许跨域使用 cookie
CORS_ALLOW_CREDENTIALS = True


# 在本地开发环境下开启跨域允许

# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:9528',
]

CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)

CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)


# 多人开发时,无法共享的本地配置可以放到新建的 local_settings.py 文件中
# 并且把 local_settings.py 加入版本管理忽略文件中
try:
from local_settings import * # noqa
except ImportError:
pass

新建测试环境配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -*- coding: utf-8 -*-


from config.default import *

DEBUG = False
ALLOWED_HOSTS = ['*']

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
# APP本地静态资源目录

STATIC_URL = '/static/'

TEMPLATES[0]['DIRS'] += (
os.path.join(BASE_DIR, 'static'),
)

# 设置静态路径的目录位置
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static", "static"),
]


# 多人开发时,无法共享的本地配置可以放到新建的 local_settings.py 文件中
# 并且把 local_settings.py 加入版本管理忽略文件中
try:
from local_settings import * # noqa
except ImportError:
pass

修改入口参数

修改开发环境下 manager.py

1
2
# 修改此行
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')

修改wsgi入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
WSGI config for opsbackend project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')

application = get_wsgi_application()

修改asgi入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# mysite/asgi.py
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()

from channels.http import AsgiHandler
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from consumer import routing



application = ProtocolTypeRouter({
"http": AsgiHandler(),
# Just HTTP for now. (We can add other protocols later.)
"websocket": AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns))
})

总结

  1. 新建config目录来区分不同环境的配置.
  2. 新建入口的配置文件, 通过环境变量来动态导入响应的配置文件功能.
  3. 修改运行入口出配置文件的导入位置.
CATALOG
  1. 1. 前言
  2. 2. 新建配置文件
    1. 2.1. 创建配置文件入口
    2. 2.2. 新建配置文件目录
      1. 2.2.1. 新建默认配置 default.py
      2. 2.2.2. 新建开发环境配置dev.py
      3. 2.2.3. 新建测试环境配置
  3. 3. 修改入口参数
    1. 3.1. 修改开发环境下 manager.py
    2. 3.2. 修改wsgi入口
    3. 3.3. 修改asgi入口
  4. 4. 总结