settings.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. __package__ = 'archivebox.core'
  2. import os
  3. import sys
  4. import re
  5. import logging
  6. from pathlib import Path
  7. from datetime import datetime
  8. from django.utils.crypto import get_random_string
  9. from ..config import ( # noqa: F401
  10. DEBUG,
  11. IS_TTY,
  12. VERSION,
  13. IN_DOCKER,
  14. SECRET_KEY,
  15. ALLOWED_HOSTS,
  16. PACKAGE_DIR,
  17. TEMPLATES_DIR_NAME,
  18. SQL_INDEX_FILENAME,
  19. OUTPUT_DIR,
  20. LOGS_DIR,
  21. )
  22. IS_MIGRATING = 'makemigrations' in sys.argv[:3] or 'migrate' in sys.argv[:3]
  23. IS_TESTING = 'test' in sys.argv[:3] or 'PYTEST_CURRENT_TEST' in os.environ
  24. IS_SHELL = 'shell' in sys.argv[:3] or 'shell_plus' in sys.argv[:3]
  25. ################################################################################
  26. ### Django Core Settings
  27. ################################################################################
  28. WSGI_APPLICATION = 'core.wsgi.application'
  29. ROOT_URLCONF = 'core.urls'
  30. LOGIN_URL = '/accounts/login/'
  31. LOGOUT_REDIRECT_URL = '/'
  32. PASSWORD_RESET_URL = '/accounts/password_reset/'
  33. APPEND_SLASH = True
  34. DEBUG = True # DEBUG or ('--debug' in sys.argv)
  35. DEBUG_TOOLBAR = True
  36. INSTALLED_APPS = [
  37. 'django.contrib.auth',
  38. 'django.contrib.contenttypes',
  39. 'django.contrib.sessions',
  40. 'django.contrib.messages',
  41. 'django.contrib.staticfiles',
  42. 'django.contrib.admin',
  43. 'core',
  44. 'django_extensions',
  45. ]
  46. if DEBUG_TOOLBAR:
  47. INSTALLED_APPS = [*INSTALLED_APPS, 'debug_toolbar']
  48. INTERNAL_IPS = ['0.0.0.0', '127.0.0.1', '*']
  49. DEBUG_TOOLBAR_CONFIG = {
  50. "SHOW_TOOLBAR_CALLBACK": lambda request: True,
  51. "RENDER_PANELS": True,
  52. }
  53. DEBUG_TOOLBAR_PANELS = [
  54. 'debug_toolbar.panels.history.HistoryPanel',
  55. 'debug_toolbar.panels.versions.VersionsPanel',
  56. 'debug_toolbar.panels.timer.TimerPanel',
  57. 'debug_toolbar.panels.settings.SettingsPanel',
  58. 'debug_toolbar.panels.headers.HeadersPanel',
  59. 'debug_toolbar.panels.request.RequestPanel',
  60. 'debug_toolbar.panels.sql.SQLPanel',
  61. 'debug_toolbar.panels.staticfiles.StaticFilesPanel',
  62. # 'debug_toolbar.panels.templates.TemplatesPanel',
  63. 'debug_toolbar.panels.cache.CachePanel',
  64. 'debug_toolbar.panels.signals.SignalsPanel',
  65. 'debug_toolbar.panels.logging.LoggingPanel',
  66. 'debug_toolbar.panels.redirects.RedirectsPanel',
  67. 'debug_toolbar.panels.profiling.ProfilingPanel',
  68. 'djdt_flamegraph.FlamegraphPanel',
  69. ]
  70. MIDDLEWARE = [
  71. 'django.middleware.security.SecurityMiddleware',
  72. 'django.contrib.sessions.middleware.SessionMiddleware',
  73. 'django.middleware.common.CommonMiddleware',
  74. 'django.middleware.csrf.CsrfViewMiddleware',
  75. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  76. 'django.contrib.messages.middleware.MessageMiddleware',
  77. ]
  78. if DEBUG_TOOLBAR:
  79. MIDDLEWARE = [*MIDDLEWARE, 'debug_toolbar.middleware.DebugToolbarMiddleware']
  80. AUTHENTICATION_BACKENDS = [
  81. 'django.contrib.auth.backends.ModelBackend',
  82. ]
  83. ################################################################################
  84. ### Staticfile and Template Settings
  85. ################################################################################
  86. STATIC_URL = '/static/'
  87. STATICFILES_DIRS = [
  88. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME / 'static'),
  89. ]
  90. TEMPLATE_DIRS = [
  91. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME / 'core'),
  92. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME / 'admin'),
  93. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME),
  94. ]
  95. TEMPLATES = [
  96. {
  97. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  98. 'DIRS': TEMPLATE_DIRS,
  99. 'APP_DIRS': True,
  100. 'OPTIONS': {
  101. 'context_processors': [
  102. 'django.template.context_processors.debug',
  103. 'django.template.context_processors.request',
  104. 'django.contrib.auth.context_processors.auth',
  105. 'django.contrib.messages.context_processors.messages',
  106. ],
  107. },
  108. },
  109. ]
  110. ################################################################################
  111. ### External Service Settings
  112. ################################################################################
  113. DATABASE_FILE = Path(OUTPUT_DIR) / SQL_INDEX_FILENAME
  114. DATABASE_NAME = os.environ.get("ARCHIVEBOX_DATABASE_NAME", str(DATABASE_FILE))
  115. DATABASES = {
  116. 'default': {
  117. 'ENGINE': 'django.db.backends.sqlite3',
  118. 'NAME': DATABASE_NAME,
  119. # DB setup is sometimes modified at runtime by setup_django() in config.py
  120. }
  121. }
  122. # CACHES = {
  123. # 'default': {
  124. # 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
  125. # 'LOCATION': 'cache_default',
  126. # }
  127. # }
  128. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
  129. ################################################################################
  130. ### Security Settings
  131. ################################################################################
  132. SECRET_KEY = SECRET_KEY or get_random_string(50, 'abcdefghijklmnopqrstuvwxyz0123456789_')
  133. ALLOWED_HOSTS = ALLOWED_HOSTS.split(',')
  134. SECURE_BROWSER_XSS_FILTER = True
  135. SECURE_CONTENT_TYPE_NOSNIFF = True
  136. CSRF_COOKIE_SECURE = False
  137. SESSION_COOKIE_SECURE = False
  138. SESSION_COOKIE_DOMAIN = None
  139. SESSION_COOKIE_AGE = 1209600 # 2 weeks
  140. SESSION_EXPIRE_AT_BROWSER_CLOSE = False
  141. SESSION_SAVE_EVERY_REQUEST = True
  142. SESSION_ENGINE = "django.contrib.sessions.backends.db"
  143. AUTH_PASSWORD_VALIDATORS = [
  144. {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
  145. {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
  146. {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
  147. {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
  148. ]
  149. ################################################################################
  150. ### Shell Settings
  151. ################################################################################
  152. SHELL_PLUS = 'ipython'
  153. SHELL_PLUS_PRINT_SQL = False
  154. IPYTHON_ARGUMENTS = ['--no-confirm-exit', '--no-banner']
  155. IPYTHON_KERNEL_DISPLAY_NAME = 'ArchiveBox Django Shell'
  156. if IS_SHELL:
  157. os.environ['PYTHONSTARTUP'] = str(Path(PACKAGE_DIR) / 'core' / 'welcome_message.py')
  158. ################################################################################
  159. ### Internationalization & Localization Settings
  160. ################################################################################
  161. LANGUAGE_CODE = 'en-us'
  162. TIME_ZONE = 'UTC'
  163. USE_I18N = False
  164. USE_L10N = False
  165. USE_TZ = False
  166. DATETIME_FORMAT = 'Y-m-d g:iA'
  167. SHORT_DATETIME_FORMAT = 'Y-m-d h:iA'
  168. ################################################################################
  169. ### Logging Settings
  170. ################################################################################
  171. IGNORABLE_404_URLS = [
  172. re.compile(r'apple-touch-icon.*\.png$'),
  173. re.compile(r'favicon\.ico$'),
  174. re.compile(r'robots\.txt$'),
  175. re.compile(r'.*\.(css|js)\.map$'),
  176. ]
  177. class NoisyRequestsFilter(logging.Filter):
  178. def filter(self, record):
  179. logline = record.getMessage()
  180. # ignore harmless 404s for the patterns in IGNORABLE_404_URLS
  181. for ignorable_url_pattern in IGNORABLE_404_URLS:
  182. ignorable_log_pattern = re.compile(f'^"GET /.*/?{ignorable_url_pattern.pattern[:-1]} HTTP/.*" (200|30.|404) .+$', re.I | re.M)
  183. if ignorable_log_pattern.match(logline):
  184. return 0
  185. # ignore staticfile requests that 200 or 30*
  186. ignoreable_200_log_pattern = re.compile(r'"GET /static/.* HTTP/.*" (200|30.) .+', re.I | re.M)
  187. if ignoreable_200_log_pattern.match(logline):
  188. return 0
  189. return 1
  190. ERROR_LOG = (LOGS_DIR / 'errors.log') if LOGS_DIR.exists() else '/dev/null'
  191. LOGGING = {
  192. 'version': 1,
  193. 'disable_existing_loggers': False,
  194. 'handlers': {
  195. 'console': {
  196. 'class': 'logging.StreamHandler',
  197. },
  198. 'logfile': {
  199. 'level': 'ERROR',
  200. 'class': 'logging.handlers.RotatingFileHandler',
  201. 'filename': ERROR_LOG,
  202. 'maxBytes': 1024 * 1024 * 25, # 25 MB
  203. 'backupCount': 10,
  204. },
  205. },
  206. 'filters': {
  207. 'noisyrequestsfilter': {
  208. '()': NoisyRequestsFilter,
  209. }
  210. },
  211. 'loggers': {
  212. 'django': {
  213. 'handlers': ['console', 'logfile'],
  214. 'level': 'INFO',
  215. 'filters': ['noisyrequestsfilter'],
  216. },
  217. 'django.server': {
  218. 'handlers': ['console', 'logfile'],
  219. 'level': 'INFO',
  220. 'filters': ['noisyrequestsfilter'],
  221. }
  222. },
  223. }