summaryrefslogtreecommitdiff
path: root/example_project/settings.py
blob: b288992a450eb3e72592abf1537aace9ac3a0e18 (plain)
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Django settings for ishtar project.

import os
import sys
from importlib import import_module
from ishtar_common.version import get_version

try:
    import sentry_sdk
    from sentry_sdk.integrations.celery import CeleryIntegration
    from sentry_sdk.integrations.django import DjangoIntegration
except ImportError:
    sentry_sdk = None

DEBUG = False
DEBUG_TOOLBAR = False
DEBUG_TO_CONSOLE = False
SQL_DEBUG = False
DJANGO_EXTENSIONS = False
TEST_VIEWS = True

if "test" in sys.argv:
    sys.path.insert(0, "..")

IMAGE_MAX_SIZE = (1280, 960)  # put None if no resizing
THUMB_MAX_SIZE = (600, 600)

# DISABLE_TASK_TIMEOUT = False  # problematic for now
DISABLE_TASK_TIMEOUT = True
CACHE_TASK_TIMEOUT = 4
CACHE_SMALLTIMEOUT = 60
CACHE_TIMEOUT = 3600
CACHE_BACKEND = "memcached://127.0.0.1:11211/"

SEP = os.path.sep
ROOT_PATH = SEP.join(os.path.abspath(__file__).split(SEP)[:-1]) + SEP
STATIC_URL = "/static/"
STATIC_ROOT = ROOT_PATH + "static/"
BASE_URL = "/"
URL_PATH = ""
EXTRA_VERSION = "git"

LOCALE_PATHS = [os.path.abspath(os.path.join(ROOT_PATH, "..", "locale"))]

STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "compressor.finders.CompressorFinder",
)

BS_STATIC = ROOT_PATH + "../bootstrap_datepicker/static"
if not os.path.exists(BS_STATIC):
    BS_STATIC = "/usr/lib/python3/dist-packages/bootstrap_datepicker/static"

STATICFILES_DIRS = (BS_STATIC,)

ODT_TEMPLATE = ROOT_PATH + "../ishtar_common/static/template.odt"

LOGIN_REDIRECT_URL = "/" + URL_PATH

ACCOUNT_ACTIVATION_DAYS = 7

# change this in local_settings
DATABASES = {
    "default": {
        "ENGINE": "django.contrib.gis.db.backends.postgis",
        "NAME": "ishtar",
        "USER": "ishtar",
        "PASSWORD": "ishtar",
        "HOST": "127.0.0.1",
        "PORT": "5432",
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "Europe/Paris"

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "fr-fr"

COUNTRY = "fr"

OOOK_DATE_FORMAT = "%-d %B %Y"
OOO_DATE_FORMAT = "%-d %B %Y"
DATE_FORMAT = "%-d %B %Y"

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
LANGUAGES = (
    ("fr", "Français"),
    ("en", "English"),
)
DEFAULT_LANGUAGE = 1

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ROOT_PATH + "media/"

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = "/media/"

MIDDLEWARE = [
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.locale.LocaleMiddleware",
]

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(ROOT_PATH, "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "ishtar_common.context_processors.get_base_context",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.csrf",
            ],
        },
    },
]


ROOT_URLCONF = "example_project.urls"

AUTHENTICATION_BACKENDS = ("ishtar_common.backend.ObjectPermBackend",)

INSTALLED_APPS = [
    "registration",
    "ishtar_common",
    "archaeological_files_pdl",
    "archaeological_files",
    "archaeological_operations",
    "archaeological_context_records",
    "archaeological_warehouse",
    "archaeological_finds",
    "ajax_select",
    "compressor",
    "rest_framework",
    "rest_framework.authtoken",
    "django.contrib.auth",
    "django.contrib.admin",
    "django.contrib.contenttypes",
    "django.contrib.postgres",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.gis",
    "django.contrib.staticfiles",
    "django.contrib.messages",
    "django.contrib.humanize",
    # 'debug_toolbar',
]

USE_TRANSLATION_OVERLOAD = True
TRANSLATION_OVERLOAD_DEBUG = False

MAIN_APP = ""

LOGFILE = ""

