We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Scaling of PostgreSQL Connections
We have tried in the past to implement connection pooling for Django <==> PostgreSQL. We should try this again so that the system doesn't get pulled down by too many parallel requests (as could happen in the event of UCL Assistant).

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `backend/uclapi/uclapi/settings.py`
Content:
```
1 """
2 Django settings for uclapi project.
3 
4 Generated by 'django-admin startproject' using Django 1.10.4.
5 
6 For more information on this file, see
7 https://docs.djangoproject.com/en/1.10/topics/settings/
8 
9 For the full list of settings and their values, see
10 https://docs.djangoproject.com/en/1.10/ref/settings/
11 """
12 
13 import os
14 import requests
15 from distutils.util import strtobool
16 
17 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
18 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19 
20 
21 # Quick-start development settings - unsuitable for production
22 # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
23 
24 # SECURITY WARNING: keep the secret key used in production secret!
25 SECRET_KEY = os.environ.get("SECRET_KEY")
26 
27 # SECURITY WARNING: don't run with debug turned on in production!
28 # This value should be set by the UCLAPI_PRODUCTION environment
29 # variable anyway. If in production, debug should be false.
30 DEBUG = not strtobool(os.environ.get("UCLAPI_PRODUCTION"))
31 
32 ALLOWED_HOSTS = ["localhost"]
33 
34 # If a domain is specified then make this an allowed host
35 if os.environ.get("UCLAPI_DOMAIN"):
36     ALLOWED_HOSTS.append(os.environ.get("UCLAPI_DOMAIN"))
37 
38 # If we are running under the AWS Elastic Load Balancer then enable internal
39 # requests so that the ELB and Health Checks work
40 if strtobool(os.environ.get("UCLAPI_RUNNING_ON_AWS_ELB")):
41     EC2_PRIVATE_IP = None
42     try:
43         EC2_PRIVATE_IP = requests.get(
44             "http://169.254.169.254/latest/meta-data/local-ipv4",
45             timeout=0.01
46         ).text
47     except requests.exceptions.RequestException:
48         pass
49 
50     if EC2_PRIVATE_IP:
51         ALLOWED_HOSTS.append(EC2_PRIVATE_IP)
52 
53 # Application definition
54 
55 INSTALLED_APPS = [
56     'django.contrib.admin',
57     'django.contrib.auth',
58     'django.contrib.contenttypes',
59     'django.contrib.sessions',
60     'django.contrib.messages',
61     'django.contrib.staticfiles',
62     'rest_framework',
63     'dashboard',
64     'marketplace',
65     'roombookings',
66     'oauth',
67     'timetable',
68     'common',
69     'raven.contrib.django.raven_compat',
70     'corsheaders',
71     'workspaces',
72     'webpack_loader'
73 ]
74 
75 MIDDLEWARE = [
76     'django.middleware.security.SecurityMiddleware',
77     'django.contrib.sessions.middleware.SessionMiddleware',
78     'corsheaders.middleware.CorsMiddleware',
79     'django.middleware.common.CommonMiddleware',
80     'django.middleware.csrf.CsrfViewMiddleware',
81     'django.contrib.auth.middleware.AuthenticationMiddleware',
82     'django.contrib.messages.middleware.MessageMiddleware',
83     'django.middleware.clickjacking.XFrameOptionsMiddleware',
84 ]
85 
86 if DEBUG:
87     MIDDLEWARE.append(
88         'dashboard.middleware.fake_shibboleth_middleware'
89         '.FakeShibbolethMiddleWare'
90     )
91 
92 ROOT_URLCONF = 'uclapi.urls'
93 
94 TEMPLATES = [
95     {
96         'BACKEND': 'django.template.backends.django.DjangoTemplates',
97         'DIRS': [],
98         'APP_DIRS': True,
99         'OPTIONS': {
100             'context_processors': [
101                 'django.template.context_processors.debug',
102                 'django.template.context_processors.request',
103                 'django.contrib.auth.context_processors.auth',
104                 'django.contrib.messages.context_processors.messages',
105             ],
106         },
107     },
108 ]
109 
110 WSGI_APPLICATION = 'uclapi.wsgi.application'
111 
112 
113 # Database
114 # https://docs.djangoproject.com/en/1.10/ref/settings/#databases
115 
116 DATABASES = {
117     'default': {
118         'ENGINE': 'django.db.backends.postgresql',
119         'NAME': os.environ.get("DB_UCLAPI_NAME"),
120         'USER': os.environ.get("DB_UCLAPI_USERNAME"),
121         'PASSWORD': os.environ.get("DB_UCLAPI_PASSWORD"),
122         'HOST': os.environ.get("DB_UCLAPI_HOST"),
123         'PORT': os.environ.get("DB_UCLAPI_PORT")
124     },
125     'roombookings': {
126         'ENGINE': 'django.db.backends.oracle',
127         'NAME': os.environ.get("DB_ROOMS_NAME"),
128         'USER': os.environ.get("DB_ROOMS_USERNAME"),
129         'PASSWORD': os.environ.get("DB_ROOMS_PASSWORD"),
130         'HOST': '',
131         'PORT': ''
132     },
133     'gencache': {
134         'ENGINE': 'django.db.backends.postgresql',
135         'NAME': os.environ.get("DB_CACHE_NAME"),
136         'USER': os.environ.get("DB_CACHE_USERNAME"),
137         'PASSWORD': os.environ.get("DB_CACHE_PASSWORD"),
138         'HOST': os.environ.get("DB_CACHE_HOST"),
139         'PORT': os.environ.get("DB_CACHE_PORT")
140     }
141 }
142 
143 DATABASE_ROUTERS = ['uclapi.dbrouters.ModelRouter']
144 
145 RAVEN_CONFIG = {
146     'dsn': os.environ.get("SENTRY_DSN"),
147 }
148 
149 
150 # Password validation
151 # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
152 
153 AUTH_PASSWORD_VALIDATORS = [
154     {
155         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',  # noqa
156     },
157     {
158         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',  # noqa
159     },
160     {
161         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',  # noqa
162     },
163     {
164         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',  # noqa
165     },
166 ]
167 
168 
169 # Internationalization
170 # https://docs.djangoproject.com/en/1.10/topics/i18n/
171 
172 LANGUAGE_CODE = 'en-us'
173 
174 TIME_ZONE = 'UTC'
175 
176 USE_I18N = True
177 
178 USE_L10N = True
179 
180 USE_TZ = False
181 
182 # Cross Origin settings
183 CORS_ORIGIN_ALLOW_ALL = True
184 CORS_URLS_REGEX = r'^/roombookings/.*$'
185 
186 # Fair use policy
187 fair_use_policy_path = os.path.join(
188     BASE_DIR,
189     'uclapi/UCLAPIAcceptableUsePolicy.txt'
190 )
191 with open(fair_use_policy_path, 'r', encoding='utf-8') as fp:
192     FAIR_USE_POLICY = list(fp)
193 
194 REDIS_UCLAPI_HOST = os.environ["REDIS_UCLAPI_HOST"]
195 
196 # Celery Settings
197 CELERY_BROKER_URL = 'redis://' + REDIS_UCLAPI_HOST
198 CELERY_ACCEPT_CONTENT = ['json']
199 CELERY_TASK_SERIALIZER = 'json'
200 CELERY_RESULT_SERIALIZER = 'json'
201 
202 ROOMBOOKINGS_SETID = 'LIVE-18-19'
203 
204 # This dictates how many Medium articles we scrape
205 MEDIUM_ARTICLE_QUANTITY = 3
206 
207 # We need to specify a tuple of STATICFILES_DIRS instead of a
208 # STATIC_ROOT so that collectstatic picks up the WebPack bundles
209 STATICFILES_DIRS = (
210     os.path.join(BASE_DIR, 'static'),
211 )
212 
213 # S3 file storage settings
214 # There are three scenarios to consider:
215 # 1) Local development
216 #    In local dev,  AWS_S3_STATICS = False
217 #                   AWS_S3_STATICS_CREDENTIALS_ENABLED = False
218 #    These allow you to use local statics using /static/ in the
219 #    same way as you would normally.
220 # 2) Production
221 #    In prod,       AWS_S3_STATICS = True
222 #                   AWS_S3_STATICS_CREDENTIALS_ENABLED = False
223 #    This means that S3 statics will be used, but no creds are
224 #    needed on the boxes because web servers should never do
225 #    uploads to the remote S3 bucket.
226 # 3) Deployment
227 #    In deployment, AWS_S3_STATICS = True
228 #                   AWS_S3_STATICS_CREDENTIALS_ENABLED = True
229 #    This will be done either from CI/CD or from the computer
230 #    of a person who has permission to upload new statics to
231 #    S3.
232 
233 if strtobool(os.environ.get("AWS_S3_STATICS", "False")):
234     DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
235     STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
236     AWS_STORAGE_BUCKET_NAME = os.environ["AWS_S3_BUCKET_NAME"]
237     AWS_LOCATION = os.environ["AWS_S3_BUCKET_PATH"]
238     AWS_S3_REGION_NAME = os.environ["AWS_S3_REGION"]
239 
240     # This is a hack to not require AWS Access Credentials
241     # when the system is running in the Cloud. This avoids us from
242     # needing to store AWS credentials.
243     # https://github.com/jschneier/django-storages/issues/254#issuecomment-329813295  # noqa
244     AWS_S3_CUSTOM_DOMAIN = "{}.s3.amazonaws.com".format(
245         AWS_STORAGE_BUCKET_NAME
246     )
247 
248     # We set the default ACL data on all stacks we upload to public-read
249     # so that the files are world readable.
250     # This is required for the statics to be served up directly.
251     # Often this is a security risk, but in this case it's
252     # actually required to serve the website.
253     AWS_DEFAULT_ACL = "public-read"
254 
255     # If credentials are enabled, collectstatic can do uploads
256     if strtobool(os.environ["AWS_S3_STATICS_CREDENTIALS_ENABLED"]):
257         AWS_ACCESS_KEY_ID = os.environ["AWS_ACCESS_KEY_ID"]
258         AWS_SECRET_ACCESS_KEY = os.environ["AWS_ACCESS_SECRET"]
259         AWS_S3_OBJECT_PARAMETERS = {
260             'CacheControl': 'max-age=86400',
261         }
262         AWS_S3_ENCRYPTION = False
263     else:
264         AWS_QUERYSTRING_AUTH = False
265 
266     # Since we are hosting on AWS, we should set the Static URL to it
267     STATIC_URL = "{}/{}".format(
268         AWS_S3_CUSTOM_DOMAIN,
269         AWS_LOCATION
270     )
271     # Set up the WebPack loader for remote loading
272     WEBPACK_LOADER = {
273         'DEFAULT': {
274             'CACHE': not DEBUG,
275             'BUNDLE_DIR_NAME': './',  # must end with slash
276             'STATS_URL': "https://{}webpack-stats.json".format(
277                 STATIC_URL
278             ),
279             'POLL_INTERVAL': 0.1,
280             'TIMEOUT': None,
281             'IGNORE': [r'.+\.hot-update.js', r'.+\.map']
282         }
283     }
284 else:
285     # https://docs.djangoproject.com/en/1.10/howto/static-files/
286     # The default Static URL is /static/ which is fine for when statics
287     # have been built and placed into their respective folders.
288     STATIC_URL = os.environ.get("STATIC_URL", '/static/')
289 
290     # Set up the WebPack loader for local loading
291     WEBPACK_LOADER = {
292         'DEFAULT': {
293             'CACHE': not DEBUG,
294             'BUNDLE_DIR_NAME': './',  # must end with slash
295             'STATS_FILE': os.path.join(
296                 BASE_DIR,
297                 'static',
298                 'webpack-stats.json'
299             ),
300             'POLL_INTERVAL': 0.1,
301             'TIMEOUT': None,
302             'IGNORE': [r'.+\.hot-update.js', r'.+\.map']
303         }
304     }
305
```
--- 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/backend/uclapi/uclapi/settings.py b/backend/uclapi/uclapi/settings.py
--- a/backend/uclapi/uclapi/settings.py
+++ b/backend/uclapi/uclapi/settings.py
@@ -115,7 +115,7 @@
 
 DATABASES = {
     'default': {
-        'ENGINE': 'django.db.backends.postgresql',
+        'ENGINE': 'django_postgrespool2',
         'NAME': os.environ.get("DB_UCLAPI_NAME"),
         'USER': os.environ.get("DB_UCLAPI_USERNAME"),
         'PASSWORD': os.environ.get("DB_UCLAPI_PASSWORD"),
@@ -131,7 +131,7 @@
         'PORT': ''
     },
     'gencache': {
-        'ENGINE': 'django.db.backends.postgresql',
+        'ENGINE': 'django_postgrespool2',
         'NAME': os.environ.get("DB_CACHE_NAME"),
         'USER': os.environ.get("DB_CACHE_USERNAME"),
         'PASSWORD': os.environ.get("DB_CACHE_PASSWORD"),
@@ -140,6 +140,15 @@
     }
 }
 
