zhongrj
2025-11-25 b89962006164a462404b79a738bee8cbb6d7fe7e
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
"""
Django settings for webodm project.
 
Generated by 'django-admin startproject' using Django 1.10.
 
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
 
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
 
import os, sys, json
 
import datetime
 
import tzlocal
from django.contrib.messages import constants as messages
 
# 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/1.10/howto/deployment/checklist/
 
try:
    from .secret_key import SECRET_KEY
except ImportError:
    if os.environ.get("WO_SECRET_KEY", "") != "":
        SECRET_KEY = os.environ.get("WO_SECRET_KEY")
    else:
        # This will be executed the first time Django runs
        # It generates a secret_key.py file that contains the SECRET_KEY
        from django.utils.crypto import get_random_string
 
        current_dir = os.path.abspath(os.path.dirname(__file__))
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        secret = get_random_string(50, chars)
        with open(os.path.join(current_dir, 'secret_key.py'), 'w') as f:
            f.write("SECRET_KEY='{}'".format(secret))
        SECRET_KEY=secret
 
        print("Generated secret key")
 
with open(os.path.join(BASE_DIR, 'package.json')) as package_file:
    data = json.load(package_file)
    VERSION = data['version']
 
TESTING = sys.argv[1:2] == ['test']
FLUSHING = sys.argv[1:2] == ['flush']
MIGRATING = sys.argv[1:2] == ['migrate']
WORKER_RUNNING = sys.argv[2:3] == ["worker"]
 
# SECURITY WARNING: don't run with debug turned on a public facing server!
DEBUG = os.environ.get('WO_DEBUG', 'YES') == 'YES' or TESTING
DEV = os.environ.get('WO_DEV', 'NO') == 'YES' and not TESTING
DEV_WATCH_PLUGINS = DEV and os.environ.get('WO_DEV_WATCH_PLUGINS', 'NO') == 'YES'
SESSION_COOKIE_SECURE = CSRF_COOKIE_SECURE = os.environ.get('WO_SSL', 'NO') == 'YES'
INTERNAL_IPS = ['127.0.0.1']
 
ALLOWED_HOSTS = ['*']
 
# Branding
APP_NAME = "WebODM"
APP_DEFAULT_LOGO = os.path.join('app', 'static', 'app', 'img', 'logo512.png')
 
# In single user mode, a default admin account is created and automatically
# used so that no login windows are displayed
SINGLE_USER_MODE = False
 
# URL to redirect to if there are no processing nodes when visiting the dashboard
PROCESSING_NODES_ONBOARDING = None
 
# Enable the /api/users endpoint which is used for autocompleting
# usernames when handling project permissions. This can be disabled
# for security reasons if you don't want to let authenticated users
# retrieve the user list. 
ENABLE_USERS_API = True
 
# Enable desktop mode. In desktop mode some styling changes
# are applied to make the application look nicer on desktop
# as well as disabling certain features (e.g. sharing)
DESKTOP_MODE = False
 
# Default CSS to add to theme
DEFAULT_THEME_CSS = ''
 
# Plugins never to load
PLUGINS_BLACKLIST = [
    #'measure',
]
 
# Serve media static files URLs even in production
FORCE_MEDIA_STATICFILES = False
 
# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'django_filters',
    'guardian',
    'rest_framework',
    'rest_framework_nested',
    'drf_yasg',
    'webpack_loader',
    'corsheaders',
    'colorfield',
    'imagekit',
    'codemirror2',
    'app',
    'nodeodm',
]
 
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.locale.LocaleMiddleware',
]
 
ROOT_URLCONF = 'webodm.urls'
 
WSGI_APPLICATION = 'webodm.wsgi.application'
 
 
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
 
DATABASES = {
    'default': {
        'ENGINE': os.environ.get('WO_DATABASE_ENGINE', 'django.contrib.gis.db.backends.postgis'),
        'NAME': os.environ.get('WO_DATABASE_NAME', 'webodm_dev'),
        'USER': os.environ.get('WO_DATABASE_USER', 'postgres'),
        'PASSWORD': os.environ.get('WO_DATABASE_PASSWORD', 'postgres'),
        'HOST': os.environ.get('WO_DATABASE_HOST', 'db'),
        'PORT': os.environ.get('WO_DATABASE_PORT', '5432'),
    }
}
 
 
# Password validation
# https://docs.djangoproject.com/en/1.10/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',
   },
]
 
# Hook guardian
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', # this is default
    'guardian.backends.ObjectPermissionBackend',
    'app.auth.backends.ExternalBackend',
)
 
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
 
LANGUAGE_CODE = 'en-us'
TIME_ZONE = tzlocal.get_localzone().zone
USE_I18N = True
USE_L10N = True
USE_TZ = True
 
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale')
]
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
 
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'build', 'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'app', 'static'),
]
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
 
# File Uploads
FILE_UPLOAD_MAX_MEMORY_SIZE = 4718592 # 4.5 MB
DATA_UPLOAD_MAX_MEMORY_SIZE = 10485760 # 10 MB
DATA_UPLOAD_MAX_NUMBER_FIELDS = None
 
FILE_UPLOAD_HANDLERS = [
    'django.core.files.uploadhandler.MemoryFileUploadHandler',
    'app.uploadhandler.TemporaryFileUploadHandler', # Ours doesn't keep file descriptors open by default
]
 
# Webpack
WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'app/bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
    }
}
 
 
# Logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            # 'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'WARNING',
        },
        'app.logger': {
            'handlers': ['console'],
            'level': 'INFO',
        },
        'apscheduler.executors.default': {
            'handlers': ['console'],
            'level': 'WARNING',
        }
    }
}
 
 
# Auth
LOGIN_REDIRECT_URL = '/dashboard/'
LOGIN_URL = '/login/'
 
# CORS (very relaxed settings, users might want to change this in production)
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
SESSION_COOKIE_SAMESITE = None
 
# File uploads
MEDIA_ROOT = os.path.join(BASE_DIR, 'app', 'media')
if TESTING:
    MEDIA_ROOT = os.path.join(BASE_DIR, 'app', 'media_test')
MEDIA_TMP = os.path.join(MEDIA_ROOT, 'tmp')
 
FILE_UPLOAD_TEMP_DIR = MEDIA_TMP
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'app', 'templates'),
            os.path.join(BASE_DIR, 'app', 'templates', 'app'),
            BASE_DIR,
            MEDIA_ROOT,
        ],
        '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',
                'app.contexts.settings.load',
            ],
        },
    },
]
 
# Store flash messages in cookies
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
MESSAGE_TAGS = {
    messages.ERROR: 'danger' # Bootstrap 3 compatibility
}
 
# REST setup
# Use Django's standard django.contrib.auth permissions (no anonymous usage)
REST_FRAMEWORK = {
  'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.DjangoObjectPermissions',
  ],
  'DEFAULT_FILTER_BACKENDS': [
    'rest_framework_guardian.filters.ObjectPermissionsFilter',
    'django_filters.rest_framework.DjangoFilterBackend',
    'rest_framework.filters.OrderingFilter',
  ],
  'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    'app.api.authentication.JSONWebTokenAuthenticationQS',
  ),
  'PAGE_SIZE': 10,
  'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
}
 
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=6),
}
 
# Celery
CELERY_BROKER_URL = os.environ.get('WO_BROKER', 'redis://localhost')
CELERY_RESULT_BACKEND = os.environ.get('WO_BROKER', 'redis://localhost')
 
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_INCLUDE=['worker.tasks', 'app.plugins.worker']
CELERY_WORKER_REDIRECT_STDOUTS = False
CELERY_WORKER_HIJACK_ROOT_LOGGER = False
 
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": os.environ.get('WO_BROKER', 'redis://localhost'),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
if DEBUG and not TESTING:
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }
 
# Number of minutes a processing node hasn't been seen 
# before it should be considered offline
NODE_OFFLINE_MINUTES = 5
 
# When turned on, updates nodes information only when necessary
# and assumes that all nodes are always online, avoiding polling
NODE_OPTIMISTIC_MODE = False
 
# URL to external auth endpoint
EXTERNAL_AUTH_ENDPOINT = ''
 
# URL to a page where a user can reset the password
RESET_PASSWORD_LINK = ''
 
# Number of hours before tasks are automatically deleted
# from an account that is exceeding a disk quota
QUOTA_EXCEEDED_GRACE_PERIOD = 8
 
# Maximum number of processing nodes to show in "Processing Nodes" menus/dropdowns
UI_MAX_PROCESSING_NODES = None
 
# Number of hours before partial tasks
# are removed (or None to disable)
CLEANUP_PARTIAL_TASKS = 72
 
# Maximum number of threads that a worker should use for processing
WORKERS_MAX_THREADS = 1
 
# Link to GCP docs
GCP_DOCS_LINK = "https://docs.opendronemap.org/gcp/#gcp-file-format"
 
# Link to general docs
DOCS_LINK = "https://docs.opendronemap.org"
 
# Link to task options docs
TASK_OPTIONS_DOCS_LINK = "https://docs.opendronemap.org/arguments/"
 
if TESTING or FLUSHING:
    CELERY_TASK_ALWAYS_EAGER = True
    EXTERNAL_AUTH_ENDPOINT = 'http://0.0.0.0:5555/auth'
 
try:
    from .local_settings import *
except ImportError:
    pass
 
try:
    from .settings_override import *
except ImportError:
    pass