-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathsettings.py
331 lines (283 loc) · 9.67 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""These settings rely on various environment variables being set"""
import os
import sys
from pathlib import Path
from warnings import filterwarnings
import dj_database_url
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.huey import HueyIntegration
from sentry_sdk.integrations.logging import ignore_logger
from sentry_sdk.integrations.redis import RedisIntegration
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ["SECRET_KEY"]
ALLOWED_HOSTS = os.environ.get(
"ALLOWED_HOSTS", "[::1] 127.0.0.1 localhost 16.local"
).split()
CSRF_TRUSTED_ORIGINS = os.environ.get(
"CSRF_TRUSTED_ORIGINS",
"https://bustimes.org https://staging.bustimes.org https://bustimes-org.fly.dev",
).split()
TEST = "test" in sys.argv or "pytest" in sys.argv[0]
DEBUG = bool(os.environ.get("DEBUG", False))
SERVER_EMAIL = "[email protected]"
DEFAULT_FROM_EMAIL = "bustimes.org <[email protected]>"
EMAIL_HOST = os.environ.get("EMAIL_HOST", "")
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", "")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", "")
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_TIMEOUT = 10
if TEST:
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
INSTALLED_APPS = [
# "daphne",
"accounts",
"busstops",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.gis",
"django.contrib.sitemaps",
"django.contrib.humanize",
"bustimes",
"disruptions",
"fares",
"vehicles",
"vosa",
"email_obfuscator",
"api",
"rest_framework",
"django_filters",
"simple_history",
"huey.contrib.djhuey",
"corsheaders",
"turnstile",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"corsheaders.middleware.CorsMiddleware",
"busstops.middleware.GZipIfNotStreamingMiddleware",
"busstops.middleware.WhiteNoiseWithFallbackMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
# Stadia Maps tiles require we send at least the origin in cross-origin requests.
# For same-origin requests, the full referrer is useful (e.g. for the contact form)
SECURE_REFERRER_POLICY = "origin-when-cross-origin"
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ("HTTP_CF_VISITOR", '{"scheme":"https"}')
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_REDIRECT_EXEMPT = [r"^version$"]
CORS_ALLOW_ALL_ORIGINS = True
CORS_URLS_REGEX = r"(^\/(api\/|(vehicles|stops)\.json)|.*\/journeys\/.*)"
if DEBUG and "runserver" in sys.argv:
INSTALLED_APPS += [
"debug_toolbar",
"template_profiler_panel",
]
MIDDLEWARE += [
"debug_toolbar.middleware.DebugToolbarMiddleware",
"debug_toolbar_force.middleware.ForceDebugToolbarMiddleware",
]
INTERNAL_IPS = ["127.0.0.1"]
# DEBUG_TOOLBAR_PANELS = [
# "template_profiler_panel.panels.template.TemplateProfilerPanel",
# ]
ROOT_URLCONF = "buses.urls"
ASGI_APPLICATION = "buses.asgi.application"
DATABASES = {"default": dj_database_url.config(conn_max_age=None)}
DATABASES["default"]["OPTIONS"] = {
"application_name": os.environ.get("APPLICATION_NAME") or " ".join(sys.argv)[-63:],
"connect_timeout": 9,
}
DATABASES["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
DATABASES["default"]["TEST"] = {"SERIALIZE": False}
if DEBUG and "runserver" in sys.argv:
del DATABASES["default"][
"CONN_MAX_AGE"
] # reset to the default (i.e. no persistent connections)
TEST_RUNNER = "django_slowtests.testrunner.DiscoverSlowestTestsRunner"
NUM_SLOW_TESTS = 10
AUTH_USER_MODEL = "accounts.User"
LOGIN_REDIRECT_URL = "/vehicles"
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 100,
}
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
READ_DATABASE = "default"
# if os.environ.get("READ_ONLY_DB_HOST"):
# REPLICA_DATABASES = []
# for i, host in enumerate(os.environ["READ_ONLY_DB_HOST"].split()):
# key = f"read-only-{i}"
# DATABASES[key] = DATABASES["default"].copy()
# DATABASES[key]["HOST"] = host
# REPLICA_DATABASES.append(key)
# DATABASE_ROUTERS = ["multidb.PinningReplicaRouter"]
# MIDDLEWARE.append("busstops.middleware.pin_db_middleware")
# READ_DATABASE = key
DATA_UPLOAD_MAX_MEMORY_SIZE = None
DATA_UPLOAD_MAX_NUMBER_FIELDS = 2000
REDIS_URL = os.environ.get("REDIS_URL")
HUEY = {
"name": "bustimes",
"immediate": DEBUG or TEST,
"connection": {
"url": REDIS_URL,
},
}
STATIC_URL = "/static/"
STATIC_ROOT = os.environ.get("STATIC_ROOT", BASE_DIR / "staticfiles")
STORAGES = {
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
}
WHITENOISE_ROOT = BASE_DIR / "busstops" / "static" / "root"
WHITENOISE_MIMETYPES = {
".webmanifest": "application/manifest+json",
}
TEMPLATE_MINIFER_STRIP_FUNCTION = "buses.utils.minify"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"debug": DEBUG,
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"buses.context_processors.ad",
"vehicles.context_processors.liveries_css_version",
],
"loaders": [
(
"django.template.loaders.cached.Loader",
["template_minifier.template.loaders.app_directories.Loader"],
)
],
},
},
{
"BACKEND": "django.template.backends.jinja2.Jinja2",
"DIRS": ["busstops/templates/jinja2"],
"OPTIONS": {
"environment": "buses.jinja2.environment",
},
},
]
if DEBUG:
TEMPLATES[0]["OPTIONS"]["loaders"] = [
"django.template.loaders.app_directories.Loader"
]
elif TEST:
TEMPLATES[0]["OPTIONS"]["loaders"] = [
(
"django.template.loaders.cached.Loader",
["django.template.loaders.app_directories.Loader"],
)
]
CACHES = {}
if TEST or DEBUG:
CACHES["default"] = {"BACKEND": "django.core.cache.backends.dummy.DummyCache"}
# elif DEBUG or not REDIS_URL:
# CACHES["default"] = {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}
if REDIS_URL and not TEST:
CACHES["redis"] = {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": REDIS_URL,
"KEY_PREFIX": os.environ.get("CACHE_KEY_PREFIX", ""),
}
if "default" not in CACHES:
CACHES["default"] = CACHES["redis"]
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
TIME_ZONE = "Europe/London"
USE_TZ = True
USE_I18N = False
LANGUAGE_CODE = "en-gb"
# https://adamj.eu/tech/2023/12/07/django-fix-urlfield-assume-scheme-warnings/
filterwarnings(
"ignore", "The FORMS_URLFIELD_ASSUME_HTTPS transitional setting is deprecated."
)
FORMS_URLFIELD_ASSUME_HTTPS = True
def traces_sampler(context):
try:
url = context["wsgi_environ"]["RAW_URI"]
except KeyError:
return 0
if (
url == "/version"
or url.startswith("/vehicles.json")
or url.startswith("/stops.json")
or url.startswith("/static/")
or url.startswith("/journeys/")
):
return 0
if url.startswith("/stops/") or url.startswith("/services/"):
return 0.004
if url.startswith("/vehicles"):
return 0.0005
return 0.001
if not TEST: # pragma: nocover
if "SENTRY_DSN" in os.environ:
sentry_sdk.init(
dsn=os.environ.get("SENTRY_DSN"),
integrations=[DjangoIntegration(), RedisIntegration(), HueyIntegration()],
ignore_errors=[KeyboardInterrupt, RuntimeError],
release=os.environ.get("COMMIT_HASH")
or os.environ.get("KAMAL_CONTAINER_NAME"),
traces_sampler=traces_sampler,
)
ignore_logger("django.security.DisallowedHost")
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
"root": {
"handlers": ["console"],
"level": "INFO",
},
}
TFL = { # London
"app_id": os.environ.get("TFL_APP_ID"),
"app_key": os.environ.get("TFL_APP_KEY"),
}
TFE_OPERATORS = {
"Lothian Buses",
"Lothian Country Buses",
"East Coast Buses",
"Edinburgh Trams",
}
NTA_API_KEY = os.environ.get("NTA_API_KEY") # Ireland
ALLOW_VEHICLE_NOTES_OPERATORS = (
"NATX", # National Express
"SCLK", # Scottish Citylink
"ie-526", # Irish Citylink
"ie-1178", # Dublin Express
)
NEW_VEHICLE_WEBHOOK_URL = os.environ.get("NEW_VEHICLE_WEBHOOK_URL")
DATA_DIR = os.environ.get("DATA_DIR")
if DATA_DIR:
DATA_DIR = Path(DATA_DIR)
else:
DATA_DIR = BASE_DIR / "data"
TNDS_DIR = DATA_DIR / "TNDS"
# captchas
TURNSTILE_SITEKEY = os.environ.get("TURNSTILE_SITEKEY", "0x4AAAAAAAFWiyCqdh2c-5sy")
TURNSTILE_SECRET = os.environ.get("TURNSTILE_SECRET")
ABBREVIATE_HOURLY = False # we override this in some tests, that's all
DISABLE_REGISTRATION = os.environ.get("DISABLE_REGISTRATION", False)
DISABLE_EDITING = os.environ.get("DISABLE_EDITING", False)