-
Notifications
You must be signed in to change notification settings - Fork 2
/
settings.py
230 lines (187 loc) · 7.09 KB
/
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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""
Django settings for project hello_visitor.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
import logging
from pathlib import Path
from pydantic import (
BaseSettings,
PostgresDsn,
EmailStr,
HttpUrl,
)
import dj_database_url
logger = logging.getLogger(__name__)
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# 12-factor-app best practice: all logging goes to the console
# https://12factor.net/
# https://docs.djangoproject.com/en/3.2/topics/logging/#examples
LOGGING_CONFIG = None
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {"format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"}
},
"handlers": {
"console": {
"level": "WARNING",
"class": "logging.StreamHandler",
"formatter": "console",
},
},
"root": {
"handlers": ["console"],
"level": "WARNING",
},
}
import logging.config # pylint: disable=ungrouped-imports, wrong-import-position, wrong-import-order
logging.config.dictConfig(LOGGING)
# 12-factor-app best practice: all configuration is stored in the environment
#
# Use pydantic with run-time type coercion & validation
# https://pydantic-docs.helpmanual.io/usage/settings
class SettingsFromEnvironment(BaseSettings):
"""Defines environment variables with their types and optional defaults"""
# postgresql
DATABASE_URL: PostgresDsn
DATABASE_SSL: bool = True
# Django settings
SECRET_KEY: str
DEBUG: bool = False
DEBUG_TEMPLATES: bool = False
USE_SSL: bool = False
ALLOWED_HOSTS: list
class Config: # pylint: disable=too-few-public-methods
"""Defines configuration for pydantic environment loading"""
env_file = str(BASE_DIR / ".env")
case_sensitive = True
config = SettingsFromEnvironment()
os.environ["DATABASE_URL"] = config.DATABASE_URL
DATABASES = {
"default": dj_database_url.config(conn_max_age=600, ssl_require=config.DATABASE_SSL)
}
SECRET_KEY = config.SECRET_KEY
DEBUG = config.DEBUG
DEBUG_TEMPLATES = config.DEBUG_TEMPLATES
USE_SSL = config.USE_SSL
ALLOWED_HOSTS = config.ALLOWED_HOSTS
if not USE_SSL:
SECURE_PROXY_SSL_HEADER = None
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
else:
# IMPORTANT: ONLY APPLY THESE ON THE SERVER !
#
# (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your
# site should be available over both SSL and non-SSL connections, you
# may want to either set this setting True or configure a load balancer
# or reverse-proxy server to redirect all connections to HTTPS.
# https://help.heroku.com/J2R1S4T8/can-heroku-force-an-application-to-use-ssl-tls
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = True
# (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only session
# cookie makes it more difficult for network traffic sniffers to hijack
# user sessions.
SESSION_COOKIE_SECURE = True
# (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your
# MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. Using a
# secure-only CSRF cookie makes it more difficult for network traffic
# sniffers to steal the CSRF token.
CSRF_COOKIE_SECURE = True
# IMPORTANT:
# (-) Add these only once the HTTPS redirect is confirmed to work
#
# (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your
# entire site is served only over SSL, you may want to consider setting
# a value and enabling HTTP Strict Transport Security. Be sure to read
# the documentation first; enabling HSTS carelessly can cause serious,
# irreversible problems.
SECURE_HSTS_SECONDS = 2592000 # 1 month
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
# Application definition
INSTALLED_APPS = [
"homepage.apps.HomepageConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"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 = "hello_visitor.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"debug": True,
"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 = "hello_visitor.wsgi.application"
# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
#
# location where you will store your static files
STATICFILES_DIRS = [BASE_DIR / "static"]
# location where django collects all static files
# add this to .gitignore (!)
STATIC_ROOT = BASE_DIR / "staticfiles"
STATIC_ROOT.mkdir(exist_ok=True)
# URL to use when referring to static files located in STATIC_ROOT.
STATIC_URL = "/static/"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"