+# Max connections is pool_size + max_overflow
+# Will idle at pool_size connections, overflow are for spikes in traffic
+
+DATABASE_POOL_ARGS = {
+    'max_overflow': 15,
+    'pool_size': 5,
+    'recycle': 300
+}
+
 DATABASE_ROUTERS = ['uclapi.dbrouters.ModelRouter']
 
 RAVEN_CONFIG = {

{"golden_diff": "diff --git a/backend/uclapi/uclapi/settings.py b/backend/uclapi/uclapi/settings.py\n--- a/backend/uclapi/uclapi/settings.py\n+++ b/backend/uclapi/uclapi/settings.py\n@@ -115,7 +115,7 @@\n \n DATABASES = {\n     'default': {\n-        'ENGINE': 'django.db.backends.postgresql',\n+        'ENGINE': 'django_postgrespool2',\n         'NAME': os.environ.get(\"DB_UCLAPI_NAME\"),\n         'USER': os.environ.get(\"DB_UCLAPI_USERNAME\"),\n         'PASSWORD': os.environ.get(\"DB_UCLAPI_PASSWORD\"),\n@@ -131,7 +131,7 @@\n         'PORT': ''\n     },\n     'gencache': {\n-        'ENGINE': 'django.db.backends.postgresql',\n+        'ENGINE': 'django_postgrespool2',\n         'NAME': os.environ.get(\"DB_CACHE_NAME\"),\n         'USER': os.environ.get(\"DB_CACHE_USERNAME\"),\n         'PASSWORD': os.environ.get(\"DB_CACHE_PASSWORD\"),\n@@ -140,6 +140,15 @@\n     }\n }\n \n+# Max connections is pool_size + max_overflow\n+# Will idle at pool_size connections, overflow are for spikes in traffic\n+\n+DATABASE_POOL_ARGS = {\n+    'max_overflow': 15,\n+    'pool_size': 5,\n+    'recycle': 300\n+}\n+\n DATABASE_ROUTERS = ['uclapi.dbrouters.ModelRouter']\n \n RAVEN_CONFIG = {\n", "issue": "Scaling of PostgreSQL Connections\nWe have tried in the past to implement connection pooling for Django <==> PostgreSQL. We should try this again so that the system doesn't get pulled down by too many parallel requests (as could happen in the event of UCL Assistant).\n", "before_files": [{"content": "\"\"\"\nDjango settings for uclapi project.\n\nGenerated by 'django-admin startproject' using Django 1.10.4.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.10/ref/settings/\n\"\"\"\n\nimport os\nimport requests\nfrom distutils.util import strtobool\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\n# SECURITY WARNING: don't run with debug turned on in production!\n# This value should be set by the UCLAPI_PRODUCTION environment\n# variable anyway. If in production, debug should be false.\nDEBUG = not strtobool(os.environ.get(\"UCLAPI_PRODUCTION\"))\n\nALLOWED_HOSTS = [\"localhost\"]\n\n# If a domain is specified then make this an allowed host\nif os.environ.get(\"UCLAPI_DOMAIN\"):\n    ALLOWED_HOSTS.append(os.environ.get(\"UCLAPI_DOMAIN\"))\n\n# If we are running under the AWS Elastic Load Balancer then enable internal\n# requests so that the ELB and Health Checks work\nif strtobool(os.environ.get(\"UCLAPI_RUNNING_ON_AWS_ELB\")):\n    EC2_PRIVATE_IP = None\n    try:\n        EC2_PRIVATE_IP = requests.get(\n            \"http://169.254.169.254/latest/meta-data/local-ipv4\",\n            timeout=0.01\n        ).text\n    except requests.exceptions.RequestException:\n        pass\n\n    if EC2_PRIVATE_IP:\n        ALLOWED_HOSTS.append(EC2_PRIVATE_IP)\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    'dashboard',\n    'marketplace',\n    'roombookings',\n    'oauth',\n    'timetable',\n    'common',\n    'raven.contrib.django.raven_compat',\n    'corsheaders',\n    'workspaces',\n    'webpack_loader'\n]\n\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'corsheaders.middleware.CorsMiddleware',\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]\n\nif DEBUG:\n    MIDDLEWARE.append(\n        'dashboard.middleware.fake_shibboleth_middleware'\n        '.FakeShibbolethMiddleWare'\n    )\n\nROOT_URLCONF = 'uclapi.urls'\n\nTEMPLATES = [\n    {\n        'BACKEND': 'django.template.backends.django.DjangoTemplates',\n        'DIRS': [],\n        'APP_DIRS': True,\n        'OPTIONS': {\n            'context_processors': [\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 = 'uclapi.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n\nDATABASES = {\n    'default': {\n        'ENGINE': 'django.db.backends.postgresql',\n        'NAME': os.environ.get(\"DB_UCLAPI_NAME\"),\n        'USER': os.environ.get(\"DB_UCLAPI_USERNAME\"),\n        'PASSWORD': os.environ.get(\"DB_UCLAPI_PASSWORD\"),\n        'HOST': os.environ.get(\"DB_UCLAPI_HOST\"),\n        'PORT': os.environ.get(\"DB_UCLAPI_PORT\")\n    },\n    'roombookings': {\n        'ENGINE': 'django.db.backends.oracle',\n        'NAME': os.environ.get(\"DB_ROOMS_NAME\"),\n        'USER': os.environ.get(\"DB_ROOMS_USERNAME\"),\n        'PASSWORD': os.environ.get(\"DB_ROOMS_PASSWORD\"),\n        'HOST': '',\n        'PORT': ''\n    },\n    'gencache': {\n        'ENGINE': 'django.db.backends.postgresql',\n        'NAME': os.environ.get(\"DB_CACHE_NAME\"),\n        'USER': os.environ.get(\"DB_CACHE_USERNAME\"),\n        'PASSWORD': os.environ.get(\"DB_CACHE_PASSWORD\"),\n        'HOST': os.environ.get(\"DB_CACHE_HOST\"),\n        'PORT': os.environ.get(\"DB_CACHE_PORT\")\n    }\n}\n\nDATABASE_ROUTERS = ['uclapi.dbrouters.ModelRouter']\n\nRAVEN_CONFIG = {\n    'dsn': os.environ.get(\"SENTRY_DSN\"),\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',  # noqa\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',  # noqa\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',  # noqa\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',  # noqa\n    },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = False\n\n# Cross Origin settings\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_URLS_REGEX = r'^/roombookings/.*$'\n\n# Fair use policy\nfair_use_policy_path = os.path.join(\n    BASE_DIR,\n    'uclapi/UCLAPIAcceptableUsePolicy.txt'\n)\nwith open(fair_use_policy_path, 'r', encoding='utf-8') as fp:\n    FAIR_USE_POLICY = list(fp)\n\nREDIS_UCLAPI_HOST = os.environ[\"REDIS_UCLAPI_HOST\"]\n\n# Celery Settings\nCELERY_BROKER_URL = 'redis://' + REDIS_UCLAPI_HOST\nCELERY_ACCEPT_CONTENT = ['json']\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\n\nROOMBOOKINGS_SETID = 'LIVE-18-19'\n\n# This dictates how many Medium articles we scrape\nMEDIUM_ARTICLE_QUANTITY = 3\n\n# We need to specify a tuple of STATICFILES_DIRS instead of a\n# STATIC_ROOT so that collectstatic picks up the WebPack bundles\nSTATICFILES_DIRS = (\n    os.path.join(BASE_DIR, 'static'),\n)\n\n# S3 file storage settings\n# There are three scenarios to consider:\n# 1) Local development\n#    In local dev,  AWS_S3_STATICS = False\n#                   AWS_S3_STATICS_CREDENTIALS_ENABLED = False\n#    These allow you to use local statics using /static/ in the\n#    same way as you would normally.\n# 2) Production\n#    In prod,       AWS_S3_STATICS = True\n#                   AWS_S3_STATICS_CREDENTIALS_ENABLED = False\n#    This means that S3 statics will be used, but no creds are\n#    needed on the boxes because web servers should never do\n#    uploads to the remote S3 bucket.\n# 3) Deployment\n#    In deployment, AWS_S3_STATICS = True\n#                   AWS_S3_STATICS_CREDENTIALS_ENABLED = True\n#    This will be done either from CI/CD or from the computer\n#    of a person who has permission to upload new statics to\n#    S3.\n\nif strtobool(os.environ.get(\"AWS_S3_STATICS\", \"False\")):\n    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n    AWS_STORAGE_BUCKET_NAME = os.environ[\"AWS_S3_BUCKET_NAME\"]\n    AWS_LOCATION = os.environ[\"AWS_S3_BUCKET_PATH\"]\n    AWS_S3_REGION_NAME = os.environ[\"AWS_S3_REGION\"]\n\n    # This is a hack to not require AWS Access Credentials\n    # when the system is running in the Cloud. This avoids us from\n    # needing to store AWS credentials.\n    # https://github.com/jschneier/django-storages/issues/254#issuecomment-329813295  # noqa\n    AWS_S3_CUSTOM_DOMAIN = \"{}.s3.amazonaws.com\".format(\n        AWS_STORAGE_BUCKET_NAME\n    )\n\n    # We set the default ACL data on all stacks we upload to public-read\n    # so that the files are world readable.\n    # This is required for the statics to be served up directly.\n    # Often this is a security risk, but in this case it's\n    # actually required to serve the website.\n    AWS_DEFAULT_ACL = \"public-read\"\n\n    # If credentials are enabled, collectstatic can do uploads\n    if strtobool(os.environ[\"AWS_S3_STATICS_CREDENTIALS_ENABLED\"]):\n        AWS_ACCESS_KEY_ID = os.environ[\"AWS_ACCESS_KEY_ID\"]\n        AWS_SECRET_ACCESS_KEY = os.environ[\"AWS_ACCESS_SECRET\"]\n        AWS_S3_OBJECT_PARAMETERS = {\n            'CacheControl': 'max-age=86400',\n        }\n        AWS_S3_ENCRYPTION = False\n    else:\n        AWS_QUERYSTRING_AUTH = False\n\n    # Since we are hosting on AWS, we should set the Static URL to it\n    STATIC_URL = \"{}/{}\".format(\n        AWS_S3_CUSTOM_DOMAIN,\n        AWS_LOCATION\n    )\n    # Set up the WebPack loader for remote loading\n    WEBPACK_LOADER = {\n        'DEFAULT': {\n            'CACHE': not DEBUG,\n            'BUNDLE_DIR_NAME': './',  # must end with slash\n            'STATS_URL': \"https://{}webpack-stats.json\".format(\n                STATIC_URL\n            ),\n            'POLL_INTERVAL': 0.1,\n            'TIMEOUT': None,\n            'IGNORE': [r'.+\\.hot-update.js', r'.+\\.map']\n        }\n    }\nelse:\n    # https://docs.djangoproject.com/en/1.10/howto/static-files/\n    # The default Static URL is /static/ which is fine for when statics\n    # have been built and placed into their respective folders.\n    STATIC_URL = os.environ.get(\"STATIC_URL\", '/static/')\n\n    # Set up the WebPack loader for local loading\n    WEBPACK_LOADER = {\n        'DEFAULT': {\n            'CACHE': not DEBUG,\n            'BUNDLE_DIR_NAME': './',  # must end with slash\n            'STATS_FILE': os.path.join(\n                BASE_DIR,\n                'static',\n                'webpack-stats.json'\n            ),\n            'POLL_INTERVAL': 0.1,\n            'TIMEOUT': None,\n            'IGNORE': [r'.+\\.hot-update.js', r'.+\\.map']\n        }\n    }\n", "path": "backend/uclapi/uclapi/settings.py"}], "after_files": [{"content": "\"\"\"\nDjango settings for uclapi project.\n\nGenerated by 'django-admin startproject' using Django 1.10.4.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.10/ref/settings/\n\"\"\"\n\nimport os\nimport requests\nfrom distutils.util import strtobool\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\n# SECURITY WARNING: don't run with debug turned on in production!\n# This value should be set by the UCLAPI_PRODUCTION environment\n# variable anyway. If in production, debug should be false.\nDEBUG = not strtobool(os.environ.get(\"UCLAPI_PRODUCTION\"))\n\nALLOWED_HOSTS = [\"localhost\"]\n\n# If a domain is specified then make this an allowed host\nif os.environ.get(\"UCLAPI_DOMAIN\"):\n    ALLOWED_HOSTS.append(os.environ.get(\"UCLAPI_DOMAIN\"))\n\n# If we are running under the AWS Elastic Load Balancer then enable internal\n# requests so that the ELB and Health Checks work\nif strtobool(os.environ.get(\"UCLAPI_RUNNING_ON_AWS_ELB\")):\n    EC2_PRIVATE_IP = None\n    try:\n        EC2_PRIVATE_IP = requests.get(\n            \"http://169.254.169.254/latest/meta-data/local-ipv4\",\n            timeout=0.01\n        ).text\n    except requests.exceptions.RequestException:\n        pass\n\n    if EC2_PRIVATE_IP:\n        ALLOWED_HOSTS.append(EC2_PRIVATE_IP)\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    'dashboard',\n    'marketplace',\n    'roombookings',\n    'oauth',\n    'timetable',\n    'common',\n    'raven.contrib.django.raven_compat',\n    'corsheaders',\n    'workspaces',\n    'webpack_loader'\n]\n\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'corsheaders.middleware.CorsMiddleware',\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]\n\nif DEBUG:\n    MIDDLEWARE.append(\n        'dashboard.middleware.fake_shibboleth_middleware'\n        '.FakeShibbolethMiddleWare'\n    )\n\nROOT_URLCONF = 'uclapi.urls'\n\nTEMPLATES = [\n    {\n        'BACKEND': 'django.template.backends.django.DjangoTemplates',\n        'DIRS': [],\n        'APP_DIRS': True,\n        'OPTIONS': {\n            'context_processors': [\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 = 'uclapi.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n\nDATABASES = {\n    'default': {\n        'ENGINE': 'django_postgrespool2',\n        'NAME': os.environ.get(\"DB_UCLAPI_NAME\"),\n        'USER': os.environ.get(\"DB_UCLAPI_USERNAME\"),\n        'PASSWORD': os.environ.get(\"DB_UCLAPI_PASSWORD\"),\n        'HOST': os.environ.get(\"DB_UCLAPI_HOST\"),\n        'PORT': os.environ.get(\"DB_UCLAPI_PORT\")\n    },\n    'roombookings': {\n        'ENGINE': 'django.db.backends.oracle',\n        'NAME': os.environ.get(\"DB_ROOMS_NAME\"),\n        'USER': os.environ.get(\"DB_ROOMS_USERNAME\"),\n        'PASSWORD': os.environ.get(\"DB_ROOMS_PASSWORD\"),\n        'HOST': '',\n        'PORT': ''\n    },\n    'gencache': {\n        'ENGINE': 'django_postgrespool2',\n        'NAME': os.environ.get(\"DB_CACHE_NAME\"),\n        'USER': os.environ.get(\"DB_CACHE_USERNAME\"),\n        'PASSWORD': os.environ.get(\"DB_CACHE_PASSWORD\"),\n        'HOST': os.environ.get(\"DB_CACHE_HOST\"),\n        'PORT': os.environ.get(\"DB_CACHE_PORT\")\n    }\n}\n\n# Max connections is pool_size + max_overflow\n# Will idle at pool_size connections, overflow are for spikes in traffic\n\nDATABASE_POOL_ARGS = {\n    'max_overflow': 15,\n    'pool_size': 5,\n    'recycle': 300\n}\n\nDATABASE_ROUTERS = ['uclapi.dbrouters.ModelRouter']\n\nRAVEN_CONFIG = {\n    'dsn': os.environ.get(\"SENTRY_DSN\"),\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',  # noqa\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',  # noqa\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',  # noqa\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',  # noqa\n    },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = False\n\n# Cross Origin settings\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_URLS_REGEX = r'^/roombookings/.*$'\n\n# Fair use policy\nfair_use_policy_path = os.path.join(\n    BASE_DIR,\n    'uclapi/UCLAPIAcceptableUsePolicy.txt'\n)\nwith open(fair_use_policy_path, 'r', encoding='utf-8') as fp:\n    FAIR_USE_POLICY = list(fp)\n\nREDIS_UCLAPI_HOST = os.environ[\"REDIS_UCLAPI_HOST\"]\n\n# Celery Settings\nCELERY_BROKER_URL = 'redis://' + REDIS_UCLAPI_HOST\nCELERY_ACCEPT_CONTENT = ['json']\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\n\nROOMBOOKINGS_SETID = 'LIVE-18-19'\n\n# This dictates how many Medium articles we scrape\nMEDIUM_ARTICLE_QUANTITY = 3\n\n# We need to specify a tuple of STATICFILES_DIRS instead of a\n# STATIC_ROOT so that collectstatic picks up the WebPack bundles\nSTATICFILES_DIRS = (\n    os.path.join(BASE_DIR, 'static'),\n)\n\n# S3 file storage settings\n# There are three scenarios to consider:\n# 1) Local development\n#    In local dev,  AWS_S3_STATICS = False\n#                   AWS_S3_STATICS_CREDENTIALS_ENABLED = False\n#    These allow you to use local statics using /static/ in the\n#    same way as you would normally.\n# 2) Production\n#    In prod,       AWS_S3_STATICS = True\n#                   AWS_S3_STATICS_CREDENTIALS_ENABLED = False\n#    This means that S3 statics will be used, but no creds are\n#    needed on the boxes because web servers should never do\n#    uploads to the remote S3 bucket.\n# 3) Deployment\n#    In deployment, AWS_S3_STATICS = True\n#                   AWS_S3_STATICS_CREDENTIALS_ENABLED = True\n#    This will be done either from CI/CD or from the computer\n#    of a person who has permission to upload new statics to\n#    S3.\n\nif strtobool(os.environ.get(\"AWS_S3_STATICS\", \"False\")):\n    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n    AWS_STORAGE_BUCKET_NAME = os.environ[\"AWS_S3_BUCKET_NAME\"]\n    AWS_LOCATION = os.environ[\"AWS_S3_BUCKET_PATH\"]\n    AWS_S3_REGION_NAME = os.environ[\"AWS_S3_REGION\"]\n\n    # This is a hack to not require AWS Access Credentials\n    # when the system is running in the Cloud. This avoids us from\n    # needing to store AWS credentials.\n    # https://github.com/jschneier/django-storages/issues/254#issuecomment-329813295  # noqa\n    AWS_S3_CUSTOM_DOMAIN = \"{}.s3.amazonaws.com\".format(\n        AWS_STORAGE_BUCKET_NAME\n    )\n\n    # We set the default ACL data on all stacks we upload to public-read\n    # so that the files are world readable.\n    # This is required for the statics to be served up directly.\n    # Often this is a security risk, but in this case it's\n    # actually required to serve the website.\n    AWS_DEFAULT_ACL = \"public-read\"\n\n    # If credentials are enabled, collectstatic can do uploads\n    if strtobool(os.environ[\"AWS_S3_STATICS_CREDENTIALS_ENABLED\"]):\n        AWS_ACCESS_KEY_ID = os.environ[\"AWS_ACCESS_KEY_ID\"]\n        AWS_SECRET_ACCESS_KEY = os.environ[\"AWS_ACCESS_SECRET\"]\n        AWS_S3_OBJECT_PARAMETERS = {\n            'CacheControl': 'max-age=86400',\n        }\n        AWS_S3_ENCRYPTION = False\n    else:\n        AWS_QUERYSTRING_AUTH = False\n\n    # Since we are hosting on AWS, we should set the Static URL to it\n    STATIC_URL = \"{}/{}\".format(\n        AWS_S3_CUSTOM_DOMAIN,\n        AWS_LOCATION\n    )\n    # Set up the WebPack loader for remote loading\n    WEBPACK_LOADER = {\n        'DEFAULT': {\n            'CACHE': not DEBUG,\n            'BUNDLE_DIR_NAME': './',  # must end with slash\n            'STATS_URL': \"https://{}webpack-stats.json\".format(\n                STATIC_URL\n            ),\n            'POLL_INTERVAL': 0.1,\n            'TIMEOUT': None,\n            'IGNORE': [r'.+\\.hot-update.js', r'.+\\.map']\n        }\n    }\nelse:\n    # https://docs.djangoproject.com/en/1.10/howto/static-files/\n    # The default Static URL is /static/ which is fine for when statics\n    # have been built and placed into their respective folders.\n    STATIC_URL = os.environ.get(\"STATIC_URL\", '/static/')\n\n    # Set up the WebPack loader for local loading\n    WEBPACK_LOADER = {\n        'DEFAULT': {\n            'CACHE': not DEBUG,\n            'BUNDLE_DIR_NAME': './',  # must end with slash\n            'STATS_FILE': os.path.join(\n                BASE_DIR,\n                'static',\n                'webpack-stats.json'\n            ),\n            'POLL_INTERVAL': 0.1,\n            'TIMEOUT': None,\n            'IGNORE': [r'.+\\.hot-update.js', r'.+\\.map']\n        }\n    }\n", "path": "backend/uclapi/uclapi/settings.py"}]}