settings.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. # Key must be 16, 24 or 32 bytes long and will be converted to a byte stream
  29. ENCRYPTED_FIELD_KEY = os.getenv(
  30. "VROBBLER_ENCRYPTED_FIELD_KEY", "12345678901234567890123456789012"
  31. )
  32. DJANGO_ENCRYPTED_FIELD_KEY = bytes(ENCRYPTED_FIELD_KEY, "utf-8")
  33. # Should we cull old in-progress scrobbles that are beyond the wait period for resuming?
  34. DELETE_STALE_SCROBBLES = os.getenv("VROBBLER_DELETE_STALE_SCROBBLES", True)
  35. # Used to dump data coming from srobbling sources, helpful for building new inputs
  36. DUMP_REQUEST_DATA = os.getenv("VROBBLER_DUMP_REQUEST_DATA", False)
  37. THESPORTSDB_API_KEY = os.getenv("VROBBLER_THESPORTSDB_API_KEY", "2")
  38. THESPORTSDB_BASE_URL = os.getenv(
  39. "VROBBLER_THESPORTSDB_BASE_URL", "https://www.thesportsdb.com/api/v1/json/"
  40. )
  41. TMDB_API_KEY = os.getenv("VROBBLER_TMDB_API_KEY", "")
  42. LASTFM_API_KEY = os.getenv("VROBBLER_LASTFM_API_KEY")
  43. LASTFM_SECRET_KEY = os.getenv("VROBBLER_LASTFM_SECRET_KEY")
  44. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  45. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "US/Eastern")
  46. ALLOWED_HOSTS = ["*"]
  47. CSRF_TRUSTED_ORIGINS = [
  48. os.getenv("VROBBLER_TRUSTED_ORIGINS", "http://localhost:8000")
  49. ]
  50. X_FRAME_OPTIONS = "SAMEORIGIN"
  51. REDIS_URL = os.getenv("VROBBLER_REDIS_URL", None)
  52. CELERY_TASK_ALWAYS_EAGER = os.getenv("VROBBLER_SKIP_CELERY", False)
  53. CELERY_BROKER_URL = REDIS_URL if REDIS_URL else "memory://localhost/"
  54. CELERY_RESULT_BACKEND = "django-db"
  55. CELERY_TIMEZONE = os.getenv("VROBBLER_TIME_ZONE", "US/Eastern")
  56. CELERY_TASK_TRACK_STARTED = True
  57. INSTALLED_APPS = [
  58. "django.contrib.admin",
  59. "django.contrib.auth",
  60. "django.contrib.contenttypes",
  61. "django.contrib.sessions",
  62. "django.contrib.messages",
  63. "django.contrib.staticfiles",
  64. "django.contrib.sites",
  65. "django.contrib.humanize",
  66. "django_filters",
  67. "django_extensions",
  68. "rest_framework.authtoken",
  69. "encrypted_field",
  70. "profiles",
  71. "scrobbles",
  72. "videos",
  73. "music",
  74. "podcasts",
  75. "sports",
  76. "mathfilters",
  77. "rest_framework",
  78. "allauth",
  79. "allauth.account",
  80. "allauth.socialaccount",
  81. "django_celery_results",
  82. ]
  83. SITE_ID = 1
  84. MIDDLEWARE = [
  85. "django.middleware.security.SecurityMiddleware",
  86. "whitenoise.middleware.WhiteNoiseMiddleware",
  87. "django.contrib.sessions.middleware.SessionMiddleware",
  88. "django.middleware.common.CommonMiddleware",
  89. "django.middleware.csrf.CsrfViewMiddleware",
  90. "django.contrib.auth.middleware.AuthenticationMiddleware",
  91. "django.contrib.messages.middleware.MessageMiddleware",
  92. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  93. "django.middleware.gzip.GZipMiddleware",
  94. ]
  95. ROOT_URLCONF = "vrobbler.urls"
  96. TEMPLATES = [
  97. {
  98. "BACKEND": "django.template.backends.django.DjangoTemplates",
  99. "DIRS": [str(PROJECT_ROOT.joinpath("templates"))],
  100. "APP_DIRS": True,
  101. "OPTIONS": {
  102. "context_processors": [
  103. "django.template.context_processors.debug",
  104. "django.template.context_processors.request",
  105. "django.contrib.auth.context_processors.auth",
  106. "django.contrib.messages.context_processors.messages",
  107. "videos.context_processors.video_lists",
  108. "music.context_processors.music_lists",
  109. ],
  110. },
  111. },
  112. ]
  113. WSGI_APPLICATION = "vrobbler.wsgi.application"
  114. DATABASES = {
  115. "default": dj_database_url.config(
  116. default=os.getenv("VROBBLER_DATABASE_URL", "sqlite:///db.sqlite3"),
  117. conn_max_age=600,
  118. ),
  119. }
  120. if TESTING:
  121. DATABASES = {
  122. "default": dj_database_url.config(default="sqlite:///testdb.sqlite3")
  123. }
  124. CACHES = {
  125. "default": {
  126. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  127. "LOCATION": "unique-snowflake",
  128. }
  129. }
  130. if REDIS_URL:
  131. CACHES["default"]["BACKEND"] = "django_redis.cache.RedisCache"
  132. CACHES["default"]["LOCATION"] = REDIS_URL
  133. SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
  134. AUTHENTICATION_BACKENDS = [
  135. "django.contrib.auth.backends.ModelBackend",
  136. "allauth.account.auth_backends.AuthenticationBackend",
  137. ]
  138. REST_FRAMEWORK = {
  139. "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
  140. 'DEFAULT_AUTHENTICATION_CLASSES': [
  141. 'rest_framework.authentication.BasicAuthentication',
  142. 'rest_framework.authentication.TokenAuthentication',
  143. 'rest_framework.authentication.SessionAuthentication',
  144. ],
  145. "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
  146. "DEFAULT_FILTER_BACKENDS": [
  147. "django_filters.rest_framework.DjangoFilterBackend"
  148. ],
  149. 'DEFAULT_PARSER_CLASSES': [
  150. 'rest_framework.parsers.JSONParser',
  151. ],
  152. 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'vrobbler.negotiation.IgnoreClientContentNegotiation',
  153. "PAGE_SIZE": 100,
  154. }
  155. LOGIN_REDIRECT_URL = "/"
  156. AUTH_PASSWORD_VALIDATORS = [
  157. {
  158. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  159. },
  160. {
  161. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  162. },
  163. {
  164. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  165. },
  166. {
  167. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  168. },
  169. ]
  170. # Internationalization
  171. # https://docs.djangoproject.com/en/3.1/topics/i18n/
  172. LANGUAGE_CODE = "en-us"
  173. TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "EST")
  174. USE_I18N = True
  175. USE_TZ = True
  176. # Static files (CSS, JavaScript, Images)
  177. # https://docs.djangoproject.com/en/3.1/howto/static-files/
  178. STATIC_URL = "static/"
  179. STATIC_ROOT = os.getenv(
  180. "VROBBLER_STATIC_ROOT", os.path.join(PROJECT_ROOT, "static")
  181. )
  182. MEDIA_URL = "/media/"
  183. MEDIA_ROOT = os.getenv(
  184. "VROBBLER_MEDIA_ROOT", os.path.join(PROJECT_ROOT, "media")
  185. )
  186. JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", False)
  187. LOG_TYPE = "json" if JSON_LOGGING else "log"
  188. default_level = "INFO"
  189. if DEBUG:
  190. default_level = "DEBUG"
  191. LOG_LEVEL = os.getenv("VROBBLER_LOG_LEVEL", default_level)
  192. LOG_FILE_PATH = os.getenv("VROBBLER_LOG_FILE_PATH", "/tmp/")
  193. LOGGING = {
  194. "version": 1,
  195. "disable_existing_loggers": False,
  196. "root": {
  197. "handlers": ["console", "file"],
  198. "level": LOG_LEVEL,
  199. "propagate": True,
  200. },
  201. "formatters": {
  202. "color": {
  203. "()": "colorlog.ColoredFormatter",
  204. # \r returns caret to line beginning, in tests this eats the silly dot that removes
  205. # the beautiful alignment produced below
  206. "format": "\r"
  207. "{log_color}{levelname:8s}{reset} "
  208. "{bold_cyan}{name}{reset}:"
  209. "{fg_bold_red}{lineno}{reset} "
  210. "{thin_yellow}{funcName} "
  211. "{thin_white}{message}"
  212. "{reset}",
  213. "style": "{",
  214. },
  215. "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
  216. "json": {
  217. "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
  218. "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
  219. },
  220. },
  221. "handlers": {
  222. "console": {
  223. "class": "logging.StreamHandler",
  224. "formatter": "color",
  225. "level": LOG_LEVEL,
  226. },
  227. "null": {
  228. "class": "logging.NullHandler",
  229. "level": LOG_LEVEL,
  230. },
  231. 'sql': {
  232. 'class': 'logging.handlers.RotatingFileHandler',
  233. 'filename': ''.join([LOG_FILE_PATH, 'vrobbler_sql.', LOG_TYPE]),
  234. 'formatter': LOG_TYPE,
  235. 'level': LOG_LEVEL,
  236. },
  237. 'file': {
  238. 'class': 'logging.handlers.RotatingFileHandler',
  239. 'filename': ''.join([LOG_FILE_PATH, 'vrobbler.', LOG_TYPE]),
  240. 'formatter': LOG_TYPE,
  241. 'level': LOG_LEVEL,
  242. },
  243. },
  244. "loggers": {
  245. # Quiet down our console a little
  246. "django": {
  247. "handlers": ["file"],
  248. "propagate": True,
  249. },
  250. "django.db.backends": {"handlers": ["null"]},
  251. "django.server": {"handlers": ["null"]},
  252. "pylast": {"handlers": ["null"], "propagate": False},
  253. "musicbrainzngs": {"handlers": ["null"], "propagate": False},
  254. "httpx": {"handlers": ["null"], "propagate": False},
  255. "vrobbler": {
  256. "handlers": ["console"],
  257. "propagate": False,
  258. },
  259. },
  260. }
  261. LOG_TO_CONSOLE = os.getenv("VROBBLER_LOG_TO_CONSOLE", False)
  262. if LOG_TO_CONSOLE:
  263. LOGGING['loggers']['django']['handlers'] = ["console"]
  264. LOGGING['loggers']['vrobbler']['handlers'] = ["console"]