settings.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import os
  2. import sys
  3. from pathlib import Path
  4. import dj_database_url
  5. from django.utils.translation import gettext_lazy as _
  6. from dotenv import load_dotenv
  7. PROJECT_ROOT = Path(__file__).resolve().parent
  8. BASE_DIR = Path(__file__).resolve().parent.parent
  9. sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
  10. # Tap vrobbler.conf if it's available
  11. if os.path.exists("vrobbler.conf"):
  12. load_dotenv("vrobbler.conf")
  13. elif os.path.exists("/etc/vrobbler.conf"):
  14. load_dotenv("/etc/vrobbler.conf")
  15. elif os.path.exists("/usr/local/etc/vrobbler.conf"):
  16. load_dotenv("/usr/local/etc/vrobbler.conf")
  17. # Build paths inside the project like this: BASE_DIR / 'subdir'.
  18. # Quick-start development settings - unsuitable for production
  19. # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
  20. # SECURITY WARNING: keep the secret key used in production secret!
  21. SECRET_KEY = os.getenv("VROBBLER_SECRET_KEY", "not-a-secret-234lkjasdflj132")
  22. # SECURITY WARNING: don't run with debug turned on in production!
  23. DEBUG = os.getenv("VROBBLER_DEBUG", False)
  24. TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"
  25. KEEP_DETAILED_SCROBBLE_LOGS = os.getenv(
  26. "VROBBLER_KEEP_DETAILED_SCROBBLE_LOGS", False
  27. )
  28. # Should we cull old in-progress scrobbles that are beyond the wait period for resuming?
  29. DELETE_STALE_SCROBBLES = os.getenv("VROBBLER_DELETE_STALE_SCROBBLES", True)
  30. # Used to dump data coming from srobbling sources, helpful for building new inputs
  31. DUMP_REQUEST_DATA = os.getenv("VROBBLER_DUMP_REQUEST_DATA", False)
  32. THESPORTSDB_API_KEY = os.getenv("VROBBLER_THESPORTSDB_API_KEY", "2")
  33. THESPORTSDB_BASE_URL = os.getenv(
  34. "VROBBLER_THESPORTSDB_BASE_URL", "https://www.thesportsdb.com/api/v1/json/"
  35. )
  36. TMDB_API_KEY = os.getenv("VROBBLER_TMDB_API_KEY", "")
  37. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  38. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "US/Eastern")
  39. ALLOWED_HOSTS = ["*"]
  40. CSRF_TRUSTED_ORIGINS = [
  41. os.getenv("VROBBLER_TRUSTED_ORIGINS", "http://localhost:8000")
  42. ]
  43. X_FRAME_OPTIONS = "SAMEORIGIN"
  44. CACHALOT_TIMEOUT = os.getenv("VROBBLER_CACHALOT_TIMEOUT", 3600)
  45. REDIS_URL = os.getenv("VROBBLER_REDIS_URL", None)
  46. INSTALLED_APPS = [
  47. "django.contrib.admin",
  48. "django.contrib.auth",
  49. "django.contrib.contenttypes",
  50. "django.contrib.sessions",
  51. "django.contrib.messages",
  52. "django.contrib.staticfiles",
  53. "django.contrib.sites",
  54. "django.contrib.humanize",
  55. "django_filters",
  56. "django_extensions",
  57. 'rest_framework.authtoken',
  58. "cachalot",
  59. "profiles",
  60. "scrobbles",
  61. "videos",
  62. "music",
  63. "podcasts",
  64. "sports",
  65. "rest_framework",
  66. "allauth",
  67. "allauth.account",
  68. "allauth.socialaccount",
  69. "django_celery_results",
  70. ]
  71. SITE_ID = 1
  72. MIDDLEWARE = [
  73. "django.middleware.security.SecurityMiddleware",
  74. "whitenoise.middleware.WhiteNoiseMiddleware",
  75. "django.contrib.sessions.middleware.SessionMiddleware",
  76. "django.middleware.common.CommonMiddleware",
  77. "django.middleware.csrf.CsrfViewMiddleware",
  78. "django.contrib.auth.middleware.AuthenticationMiddleware",
  79. "django.contrib.messages.middleware.MessageMiddleware",
  80. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  81. "django.middleware.gzip.GZipMiddleware",
  82. ]
  83. ROOT_URLCONF = "vrobbler.urls"
  84. TEMPLATES = [
  85. {
  86. "BACKEND": "django.template.backends.django.DjangoTemplates",
  87. "DIRS": [str(PROJECT_ROOT.joinpath("templates"))],
  88. "APP_DIRS": True,
  89. "OPTIONS": {
  90. "context_processors": [
  91. "django.template.context_processors.debug",
  92. "django.template.context_processors.request",
  93. "django.contrib.auth.context_processors.auth",
  94. "django.contrib.messages.context_processors.messages",
  95. "videos.context_processors.video_lists",
  96. "music.context_processors.music_lists",
  97. ],
  98. },
  99. },
  100. ]
  101. WSGI_APPLICATION = "vrobbler.wsgi.application"
  102. DATABASES = {
  103. "default": dj_database_url.config(
  104. default=os.getenv("VROBBLER_DATABASE_URL", "sqlite:///db.sqlite3"),
  105. conn_max_age=600,
  106. ),
  107. }
  108. if TESTING:
  109. DATABASES = {
  110. "default": dj_database_url.config(default="sqlite:///testdb.sqlite3")
  111. }
  112. CACHES = {
  113. "default": {
  114. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  115. "LOCATION": "unique-snowflake",
  116. }
  117. }
  118. if REDIS_URL:
  119. CACHES["default"][
  120. "BACKEND"
  121. ] = "django.core.cache.backends.redis.RedisCache"
  122. CACHES["default"]["LOCATION"] = REDIS_URL
  123. SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
  124. AUTHENTICATION_BACKENDS = [
  125. "django.contrib.auth.backends.ModelBackend",
  126. "allauth.account.auth_backends.AuthenticationBackend",
  127. ]
  128. REST_FRAMEWORK = {
  129. "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
  130. 'DEFAULT_AUTHENTICATION_CLASSES': [
  131. #'rest_framework.authentication.BasicAuthentication',
  132. #'rest_framework.authentication.TokenAuthentication',
  133. 'rest_framework.authentication.SessionAuthentication',
  134. ],
  135. "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
  136. "DEFAULT_FILTER_BACKENDS": [
  137. "django_filters.rest_framework.DjangoFilterBackend"
  138. ],
  139. 'DEFAULT_PARSER_CLASSES': [
  140. 'rest_framework.parsers.JSONParser',
  141. ],
  142. 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'vrobbler.negotiation.IgnoreClientContentNegotiation',
  143. "PAGE_SIZE": 100,
  144. }
  145. LOGIN_REDIRECT_URL = "/"
  146. AUTH_PASSWORD_VALIDATORS = [
  147. {
  148. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  149. },
  150. {
  151. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  152. },
  153. {
  154. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  155. },
  156. {
  157. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  158. },
  159. ]
  160. # Internationalization
  161. # https://docs.djangoproject.com/en/3.1/topics/i18n/
  162. LANGUAGE_CODE = "en-us"
  163. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "EST")
  164. USE_I18N = True
  165. USE_L10N = True
  166. USE_TZ = True
  167. # Static files (CSS, JavaScript, Images)
  168. # https://docs.djangoproject.com/en/3.1/howto/static-files/
  169. STATIC_URL = "static/"
  170. STATIC_ROOT = os.getenv(
  171. "VROBBLER_STATIC_ROOT", os.path.join(PROJECT_ROOT, "static")
  172. )
  173. MEDIA_URL = "/media/"
  174. MEDIA_ROOT = os.getenv(
  175. "VROBBLER_MEDIA_ROOT", os.path.join(PROJECT_ROOT, "media")
  176. )
  177. JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", False)
  178. LOG_TYPE = "json" if JSON_LOGGING else "log"
  179. default_level = "INFO"
  180. if DEBUG:
  181. default_level = "DEBUG"
  182. LOG_LEVEL = os.getenv("VROBBLER_LOG_LEVEL", default_level)
  183. LOG_FILE_PATH = os.getenv("VROBBLER_LOG_FILE_PATH", "/tmp/")
  184. LOGGING = {
  185. "version": 1,
  186. "disable_existing_loggers": False,
  187. "root": {
  188. "handlers": ["console", "file"],
  189. "level": LOG_LEVEL,
  190. "propagate": True,
  191. },
  192. "formatters": {
  193. "color": {
  194. "()": "colorlog.ColoredFormatter",
  195. # \r returns caret to line beginning, in tests this eats the silly dot that removes
  196. # the beautiful alignment produced below
  197. "format": "\r"
  198. "{log_color}{levelname:8s}{reset} "
  199. "{bold_cyan}{name}{reset}:"
  200. "{fg_bold_red}{lineno}{reset} "
  201. "{thin_yellow}{funcName} "
  202. "{thin_white}{message}"
  203. "{reset}",
  204. "style": "{",
  205. },
  206. "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
  207. "json": {
  208. "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
  209. "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
  210. },
  211. },
  212. "handlers": {
  213. "console": {
  214. "class": "logging.StreamHandler",
  215. "formatter": "color",
  216. "level": LOG_LEVEL,
  217. },
  218. "null": {
  219. "class": "logging.NullHandler",
  220. "level": LOG_LEVEL,
  221. },
  222. 'sql': {
  223. 'class': 'logging.handlers.RotatingFileHandler',
  224. 'filename': ''.join([LOG_FILE_PATH, 'vrobbler_sql.', LOG_TYPE]),
  225. 'formatter': LOG_TYPE,
  226. 'level': LOG_LEVEL,
  227. },
  228. 'file': {
  229. 'class': 'logging.handlers.RotatingFileHandler',
  230. 'filename': ''.join([LOG_FILE_PATH, 'vrobbler.', LOG_TYPE]),
  231. 'formatter': LOG_TYPE,
  232. 'level': LOG_LEVEL,
  233. },
  234. },
  235. "loggers": {
  236. # Quiet down our console a little
  237. "django": {
  238. "handlers": ["file"],
  239. "propagate": True,
  240. },
  241. "django.db.backends": {"handlers": ["null"]},
  242. "django.server": {"handlers": ["null"]},
  243. "vrobbler": {
  244. "handlers": ["file"],
  245. "propagate": True,
  246. },
  247. },
  248. }
  249. LOG_TO_CONSOLE = os.getenv("VROBBLER_LOG_TO_CONSOLE", False)
  250. if LOG_TO_CONSOLE:
  251. LOGGING['loggers']['django']['handlers'] = ["console"]
  252. LOGGING['loggers']['vrobbler']['handlers'] = ["console"]