We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Per-request metadata cache
## Problem
<!-- Please provide a clear and concise description of the problem that this feature request is designed to solve.-->

Currently, our `metadata` caching is global over the entire app. This may create problems if we have users simultaneously accessing different DBs. 

## Proposed solution
<!-- A clear and concise description of your proposed solution or feature. -->

We should use https://github.com/anexia/django-request-cache to cache metadata per-request only.

## Additional context
<!-- Add any other context or screenshots about the feature request here.-->

We occasionally run into state-based bugs that this would probably solve.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mathesar/state/metadata.py`
Content:
```
1 from db.metadata import get_empty_metadata
2 
3 
4 def get_cached_metadata():
5     """
6     Cached to minimize reflection queries to Postgres.
7     """
8     global _metadata_cache
9     return _metadata_cache
10 
11 
12 def reset_cached_metadata():
13     """
14     Resets MetaData cache to empty.
15     """
16     global _metadata_cache
17     _metadata_cache = get_empty_metadata()
18 
19 
20 _metadata_cache = get_empty_metadata()
21
```

Path: `config/settings.py`
Content:
```
1 """
2 Django settings for config project.
3 
4 Generated by 'django-admin startproject' using Django 3.1.7.
5 
6 For more information on this file, see
7 https://docs.djangoproject.com/en/3.1/topics/settings/
8 
9 For the full list of settings and their values, see
10 https://docs.djangoproject.com/en/3.1/ref/settings/
11 """
12 
13 import os
14 from pathlib import Path
15 
16 from decouple import Csv, config as decouple_config
17 from dj_database_url import parse as db_url
18 
19 
20 # We use a 'tuple' with pipes as delimiters as decople naively splits the global
21 # variables on commas when casting to Csv()
22 def pipe_delim(pipe_string):
23     # Remove opening and closing brackets
24     pipe_string = pipe_string[1:-1]
25     # Split on pipe delim
26     return pipe_string.split("|")
27 
28 
29 # Build paths inside the project like this: BASE_DIR / 'subdir'.
30 BASE_DIR = Path(__file__).resolve().parent.parent
31 
32 # Application definition
33 
34 INSTALLED_APPS = [
35     "django.contrib.admin",
36     "django.contrib.auth",
37     "django.contrib.contenttypes",
38     "django.contrib.sessions",
39     "django.contrib.messages",
40     "django.contrib.staticfiles",
41     "rest_framework",
42     "django_filters",
43     "django_property_filter",
44     "mathesar",
45 ]
46 
47 MIDDLEWARE = [
48     "django.middleware.security.SecurityMiddleware",
49     "django.contrib.sessions.middleware.SessionMiddleware",
50     "django.middleware.common.CommonMiddleware",
51     "django.middleware.csrf.CsrfViewMiddleware",
52     "django.contrib.auth.middleware.AuthenticationMiddleware",
53     "django.contrib.messages.middleware.MessageMiddleware",
54     "django.middleware.clickjacking.XFrameOptionsMiddleware",
55     "mathesar.middleware.CursorClosedHandlerMiddleware",
56 ]
57 
58 ROOT_URLCONF = "config.urls"
59 
60 TEMPLATES = [
61     {
62         "BACKEND": "django.template.backends.django.DjangoTemplates",
63         "DIRS": [],
64         "APP_DIRS": True,
65         "OPTIONS": {
66             "context_processors": [
67                 "config.context_processors.frontend_settings",
68                 "django.template.context_processors.debug",
69                 "django.template.context_processors.request",
70                 "django.contrib.auth.context_processors.auth",
71                 "django.contrib.messages.context_processors.messages",
72             ],
73         },
74     },
75 ]
76 
77 WSGI_APPLICATION = "config.wsgi.application"
78 
79 # Database
80 # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
81 
82 # TODO: Add to documentation that database keys should not be than 128 characters.
83 
84 # MATHESAR_DATABASES should be of the form '({db_name}|{db_url}), ({db_name}|{db_url})'
85 # See pipe_delim above for why we use pipes as delimiters
86 DATABASES = {
87     db_key: db_url(url_string)
88     for db_key, url_string in decouple_config('MATHESAR_DATABASES', cast=Csv(pipe_delim))
89 }
90 DATABASES[decouple_config('DJANGO_DATABASE_KEY')] = decouple_config('DJANGO_DATABASE_URL', cast=db_url)
91 
92 for db_key, db_dict in DATABASES.items():
93     # Engine can be '.postgresql' or '.postgresql_psycopg2'
94     if not db_dict['ENGINE'].startswith('django.db.backends.postgresql'):
95         raise ValueError(
96             f"{db_key} is not a PostgreSQL database. "
97             f"{db_dict['ENGINE']} found for {db_key}'s engine."
98         )
99 
100 
101 # pytest-django will create a new database named 'test_{DATABASES[table_db]['NAME']}'
102 # and use it for our API tests if we don't specify DATABASES[table_db]['TEST']['NAME']
103 TEST = decouple_config('TEST', default=False, cast=bool)
104 if TEST:
105     for db_key, _ in decouple_config('MATHESAR_DATABASES', cast=Csv(pipe_delim)):
106         DATABASES[db_key]['TEST'] = {'NAME': DATABASES[db_key]['NAME']}
107 
108 
109 # Quick-start development settings - unsuitable for production
110 # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
111 
112 # SECURITY WARNING: keep the secret key used in production secret!
113 SECRET_KEY = decouple_config('SECRET_KEY')
114 
115 # SECURITY WARNING: don't run with debug turned on in production!
116 DEBUG = decouple_config('DEBUG', default=False, cast=bool)
117 
118 ALLOWED_HOSTS = decouple_config('ALLOWED_HOSTS', cast=Csv())
119 
120 # Password validation
121 # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
122 
123 AUTH_PASSWORD_VALIDATORS = [
124     {
125         "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
126     },
127     {
128         "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
129     },
130     {
131         "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
132     },
133     {
134         "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
135     },
136 ]
137 
138 
139 # Internationalization
140 # https://docs.djangoproject.com/en/3.1/topics/i18n/
141 
142 LANGUAGE_CODE = "en-us"
143 
144 TIME_ZONE = "UTC"
145 
146 USE_I18N = True
147 
148 USE_L10N = True
149 
150 USE_TZ = True
151 
152 
153 # Static files (CSS, JavaScript, Images)
154 # https://docs.djangoproject.com/en/3.1/howto/static-files/
155 # https://docs.djangoproject.com/en/3.1/ref/contrib/staticfiles/
156 
157 STATIC_URL = "/static/"
158 
159 # When running with DEBUG=False, the webserver needs to serve files from this location
160 # python manage.py collectstatic has to be run to collect all static files into this location
161 # The files need to served in brotli or gzip compressed format
162 STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
163 
164 # Media files (uploaded by the user)
165 
166 MEDIA_ROOT = os.path.join(BASE_DIR, '.media/')
167 
168 MEDIA_URL = "/media/"
169 
170 # Update Authentication classes, removed BasicAuthentication
171 # Defaults: https://www.django-rest-framework.org/api-guide/settings/
172 REST_FRAMEWORK = {
173     'DEFAULT_AUTHENTICATION_CLASSES': [
174         'rest_framework.authentication.SessionAuthentication'
175     ],
176     'DEFAULT_PERMISSION_CLASSES': [
177         'rest_framework.permissions.IsAuthenticated',
178     ],
179     'DEFAULT_FILTER_BACKENDS': (
180         'django_filters.rest_framework.DjangoFilterBackend',
181         'rest_framework.filters.OrderingFilter',
182     ),
183     'TEST_REQUEST_DEFAULT_FORMAT': 'json',
184     'EXCEPTION_HANDLER':
185         'mathesar.exception_handlers.mathesar_exception_handler'
186 }
187 FRIENDLY_ERRORS = {
188     'FIELD_ERRORS': {
189         # By default drf-friendly-errors does contain error codes for ListSerializer type
190         'ListSerializer': {
191             'required': 2007,
192             'null': 2027,
193             'invalid_choice': 2083,
194             'not_a_list': 2123,
195             'empty': 2093
196         },
197         'PermittedPkRelatedField': {
198             'required': 2007,
199             'null': 2027,
200             'does_not_exist': 2151,
201             'incorrect_type': 2161
202         },
203         'PermittedSlugRelatedField': {
204             'required': 2007, 'invalid': 2002, 'null': 2027,
205             'does_not_exist': 2151, 'incorrect_type': 2161
206         },
207     },
208     'EXCEPTION_DICT': {
209         'Http404': 4005
210     }
211 }
212 # Mathesar settings
213 MATHESAR_MODE = decouple_config('MODE', default='PRODUCTION')
214 MATHESAR_UI_BUILD_LOCATION = os.path.join(BASE_DIR, 'mathesar/static/mathesar/')
215 MATHESAR_MANIFEST_LOCATION = os.path.join(MATHESAR_UI_BUILD_LOCATION, 'manifest.json')
216 MATHESAR_CLIENT_DEV_URL = 'http://localhost:3000'
217 MATHESAR_UI_SOURCE_LOCATION = os.path.join(BASE_DIR, 'mathesar_ui/')
218 MATHESAR_CAPTURE_UNHANDLED_EXCEPTION = decouple_config('CAPTURE_UNHANDLED_EXCEPTION', default=False)
219 
220 # UI source files have to be served by Django in order for static assets to be included during dev mode
221 # https://vitejs.dev/guide/assets.html
222 # https://vitejs.dev/guide/backend-integration.html
223 STATICFILES_DIRS = [MATHESAR_UI_SOURCE_LOCATION] if MATHESAR_MODE == 'DEVELOPMENT' else [MATHESAR_UI_BUILD_LOCATION]
224 
225 # Accounts
226 AUTH_USER_MODEL = 'mathesar.User'
227 LOGIN_URL = '/auth/login/'
228 LOGIN_REDIRECT_URL = '/'
229 DRF_ACCESS_POLICY = {
230     'reusable_conditions': ['mathesar.api.permission_conditions']
231 }
232
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/config/settings.py b/config/settings.py
--- a/config/settings.py
+++ b/config/settings.py
@@ -53,6 +53,8 @@
     "django.contrib.messages.middleware.MessageMiddleware",
     "django.middleware.clickjacking.XFrameOptionsMiddleware",
     "mathesar.middleware.CursorClosedHandlerMiddleware",