default_handler = {"handlers": ["logfile"], "level": "INFO", "propogate": False}

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        # Include the default Django email handler for errors
        # This is what you'd get without configuring logging at all.
        "mail_admins": {
            "class": "django.utils.log.AdminEmailHandler",
            "level": "ERROR",
            # But the emails are plain text by default - HTML is nicer
            "include_html": True,
        },
        # Log to a text file that can be rotated by logrotate
        "logfile": {
            "class": "logging.handlers.WatchedFileHandler",
            "filename": "/var/log/django/ishtar.log",
        },
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
        },
    },
    "loggers": {
        "django.request": {
            "handlers": ["mail_admins", "logfile"],
            "level": "ERROR",
            "propagate": True,
        },
        "django": {
            "handlers": ["logfile"],
            "level": "ERROR",
            "propagate": False,
        },
        "django.server": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
        "django.security.DisallowedHost": {
            "handlers": ["logfile"],
            "propagate": False,
        },
        "ishtar_pdl": default_handler,
        "ishtar_common": default_handler,
        "archaeological_files_pdl": default_handler,
        "archaeological_files": default_handler,
        "archaeological_operations": default_handler,
        "archaeological_context_records": default_handler,
        "archaeological_warehouse": default_handler,
        "archaeological_finds": default_handler,
    },
}

USE_BACKGROUND_TASK = False
USE_LIBREOFFICE = False
LIBREOFFICE_PORT = 8101
LIBREOFFICE_HOST = "localhost"

# Ishtar custom

ISHTAR_MAP_MAX_ITEMS = 50000
ISHTAR_QRCODE_VERSION = 6  # density of the QR code
ISHTAR_QRCODE_SCALE = 2  # scale of the QR code
ISHTAR_DEFAULT_YEAR = 1900

ISHTAR_SLUGS = {
    "document-publisher": ["publisher"],
}

SRID = 4326  # WGS84 - World
SURFACE_SRID = 4326  # WGS84 - World
ENCODING = "windows-1252"
ALT_ENCODING = "ISO-8859-15"
APP_NAME = "SRA - Pays de la Loire"
SURFACE_UNIT = "square-metre"
SURFACE_UNIT_LABEL = "m²"
JOINT = " | "
# dir for ishtar maintenance script - as it can be a serious security issue if
# not managed cautiously the dir contening these scripts is not set by default
ISHTAR_SCRIPT_DIR = ""

ISHTAR_FILE_PREFIX = ""
ISHTAR_OPE_PREFIX = "OA"
ISHTAR_DEF_OPE_PREFIX = "OP"
# string len of find indexes - i.e: find with index 42 will be 00042
ISHTAR_FINDS_INDEX_ZERO_LEN = 5
ISHTAR_OPE_COL_FORMAT = None
# DB key: (txt_idx, label)
ISHTAR_OPE_TYPES = {}
# DB key: txt_idx
ISHTAR_PERIODS = {}
ISHTAR_PERMIT_TYPES = {}
ISHTAR_DOC_TYPES = {"undefined": "Undefined"}

ISHTAR_SEARCH_LANGUAGE = "french"

ISHTAR_SECURE = True

ISHTAR_DPTS = []

MAX_ATTEMPTS = 1  # django background tasks

MAX_UPLOAD_SIZE = 100  # in Mo

# path to the "dot" program to generate graph
DOT_BINARY = "/usr/bin/dot"

TEST_RUNNER = "ishtar_common.tests.ManagedModelTestRunner"
CELERY_BROKER_URL = ""
SENTRY_ID = None

try:
    from custom_settings import *
except ImportError:
    pass

try:
    from local_settings import *
except ImportError as e:
    try:
        from .local_settings import *
    except ImportError as e:
        print("Unable to load local_settings.py:", e)

if USE_TRANSLATION_OVERLOAD:
    INSTALLED_APPS.insert(0, "overload_translation")

if "SECRET_KEY" not in globals():  # explicit import from the root for celery
    current_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_path).split(os.sep)[-1]
    my_module = import_module(current_dir_path + ".local_settings")
    module_dict = my_module.__dict__
    try:
        to_import = my_module.__all__
    except AttributeError:
        to_import = [name for name in module_dict if not name.startswith("_")]
    globals().update({name: module_dict[name] for name in to_import})