+    'django_userforeignkey.middleware.UserForeignKeyMiddleware',
+    'django_request_cache.middleware.RequestCacheMiddleware',
 ]
 
 ROOT_URLCONF = "config.urls"
diff --git a/mathesar/state/metadata.py b/mathesar/state/metadata.py
--- a/mathesar/state/metadata.py
+++ b/mathesar/state/metadata.py
@@ -1,11 +1,12 @@
 from db.metadata import get_empty_metadata
+from django_request_cache import cache_for_request
 
 
+@cache_for_request
 def get_cached_metadata():
     """
     Cached to minimize reflection queries to Postgres.
     """
-    global _metadata_cache
     return _metadata_cache

{"golden_diff": "diff --git a/config/settings.py b/config/settings.py\n--- a/config/settings.py\n+++ b/config/settings.py\n@@ -53,6 +53,8 @@\n     \"django.contrib.messages.middleware.MessageMiddleware\",\n     \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n     \"mathesar.middleware.CursorClosedHandlerMiddleware\",\n+    'django_userforeignkey.middleware.UserForeignKeyMiddleware',\n+    'django_request_cache.middleware.RequestCacheMiddleware',\n ]\n \n ROOT_URLCONF = \"config.urls\"\ndiff --git a/mathesar/state/metadata.py b/mathesar/state/metadata.py\n--- a/mathesar/state/metadata.py\n+++ b/mathesar/state/metadata.py\n@@ -1,11 +1,12 @@\n from db.metadata import get_empty_metadata\n+from django_request_cache import cache_for_request\n \n \n+@cache_for_request\n def get_cached_metadata():\n     \"\"\"\n     Cached to minimize reflection queries to Postgres.\n     \"\"\"\n-    global _metadata_cache\n     return _metadata_cache\n", "issue": "Per-request metadata cache\n## Problem\r\n<!-- Please provide a clear and concise description of the problem that this feature request is designed to solve.-->\r\n\r\nCurrently, our `metadata` caching is global over the entire app. This may create problems if we have users simultaneously accessing different DBs. \r\n\r\n## Proposed solution\r\n<!-- A clear and concise description of your proposed solution or feature. -->\r\n\r\nWe should use https://github.com/anexia/django-request-cache to cache metadata per-request only.\r\n\r\n## Additional context\r\n<!-- Add any other context or screenshots about the feature request here.-->\r\n\r\nWe occasionally run into state-based bugs that this would probably solve.\n", "before_files": [{"content": "from db.metadata import get_empty_metadata\n\n\ndef get_cached_metadata():\n    \"\"\"\n    Cached to minimize reflection queries to Postgres.\n    \"\"\"\n    global _metadata_cache\n    return _metadata_cache\n\n\ndef reset_cached_metadata():\n    \"\"\"\n    Resets MetaData cache to empty.\n    \"\"\"\n    global _metadata_cache\n    _metadata_cache = get_empty_metadata()\n\n\n_metadata_cache = get_empty_metadata()\n", "path": "mathesar/state/metadata.py"}, {"content": "\"\"\"\nDjango settings for config project.\n\nGenerated by 'django-admin startproject' using Django 3.1.7.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/3.1/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/3.1/ref/settings/\n\"\"\"\n\nimport os\nfrom pathlib import Path\n\nfrom decouple import Csv, config as decouple_config\nfrom dj_database_url import parse as db_url\n\n\n# We use a 'tuple' with pipes as delimiters as decople naively splits the global\n# variables on commas when casting to Csv()\ndef pipe_delim(pipe_string):\n    # Remove opening and closing brackets\n    pipe_string = pipe_string[1:-1]\n    # Split on pipe delim\n    return pipe_string.split(\"|\")\n\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n# Application definition\n\nINSTALLED_APPS = [\n    \"django.contrib.admin\",\n    \"django.contrib.auth\",\n    \"django.contrib.contenttypes\",\n    \"django.contrib.sessions\",\n    \"django.contrib.messages\",\n    \"django.contrib.staticfiles\",\n    \"rest_framework\",\n    \"django_filters\",\n    \"django_property_filter\",\n    \"mathesar\",\n]\n\nMIDDLEWARE = [\n    \"django.middleware.security.SecurityMiddleware\",\n    \"django.contrib.sessions.middleware.SessionMiddleware\",\n    \"django.middleware.common.CommonMiddleware\",\n    \"django.middleware.csrf.CsrfViewMiddleware\",\n    \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n    \"django.contrib.messages.middleware.MessageMiddleware\",\n    \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n    \"mathesar.middleware.CursorClosedHandlerMiddleware\",\n]\n\nROOT_URLCONF = \"config.urls\"\n\nTEMPLATES = [\n    {\n        \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n        \"DIRS\": [],\n        \"APP_DIRS\": True,\n        \"OPTIONS\": {\n            \"context_processors\": [\n                \"config.context_processors.frontend_settings\",\n                \"django.template.context_processors.debug\",\n                \"django.template.context_processors.request\",\n                \"django.contrib.auth.context_processors.auth\",\n                \"django.contrib.messages.context_processors.messages\",\n            ],\n        },\n    },\n]\n\nWSGI_APPLICATION = \"config.wsgi.application\"\n\n# Database\n# https://docs.djangoproject.com/en/3.1/ref/settings/#databases\n\n# TODO: Add to documentation that database keys should not be than 128 characters.\n\n# MATHESAR_DATABASES should be of the form '({db_name}|{db_url}), ({db_name}|{db_url})'\n# See pipe_delim above for why we use pipes as delimiters\nDATABASES = {\n    db_key: db_url(url_string)\n    for db_key, url_string in decouple_config('MATHESAR_DATABASES', cast=Csv(pipe_delim))\n}\nDATABASES[decouple_config('DJANGO_DATABASE_KEY')] = decouple_config('DJANGO_DATABASE_URL', cast=db_url)\n\nfor db_key, db_dict in DATABASES.items():\n    # Engine can be '.postgresql' or '.postgresql_psycopg2'\n    if not db_dict['ENGINE'].startswith('django.db.backends.postgresql'):\n        raise ValueError(\n            f\"{db_key} is not a PostgreSQL database. \"\n            f\"{db_dict['ENGINE']} found for {db_key}'s engine.\"\n        )\n\n\n# pytest-django will create a new database named 'test_{DATABASES[table_db]['NAME']}'\n# and use it for our API tests if we don't specify DATABASES[table_db]['TEST']['NAME']\nTEST = decouple_config('TEST', default=False, cast=bool)\nif TEST:\n    for db_key, _ in decouple_config('MATHESAR_DATABASES', cast=Csv(pipe_delim)):\n        DATABASES[db_key]['TEST'] = {'NAME': DATABASES[db_key]['NAME']}\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = decouple_config('SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = decouple_config('DEBUG', default=False, cast=bool)\n\nALLOWED_HOSTS = decouple_config('ALLOWED_HOSTS', cast=Csv())\n\n# Password validation\n# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\",\n    },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.1/topics/i18n/\n\nLANGUAGE_CODE = \"en-us\"\n\nTIME_ZONE = \"UTC\"\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.1/howto/static-files/\n# https://docs.djangoproject.com/en/3.1/ref/contrib/staticfiles/\n\nSTATIC_URL = \"/static/\"\n\n# When running with DEBUG=False, the webserver needs to serve files from this location\n# python manage.py collectstatic has to be run to collect all static files into this location\n# The files need to served in brotli or gzip compressed format\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static/')\n\n# Media files (uploaded by the user)\n\nMEDIA_ROOT = os.path.join(BASE_DIR, '.media/')\n\nMEDIA_URL = \"/media/\"\n\n# Update Authentication classes, removed BasicAuthentication\n# Defaults: https://www.django-rest-framework.org/api-guide/settings/\nREST_FRAMEWORK = {\n    'DEFAULT_AUTHENTICATION_CLASSES': [\n        'rest_framework.authentication.SessionAuthentication'\n    ],\n    'DEFAULT_PERMISSION_CLASSES': [\n        'rest_framework.permissions.IsAuthenticated',\n    ],\n    'DEFAULT_FILTER_BACKENDS': (\n        'django_filters.rest_framework.DjangoFilterBackend',\n        'rest_framework.filters.OrderingFilter',\n    ),\n    'TEST_REQUEST_DEFAULT_FORMAT': 'json',\n    'EXCEPTION_HANDLER':\n        'mathesar.exception_handlers.mathesar_exception_handler'\n}\nFRIENDLY_ERRORS = {\n    'FIELD_ERRORS': {\n        # By default drf-friendly-errors does contain error codes for ListSerializer type\n        'ListSerializer': {\n            'required': 2007,\n            'null': 2027,\n            'invalid_choice': 2083,\n            'not_a_list': 2123,\n            'empty': 2093\n        },\n        'PermittedPkRelatedField': {\n            'required': 2007,\n            'null': 2027,\n            'does_not_exist': 2151,\n            'incorrect_type': 2161\n        },\n        'PermittedSlugRelatedField': {\n            'required': 2007, 'invalid': 2002, 'null': 2027,\n            'does_not_exist': 2151, 'incorrect_type': 2161\n        },\n    },\n    'EXCEPTION_DICT': {\n        'Http404': 4005\n    }\n}\n# Mathesar settings\nMATHESAR_MODE = decouple_config('MODE', default='PRODUCTION')\nMATHESAR_UI_BUILD_LOCATION = os.path.join(BASE_DIR, 'mathesar/static/mathesar/')\nMATHESAR_MANIFEST_LOCATION = os.path.join(MATHESAR_UI_BUILD_LOCATION, 'manifest.json')\nMATHESAR_CLIENT_DEV_URL = 'http://localhost:3000'\nMATHESAR_UI_SOURCE_LOCATION = os.path.join(BASE_DIR, 'mathesar_ui/')\nMATHESAR_CAPTURE_UNHANDLED_EXCEPTION = decouple_config('CAPTURE_UNHANDLED_EXCEPTION', default=False)\n\n# UI source files have to be served by Django in order for static assets to be included during dev mode\n# https://vitejs.dev/guide/assets.html\n# https://vitejs.dev/guide/backend-integration.html\nSTATICFILES_DIRS = [MATHESAR_UI_SOURCE_LOCATION] if MATHESAR_MODE == 'DEVELOPMENT' else [MATHESAR_UI_BUILD_LOCATION]\n\n# Accounts\nAUTH_USER_MODEL = 'mathesar.User'\nLOGIN_URL = '/auth/login/'\nLOGIN_REDIRECT_URL = '/'\nDRF_ACCESS_POLICY = {\n    'reusable_conditions': ['mathesar.api.permission_conditions']\n}\n", "path": "config/settings.py"}], "after_files": [{"content": "from db.metadata import get_empty_metadata\nfrom django_request_cache import cache_for_request\n\n\n@cache_for_request\ndef get_cached_metadata():\n    \"\"\"\n    Cached to minimize reflection queries to Postgres.\n    \"\"\"\n    return _metadata_cache\n\n\ndef reset_cached_metadata():\n    \"\"\"\n    Resets MetaData cache to empty.\n    \"\"\"\n    global _metadata_cache\n    _metadata_cache = get_empty_metadata()\n\n\n_metadata_cache = get_empty_metadata()\n", "path": "mathesar/state/metadata.py"}, {"content": "\"\"\"\nDjango settings for config project.\n\nGenerated by 'django-admin startproject' using Django 3.1.7.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/3.1/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/3.1/ref/settings/\n\"\"\"\n\nimport os\nfrom pathlib import Path\n\nfrom decouple import Csv, config as decouple_config\nfrom dj_database_url import parse as db_url\n\n\n# We use a 'tuple' with pipes as delimiters as decople naively splits the global\n# variables on commas when casting to Csv()\ndef pipe_delim(pipe_string):\n    # Remove opening and closing brackets\n    pipe_string = pipe_string[1:-1]\n    # Split on pipe delim\n    return pipe_string.split(\"|\")\n\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n# Application definition\n\nINSTALLED_APPS = [\n    \"django.contrib.admin\",\n    \"django.contrib.auth\",\n    \"django.contrib.contenttypes\",\n    \"django.contrib.sessions\",\n    \"django.contrib.messages\",\n    \"django.contrib.staticfiles\",\n    \"rest_framework\",\n    \"django_filters\",\n    \"django_property_filter\",\n    \"mathesar\",\n]\n\nMIDDLEWARE = [\n    \"django.middleware.security.SecurityMiddleware\",\n    \"django.contrib.sessions.middleware.SessionMiddleware\",\n    \"django.middleware.common.CommonMiddleware\",\n    \"django.middleware.csrf.CsrfViewMiddleware\",\n    \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n    \"django.contrib.messages.middleware.MessageMiddleware\",\n    \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n    \"mathesar.middleware.CursorClosedHandlerMiddleware\",\n    'django_userforeignkey.middleware.UserForeignKeyMiddleware',\n    'django_request_cache.middleware.RequestCacheMiddleware',\n]\n\nROOT_URLCONF = \"config.urls\"\n\nTEMPLATES = [\n    {\n        \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n        \"DIRS\": [],\n        \"APP_DIRS\": True,\n        \"OPTIONS\": {\n            \"context_processors\": [\n                \"config.context_processors.frontend_settings\",\n                \"django.template.context_processors.debug\",\n                \"django.template.context_processors.request\",\n                \"django.contrib.auth.context_processors.auth\",\n                \"django.contrib.messages.context_processors.messages\",\n            ],\n        },\n    },\n]\n\nWSGI_APPLICATION = \"config.wsgi.application\"\n\n# Database\n# https://docs.djangoproject.com/en/3.1/ref/settings/#databases\n\n# TODO: Add to documentation that database keys should not be than 128 characters.\n\n# MATHESAR_DATABASES should be of the form '({db_name}|{db_url}), ({db_name}|{db_url})'\n# See pipe_delim above for why we use pipes as delimiters\nDATABASES = {\n    db_key: db_url(url_string)\n    for db_key, url_string in decouple_config('MATHESAR_DATABASES', cast=Csv(pipe_delim))\n}\nDATABASES[decouple_config('DJANGO_DATABASE_KEY')] = decouple_config('DJANGO_DATABASE_URL', cast=db_url)\n\nfor db_key, db_dict in DATABASES.items():\n    # Engine can be '.postgresql' or '.postgresql_psycopg2'\n    if not db_dict['ENGINE'].startswith('django.db.backends.postgresql'):\n        raise ValueError(\n            f\"{db_key} is not a PostgreSQL database. \"\n            f\"{db_dict['ENGINE']} found for {db_key}'s engine.\"\n        )\n\n\n# pytest-django will create a new database named 'test_{DATABASES[table_db]['NAME']}'\n# and use it for our API tests if we don't specify DATABASES[table_db]['TEST']['NAME']\nTEST = decouple_config('TEST', default=False, cast=bool)\nif TEST:\n    for db_key, _ in decouple_config('MATHESAR_DATABASES', cast=Csv(pipe_delim)):\n        DATABASES[db_key]['TEST'] = {'NAME': DATABASES[db_key]['NAME']}\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = decouple_config('SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = decouple_config('DEBUG', default=False, cast=bool)\n\nALLOWED_HOSTS = decouple_config('ALLOWED_HOSTS', cast=Csv())\n\n# Password validation\n# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\",\n    },\n    {\n        \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\",\n    },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.1/topics/i18n/\n\nLANGUAGE_CODE = \"en-us\"\n\nTIME_ZONE = \"UTC\"\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.1/howto/static-files/\n# https://docs.djangoproject.com/en/3.1/ref/contrib/staticfiles/\n\nSTATIC_URL = \"/static/\"\n\n# When running with DEBUG=False, the webserver needs to serve files from this location\n# python manage.py collectstatic has to be run to collect all static files into this location\n# The files need to served in brotli or gzip compressed format\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static/')\n\n# Media files (uploaded by the user)\n\nMEDIA_ROOT = os.path.join(BASE_DIR, '.media/')\n\nMEDIA_URL = \"/media/\"\n\n# Update Authentication classes, removed BasicAuthentication\n# Defaults: https://www.django-rest-framework.org/api-guide/settings/\nREST_FRAMEWORK = {\n    'DEFAULT_AUTHENTICATION_CLASSES': [\n        'rest_framework.authentication.SessionAuthentication'\n    ],\n    'DEFAULT_PERMISSION_CLASSES': [\n        'rest_framework.permissions.IsAuthenticated',\n    ],\n    'DEFAULT_FILTER_BACKENDS': (\n        'django_filters.rest_framework.DjangoFilterBackend',\n        'rest_framework.filters.OrderingFilter',\n    ),\n    'TEST_REQUEST_DEFAULT_FORMAT': 'json',\n    'EXCEPTION_HANDLER':\n        'mathesar.exception_handlers.mathesar_exception_handler'\n}\nFRIENDLY_ERRORS = {\n    'FIELD_ERRORS': {\n        # By default drf-friendly-errors does contain error codes for ListSerializer type\n        'ListSerializer': {\n            'required': 2007,\n            'null': 2027,\n            'invalid_choice': 2083,\n            'not_a_list': 2123,\n            'empty': 2093\n        },\n        'PermittedPkRelatedField': {\n            'required': 2007,\n            'null': 2027,\n            'does_not_exist': 2151,\n            'incorrect_type': 2161\n        },\n        'PermittedSlugRelatedField': {\n            'required': 2007, 'invalid': 2002, 'null': 2027,\n            'does_not_exist': 2151, 'incorrect_type': 2161\n        },\n    },\n    'EXCEPTION_DICT': {\n        'Http404': 4005\n    }\n}\n# Mathesar settings\nMATHESAR_MODE = decouple_config('MODE', default='PRODUCTION')\nMATHESAR_UI_BUILD_LOCATION = os.path.join(BASE_DIR, 'mathesar/static/mathesar/')\nMATHESAR_MANIFEST_LOCATION = os.path.join(MATHESAR_UI_BUILD_LOCATION, 'manifest.json')\nMATHESAR_CLIENT_DEV_URL = 'http://localhost:3000'\nMATHESAR_UI_SOURCE_LOCATION = os.path.join(BASE_DIR, 'mathesar_ui/')\nMATHESAR_CAPTURE_UNHANDLED_EXCEPTION = decouple_config('CAPTURE_UNHANDLED_EXCEPTION', default=False)\n\n# UI source files have to be served by Django in order for static assets to be included during dev mode\n# https://vitejs.dev/guide/assets.html\n# https://vitejs.dev/guide/backend-integration.html\nSTATICFILES_DIRS = [MATHESAR_UI_SOURCE_LOCATION] if MATHESAR_MODE == 'DEVELOPMENT' else [MATHESAR_UI_BUILD_LOCATION]\n\n# Accounts\nAUTH_USER_MODEL = 'mathesar.User'\nLOGIN_URL = '/auth/login/'\nLOGIN_REDIRECT_URL = '/'\nDRF_ACCESS_POLICY = {\n    'reusable_conditions': ['mathesar.api.permission_conditions']\n}\n", "path": "config/settings.py"}]}