if LANGUAGE_CODE == "fr-fr" and SRID == 4326:
    SRID = 27572  # Lambert zone II - France
    SURFACE_SRID = 2154  # Lambert 93 - France

TABLE_COLS = {}  # allow to overload table col settings on extra module
COL_LABELS = {}

if MAIN_APP:
    INSTALLED_APPS.insert(INSTALLED_APPS.index("ishtar_common"), MAIN_APP)
    extra_module = import_module(MAIN_APP + ".extra_settings")
    if hasattr(extra_module, "TABLE_COLS"):
        TABLE_COLS = extra_module.TABLE_COLS
    if hasattr(extra_module, "COL_LABELS"):
        COL_LABELS = extra_module.COL_LABELS

TESTING = sys.argv[1:2] == ["test"]

PROJECT_SLUG = locals().get("PROJECT_SLUG", "default")

if LOGFILE:
    LOGGING["handlers"]["logfile"]["filename"] = LOGFILE
elif DEBUG:
    LOGGING["handlers"]["logfile"]["filename"] = (
            ROOT_PATH + "log-" + PROJECT_SLUG + ".log"
    )
else:
    LOGGING["handlers"]["logfile"]["filename"] = (
        "/var/log/django/ishtar-" + PROJECT_SLUG + ".log"
    )

INTERNAL_IPS = ("127.0.0.1",)

JQUERY_URL = STATIC_URL + "js/jquery.min.js"
JQUERY_UI_URL = STATIC_URL + "js/jquery-ui/"

if DEBUG:
    # make all loggers use the console
    for logger in LOGGING["loggers"]:
        if DEBUG_TO_CONSOLE:
            LOGGING["loggers"][logger]["handlers"] = ["console"]
        elif "console" not in LOGGING["loggers"][logger]["handlers"]:
            LOGGING["loggers"][logger]["handlers"] += ["console"]

if USE_BACKGROUND_TASK:
    if not CELERY_BROKER_URL:
        CELERY_BROKER_URL = "amqp://localhost"

if DJANGO_EXTENSIONS:
    INSTALLED_APPS.append("django_extensions")

if DEBUG_TOOLBAR:
    if ".." not in sys.path:
        sys.path.insert(0, "..")
    global DEBUG_TOOLBAR_PANELS
    global DEBUG_TOOLBAR_CONFIG
    MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
    INSTALLED_APPS += ["debug_toolbar"]
    DEBUG_TOOLBAR_PANELS = (
        "debug_toolbar.panels.versions.VersionsPanel",
        "debug_toolbar.panels.timer.TimerPanel",
        "debug_toolbar.panels.settings.SettingsPanel",
        "debug_toolbar.panels.headers.HeadersPanel",
        "debug_toolbar.panels.request.RequestPanel",
        "debug_toolbar.panels.sql.SQLPanel",
        "debug_toolbar.panels.staticfiles.StaticFilesPanel",
        "debug_toolbar.panels.templates.TemplatesPanel",
        "debug_toolbar.panels.cache.CachePanel",
        "debug_toolbar.panels.signals.SignalsPanel",
        "debug_toolbar.panels.logging.LoggingPanel",
        "debug_toolbar.panels.redirects.RedirectsPanel",
    )
    DEBUG_TOOLBAR_CONFIG = {"INTERCEPT_REDIRECTS": False}


if SQL_DEBUG:
    LOGGING["loggers"]["django.db.backends"] = {
        "level": "DEBUG",
        "handlers": ["console"],
    }

if "test" in sys.argv:
    PROJECT_SLUG += "-test"

if not DEBUG:
    # persistent connection
    DATABASES["default"]["CONN_MAX_AGE"] = 600


def filter_irrelevant_errors(event, hint):
    if event.get("logger", None) == "django.security.DisallowedHost":
        return None
    return event


if SENTRY_ID and sentry_sdk:
    sentry_integrations = [DjangoIntegration()]
    if USE_BACKGROUND_TASK:
        sentry_integrations.append(CeleryIntegration())
    sentry_sdk.init(
        dsn=SENTRY_ID,
        integrations=sentry_integrations,
        before_send=filter_irrelevant_errors,
        send_default_pii=True,
        release=get_version() + "-" + EXTRA_VERSION
    )