We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
IConfigurer plugin load order
**CKAN version**
(all)

**Describe the bug**
`update_config` runs through all IConfigurer plugins from first to last calling `plugin.update_config`. The pattern for other interfaces is that the "first plugin wins", but this is difficult to implement when later plugins override values from earlier ones in the list.

**Steps to reproduce**
Enable two plugins that set the same config value using IConfigurer

**Expected behavior**
First plugin value should win, like with other interfaces.

**Additional details**
ckanext-envvars recommends adding `envvars` last in the list of plugins, which makes sense but if other plugins depend on/override values configured in envvars (e.g. ckanext-scheming) they won't be available at `update_config` time.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ckan/config/environment.py`
Content:
```
1 # encoding: utf-8
2 '''CKAN environment configuration'''
3 from __future__ import annotations
4 
5 import os
6 import logging
7 import warnings
8 import pytz
9 
10 from typing import Union, cast
11 
12 import sqlalchemy
13 
14 import ckan.model as model
15 import ckan.plugins as p
16 import ckan.lib.plugins as lib_plugins
17 import ckan.lib.helpers as helpers
18 import ckan.lib.app_globals as app_globals
19 from ckan.lib.redis import is_redis_available
20 import ckan.lib.search as search
21 import ckan.logic as logic
22 import ckan.authz as authz
23 from ckan.lib.webassets_tools import webassets_init
24 from ckan.lib.i18n import build_js_translations
25 
26 from ckan.common import CKANConfig, config, config_declaration
27 from ckan.exceptions import CkanConfigurationException
28 from ckan.types import Config
29 
30 log = logging.getLogger(__name__)
31 
32 # Suppress benign warning 'Unbuilt egg for setuptools'
33 warnings.simplefilter('ignore', UserWarning)
34 
35 
36 def load_environment(conf: Union[Config, CKANConfig]):
37     """
38     Configure the Pylons environment via the ``pylons.config`` object. This
39     code should only need to be run once.
40     """
41     os.environ['CKAN_CONFIG'] = cast(str, conf['__file__'])
42 
43     valid_base_public_folder_names = ['public', 'public-bs3']
44     static_files = conf.get('ckan.base_public_folder', 'public')
45     conf['ckan.base_public_folder'] = static_files
46 
47     if static_files not in valid_base_public_folder_names:
48         raise CkanConfigurationException(
49             'You provided an invalid value for ckan.base_public_folder. '
50             'Possible values are: "public" and "public-bs3".'
51         )
52 
53     log.info('Loading static files from %s' % static_files)
54 
55     # Initialize main CKAN config object
56     config.update(conf)
57 
58     # Setup the SQLAlchemy database engine
59     # Suppress a couple of sqlalchemy warnings
60     msgs = ['^Unicode type received non-unicode bind param value',
61             "^Did not recognize type 'BIGINT' of column 'size'",
62             "^Did not recognize type 'tsvector' of column 'search_vector'"
63             ]
64     for msg in msgs:
65         warnings.filterwarnings('ignore', msg, sqlalchemy.exc.SAWarning)
66 
67     # load all CKAN plugins
68     p.load_all()
69 
70     # Check Redis availability
71     if not is_redis_available():
72         log.critical('Could not connect to Redis.')
73 
74     app_globals.reset()
75 
76     # Build JavaScript translations. Must be done after plugins have
77     # been loaded.
78     build_js_translations()
79 
80 
81 # A mapping of config settings that can be overridden by env vars.
82 # Note: Do not remove the following lines, they are used in the docs
83 # Start CONFIG_FROM_ENV_VARS
84 CONFIG_FROM_ENV_VARS: dict[str, str] = {
85     'sqlalchemy.url': 'CKAN_SQLALCHEMY_URL',
86     'ckan.datastore.write_url': 'CKAN_DATASTORE_WRITE_URL',
87     'ckan.datastore.read_url': 'CKAN_DATASTORE_READ_URL',
88     'ckan.redis.url': 'CKAN_REDIS_URL',
89     'solr_url': 'CKAN_SOLR_URL',
90     'solr_user': 'CKAN_SOLR_USER',
91     'solr_password': 'CKAN_SOLR_PASSWORD',
92     'ckan.site_id': 'CKAN_SITE_ID',
93     'ckan.site_url': 'CKAN_SITE_URL',
94     'ckan.storage_path': 'CKAN_STORAGE_PATH',
95     'ckan.datapusher.url': 'CKAN_DATAPUSHER_URL',
96     'smtp.server': 'CKAN_SMTP_SERVER',
97     'smtp.starttls': 'CKAN_SMTP_STARTTLS',
98     'smtp.user': 'CKAN_SMTP_USER',
99     'smtp.password': 'CKAN_SMTP_PASSWORD',
100     'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM',
101     'ckan.max_resource_size': 'CKAN_MAX_UPLOAD_SIZE_MB'
102 }
103 # End CONFIG_FROM_ENV_VARS
104 
105 
106 def update_config() -> None:
107     ''' This code needs to be run when the config is changed to take those
108     changes into account. It is called whenever a plugin is loaded as the
109     plugin might have changed the config values (for instance it might
110     change ckan.site_url) '''
111 
112     config_declaration.setup()
113     config_declaration.make_safe(config)
114     config_declaration.normalize(config)
115 
116     webassets_init()
117 
118     for plugin in p.PluginImplementations(p.IConfigurer):
119         # must do update in place as this does not work:
120         # config = plugin.update_config(config)
121         plugin.update_config(config)
122 
123     for option in CONFIG_FROM_ENV_VARS:
124         from_env = os.environ.get(CONFIG_FROM_ENV_VARS[option], None)
125         if from_env:
126             config[option] = from_env
127 
128     if config.get_value("config.mode") == "strict":
129         _, errors = config_declaration.validate(config)
130         if errors:
131             msg = "\n".join(
132                 "{}: {}".format(key, "; ".join(issues))
133                 for key, issues in errors.items()
134             )
135             raise CkanConfigurationException(msg)
136 
137     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
138 
139     site_url = config.get_value('ckan.site_url')
140     if not site_url:
141         raise RuntimeError(
142             'ckan.site_url is not configured and it must have a value.'
143             ' Please amend your .ini file.')
144     if not site_url.lower().startswith('http'):
145         raise RuntimeError(
146             'ckan.site_url should be a full URL, including the schema '
147             '(http or https)')
148     # Remove backslash from site_url if present
149     config['ckan.site_url'] = site_url.rstrip('/')
150 
151     display_timezone = config.get_value('ckan.display_timezone')
152     if (display_timezone and
153             display_timezone != 'server' and
154             display_timezone not in pytz.all_timezones):
155         raise CkanConfigurationException(
156             "ckan.display_timezone is not 'server' or a valid timezone"
157         )
158 
159     # Init SOLR settings and check if the schema is compatible
160     # from ckan.lib.search import SolrSettings, check_solr_schema_version
161 
162     # lib.search is imported here as we need the config enabled and parsed
163     search.SolrSettings.init(config.get_value('solr_url'),
164                              config.get_value('solr_user'),
165                              config.get_value('solr_password'))
166     search.check_solr_schema_version()
167 
168     lib_plugins.reset_package_plugins()
169     lib_plugins.register_package_plugins()
170     lib_plugins.reset_group_plugins()
171     lib_plugins.register_group_plugins()
172 
173     # initialise the globals
174     app_globals.app_globals._init()
175 
176     helpers.load_plugin_helpers()
177 
178     # Templates and CSS loading from configuration
179     valid_base_templates_folder_names = ['templates', 'templates-bs3']
180     templates = config.get('ckan.base_templates_folder', 'templates')
181     config['ckan.base_templates_folder'] = templates
182 
183     if templates not in valid_base_templates_folder_names:
184         raise CkanConfigurationException(
185             'You provided an invalid value for ckan.base_templates_folder. '
186             'Possible values are: "templates" and "templates-bs3".'
187         )
188 
189     jinja2_templates_path = os.path.join(root, templates)
190     log.info('Loading templates from %s' % jinja2_templates_path)
191     template_paths = [jinja2_templates_path]
192 
193     extra_template_paths = config.get_value('extra_template_paths')
194     if extra_template_paths:
195         # must be first for them to override defaults
196         template_paths = extra_template_paths.split(',') + template_paths
197     config['computed_template_paths'] = template_paths
198 
199     # Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)
200     # to eliminate database errors due to stale pooled connections
201     config.setdefault('sqlalchemy.pool_pre_ping', True)
202     # Initialize SQLAlchemy
203     engine = sqlalchemy.engine_from_config(config)
204     model.init_model(engine)
205 
206     for plugin in p.PluginImplementations(p.IConfigurable):
207         plugin.configure(config)
208 
209     # clear other caches
210     logic.clear_actions_cache()
211     logic.clear_validators_cache()
212     authz.clear_auth_functions_cache()
213 
214     # Here we create the site user if they are not already in the database
215     try:
216         logic.get_action('get_site_user')({'ignore_auth': True}, {})
217     except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):
218         # The database is not yet initialised. It happens in `ckan db init`
219         pass
220     except sqlalchemy.exc.IntegrityError:
221         # Race condition, user already exists.
222         pass
223 
224     # Close current session and open database connections to ensure a clean
225     # clean environment even if an error occurs later on
226     model.Session.remove()
227     model.Session.bind.dispose()
228
```
--- 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/ckan/config/environment.py b/ckan/config/environment.py
--- a/ckan/config/environment.py
+++ b/ckan/config/environment.py
@@ -115,7 +115,7 @@
 
     webassets_init()
 
-    for plugin in p.PluginImplementations(p.IConfigurer):
+    for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):
         # must do update in place as this does not work:
         # config = plugin.update_config(config)
         plugin.update_config(config)

{"golden_diff": "diff --git a/ckan/config/environment.py b/ckan/config/environment.py\n--- a/ckan/config/environment.py\n+++ b/ckan/config/environment.py\n@@ -115,7 +115,7 @@\n \n     webassets_init()\n \n-    for plugin in p.PluginImplementations(p.IConfigurer):\n+    for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):\n         # must do update in place as this does not work:\n         # config = plugin.update_config(config)\n         plugin.update_config(config)\n", "issue": "IConfigurer plugin load order\n**CKAN version**\r\n(all)\r\n\r\n**Describe the bug**\r\n`update_config` runs through all IConfigurer plugins from first to last calling `plugin.update_config`. The pattern for other interfaces is that the \"first plugin wins\", but this is difficult to implement when later plugins override values from earlier ones in the list.\r\n\r\n**Steps to reproduce**\r\nEnable two plugins that set the same config value using IConfigurer\r\n\r\n**Expected behavior**\r\nFirst plugin value should win, like with other interfaces.\r\n\r\n**Additional details**\r\nckanext-envvars recommends adding `envvars` last in the list of plugins, which makes sense but if other plugins depend on/override values configured in envvars (e.g. ckanext-scheming) they won't be available at `update_config` time.\n", "before_files": [{"content": "# encoding: utf-8\n'''CKAN environment configuration'''\nfrom __future__ import annotations\n\nimport os\nimport logging\nimport warnings\nimport pytz\n\nfrom typing import Union, cast\n\nimport sqlalchemy\n\nimport ckan.model as model\nimport ckan.plugins as p\nimport ckan.lib.plugins as lib_plugins\nimport ckan.lib.helpers as helpers\nimport ckan.lib.app_globals as app_globals\nfrom ckan.lib.redis import is_redis_available\nimport ckan.lib.search as search\nimport ckan.logic as logic\nimport ckan.authz as authz\nfrom ckan.lib.webassets_tools import webassets_init\nfrom ckan.lib.i18n import build_js_translations\n\nfrom ckan.common import CKANConfig, config, config_declaration\nfrom ckan.exceptions import CkanConfigurationException\nfrom ckan.types import Config\n\nlog = logging.getLogger(__name__)\n\n# Suppress benign warning 'Unbuilt egg for setuptools'\nwarnings.simplefilter('ignore', UserWarning)\n\n\ndef load_environment(conf: Union[Config, CKANConfig]):\n    \"\"\"\n    Configure the Pylons environment via the ``pylons.config`` object. This\n    code should only need to be run once.\n    \"\"\"\n    os.environ['CKAN_CONFIG'] = cast(str, conf['__file__'])\n\n    valid_base_public_folder_names = ['public', 'public-bs3']\n    static_files = conf.get('ckan.base_public_folder', 'public')\n    conf['ckan.base_public_folder'] = static_files\n\n    if static_files not in valid_base_public_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_public_folder. '\n            'Possible values are: \"public\" and \"public-bs3\".'\n        )\n\n    log.info('Loading static files from %s' % static_files)\n\n    # Initialize main CKAN config object\n    config.update(conf)\n\n    # Setup the SQLAlchemy database engine\n    # Suppress a couple of sqlalchemy warnings\n    msgs = ['^Unicode type received non-unicode bind param value',\n            \"^Did not recognize type 'BIGINT' of column 'size'\",\n            \"^Did not recognize type 'tsvector' of column 'search_vector'\"\n            ]\n    for msg in msgs:\n        warnings.filterwarnings('ignore', msg, sqlalchemy.exc.SAWarning)\n\n    # load all CKAN plugins\n    p.load_all()\n\n    # Check Redis availability\n    if not is_redis_available():\n        log.critical('Could not connect to Redis.')\n\n    app_globals.reset()\n\n    # Build JavaScript translations. Must be done after plugins have\n    # been loaded.\n    build_js_translations()\n\n\n# A mapping of config settings that can be overridden by env vars.\n# Note: Do not remove the following lines, they are used in the docs\n# Start CONFIG_FROM_ENV_VARS\nCONFIG_FROM_ENV_VARS: dict[str, str] = {\n    'sqlalchemy.url': 'CKAN_SQLALCHEMY_URL',\n    'ckan.datastore.write_url': 'CKAN_DATASTORE_WRITE_URL',\n    'ckan.datastore.read_url': 'CKAN_DATASTORE_READ_URL',\n    'ckan.redis.url': 'CKAN_REDIS_URL',\n    'solr_url': 'CKAN_SOLR_URL',\n    'solr_user': 'CKAN_SOLR_USER',\n    'solr_password': 'CKAN_SOLR_PASSWORD',\n    'ckan.site_id': 'CKAN_SITE_ID',\n    'ckan.site_url': 'CKAN_SITE_URL',\n    'ckan.storage_path': 'CKAN_STORAGE_PATH',\n    'ckan.datapusher.url': 'CKAN_DATAPUSHER_URL',\n    'smtp.server': 'CKAN_SMTP_SERVER',\n    'smtp.starttls': 'CKAN_SMTP_STARTTLS',\n    'smtp.user': 'CKAN_SMTP_USER',\n    'smtp.password': 'CKAN_SMTP_PASSWORD',\n    'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM',\n    'ckan.max_resource_size': 'CKAN_MAX_UPLOAD_SIZE_MB'\n}\n# End CONFIG_FROM_ENV_VARS\n\n\ndef update_config() -> None:\n    ''' This code needs to be run when the config is changed to take those\n    changes into account. It is called whenever a plugin is loaded as the\n    plugin might have changed the config values (for instance it might\n    change ckan.site_url) '''\n\n    config_declaration.setup()\n    config_declaration.make_safe(config)\n    config_declaration.normalize(config)\n\n    webassets_init()\n\n    for plugin in p.PluginImplementations(p.IConfigurer):\n        # must do update in place as this does not work:\n        # config = plugin.update_config(config)\n        plugin.update_config(config)\n\n    for option in CONFIG_FROM_ENV_VARS:\n        from_env = os.environ.get(CONFIG_FROM_ENV_VARS[option], None)\n        if from_env:\n            config[option] = from_env\n\n    if config.get_value(\"config.mode\") == \"strict\":\n        _, errors = config_declaration.validate(config)\n        if errors:\n            msg = \"\\n\".join(\n                \"{}: {}\".format(key, \"; \".join(issues))\n                for key, issues in errors.items()\n            )\n            raise CkanConfigurationException(msg)\n\n    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n    site_url = config.get_value('ckan.site_url')\n    if not site_url:\n        raise RuntimeError(\n            'ckan.site_url is not configured and it must have a value.'\n            ' Please amend your .ini file.')\n    if not site_url.lower().startswith('http'):\n        raise RuntimeError(\n            'ckan.site_url should be a full URL, including the schema '\n            '(http or https)')\n    # Remove backslash from site_url if present\n    config['ckan.site_url'] = site_url.rstrip('/')\n\n    display_timezone = config.get_value('ckan.display_timezone')\n    if (display_timezone and\n            display_timezone != 'server' and\n            display_timezone not in pytz.all_timezones):\n        raise CkanConfigurationException(\n            \"ckan.display_timezone is not 'server' or a valid timezone\"\n        )\n\n    # Init SOLR settings and check if the schema is compatible\n    # from ckan.lib.search import SolrSettings, check_solr_schema_version\n\n    # lib.search is imported here as we need the config enabled and parsed\n    search.SolrSettings.init(config.get_value('solr_url'),\n                             config.get_value('solr_user'),\n                             config.get_value('solr_password'))\n    search.check_solr_schema_version()\n\n    lib_plugins.reset_package_plugins()\n    lib_plugins.register_package_plugins()\n    lib_plugins.reset_group_plugins()\n    lib_plugins.register_group_plugins()\n\n    # initialise the globals\n    app_globals.app_globals._init()\n\n    helpers.load_plugin_helpers()\n\n    # Templates and CSS loading from configuration\n    valid_base_templates_folder_names = ['templates', 'templates-bs3']\n    templates = config.get('ckan.base_templates_folder', 'templates')\n    config['ckan.base_templates_folder'] = templates\n\n    if templates not in valid_base_templates_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_templates_folder. '\n            'Possible values are: \"templates\" and \"templates-bs3\".'\n        )\n\n    jinja2_templates_path = os.path.join(root, templates)\n    log.info('Loading templates from %s' % jinja2_templates_path)\n    template_paths = [jinja2_templates_path]\n\n    extra_template_paths = config.get_value('extra_template_paths')\n    if extra_template_paths:\n        # must be first for them to override defaults\n        template_paths = extra_template_paths.split(',') + template_paths\n    config['computed_template_paths'] = template_paths\n\n    # Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)\n    # to eliminate database errors due to stale pooled connections\n    config.setdefault('sqlalchemy.pool_pre_ping', True)\n    # Initialize SQLAlchemy\n    engine = sqlalchemy.engine_from_config(config)\n    model.init_model(engine)\n\n    for plugin in p.PluginImplementations(p.IConfigurable):\n        plugin.configure(config)\n\n    # clear other caches\n    logic.clear_actions_cache()\n    logic.clear_validators_cache()\n    authz.clear_auth_functions_cache()\n\n    # Here we create the site user if they are not already in the database\n    try:\n        logic.get_action('get_site_user')({'ignore_auth': True}, {})\n    except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):\n        # The database is not yet initialised. It happens in `ckan db init`\n        pass\n    except sqlalchemy.exc.IntegrityError:\n        # Race condition, user already exists.\n        pass\n\n    # Close current session and open database connections to ensure a clean\n    # clean environment even if an error occurs later on\n    model.Session.remove()\n    model.Session.bind.dispose()\n", "path": "ckan/config/environment.py"}], "after_files": [{"content": "# encoding: utf-8\n'''CKAN environment configuration'''\nfrom __future__ import annotations\n\nimport os\nimport logging\nimport warnings\nimport pytz\n\nfrom typing import Union, cast\n\nimport sqlalchemy\n\nimport ckan.model as model\nimport ckan.plugins as p\nimport ckan.lib.plugins as lib_plugins\nimport ckan.lib.helpers as helpers\nimport ckan.lib.app_globals as app_globals\nfrom ckan.lib.redis import is_redis_available\nimport ckan.lib.search as search\nimport ckan.logic as logic\nimport ckan.authz as authz\nfrom ckan.lib.webassets_tools import webassets_init\nfrom ckan.lib.i18n import build_js_translations\n\nfrom ckan.common import CKANConfig, config, config_declaration\nfrom ckan.exceptions import CkanConfigurationException\nfrom ckan.types import Config\n\nlog = logging.getLogger(__name__)\n\n# Suppress benign warning 'Unbuilt egg for setuptools'\nwarnings.simplefilter('ignore', UserWarning)\n\n\ndef load_environment(conf: Union[Config, CKANConfig]):\n    \"\"\"\n    Configure the Pylons environment via the ``pylons.config`` object. This\n    code should only need to be run once.\n    \"\"\"\n    os.environ['CKAN_CONFIG'] = cast(str, conf['__file__'])\n\n    valid_base_public_folder_names = ['public', 'public-bs3']\n    static_files = conf.get('ckan.base_public_folder', 'public')\n    conf['ckan.base_public_folder'] = static_files\n\n    if static_files not in valid_base_public_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_public_folder. '\n            'Possible values are: \"public\" and \"public-bs3\".'\n        )\n\n    log.info('Loading static files from %s' % static_files)\n\n    # Initialize main CKAN config object\n    config.update(conf)\n\n    # Setup the SQLAlchemy database engine\n    # Suppress a couple of sqlalchemy warnings\n    msgs = ['^Unicode type received non-unicode bind param value',\n            \"^Did not recognize type 'BIGINT' of column 'size'\",\n            \"^Did not recognize type 'tsvector' of column 'search_vector'\"\n            ]\n    for msg in msgs:\n        warnings.filterwarnings('ignore', msg, sqlalchemy.exc.SAWarning)\n\n    # load all CKAN plugins\n    p.load_all()\n\n    # Check Redis availability\n    if not is_redis_available():\n        log.critical('Could not connect to Redis.')\n\n    app_globals.reset()\n\n    # Build JavaScript translations. Must be done after plugins have\n    # been loaded.\n    build_js_translations()\n\n\n# A mapping of config settings that can be overridden by env vars.\n# Note: Do not remove the following lines, they are used in the docs\n# Start CONFIG_FROM_ENV_VARS\nCONFIG_FROM_ENV_VARS: dict[str, str] = {\n    'sqlalchemy.url': 'CKAN_SQLALCHEMY_URL',\n    'ckan.datastore.write_url': 'CKAN_DATASTORE_WRITE_URL',\n    'ckan.datastore.read_url': 'CKAN_DATASTORE_READ_URL',\n    'ckan.redis.url': 'CKAN_REDIS_URL',\n    'solr_url': 'CKAN_SOLR_URL',\n    'solr_user': 'CKAN_SOLR_USER',\n    'solr_password': 'CKAN_SOLR_PASSWORD',\n    'ckan.site_id': 'CKAN_SITE_ID',\n    'ckan.site_url': 'CKAN_SITE_URL',\n    'ckan.storage_path': 'CKAN_STORAGE_PATH',\n    'ckan.datapusher.url': 'CKAN_DATAPUSHER_URL',\n    'smtp.server': 'CKAN_SMTP_SERVER',\n    'smtp.starttls': 'CKAN_SMTP_STARTTLS',\n    'smtp.user': 'CKAN_SMTP_USER',\n    'smtp.password': 'CKAN_SMTP_PASSWORD',\n    'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM',\n    'ckan.max_resource_size': 'CKAN_MAX_UPLOAD_SIZE_MB'\n}\n# End CONFIG_FROM_ENV_VARS\n\n\ndef update_config() -> None:\n    ''' This code needs to be run when the config is changed to take those\n    changes into account. It is called whenever a plugin is loaded as the\n    plugin might have changed the config values (for instance it might\n    change ckan.site_url) '''\n\n    config_declaration.setup()\n    config_declaration.make_safe(config)\n    config_declaration.normalize(config)\n\n    webassets_init()\n\n    for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):\n        # must do update in place as this does not work:\n        # config = plugin.update_config(config)\n        plugin.update_config(config)\n\n    for option in CONFIG_FROM_ENV_VARS:\n        from_env = os.environ.get(CONFIG_FROM_ENV_VARS[option], None)\n        if from_env:\n            config[option] = from_env\n\n    if config.get_value(\"config.mode\") == \"strict\":\n        _, errors = config_declaration.validate(config)\n        if errors:\n            msg = \"\\n\".join(\n                \"{}: {}\".format(key, \"; \".join(issues))\n                for key, issues in errors.items()\n            )\n            raise CkanConfigurationException(msg)\n\n    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n    site_url = config.get_value('ckan.site_url')\n    if not site_url:\n        raise RuntimeError(\n            'ckan.site_url is not configured and it must have a value.'\n            ' Please amend your .ini file.')\n    if not site_url.lower().startswith('http'):\n        raise RuntimeError(\n            'ckan.site_url should be a full URL, including the schema '\n            '(http or https)')\n    # Remove backslash from site_url if present\n    config['ckan.site_url'] = site_url.rstrip('/')\n\n    display_timezone = config.get_value('ckan.display_timezone')\n    if (display_timezone and\n            display_timezone != 'server' and\n            display_timezone not in pytz.all_timezones):\n        raise CkanConfigurationException(\n            \"ckan.display_timezone is not 'server' or a valid timezone\"\n        )\n\n    # Init SOLR settings and check if the schema is compatible\n    # from ckan.lib.search import SolrSettings, check_solr_schema_version\n\n    # lib.search is imported here as we need the config enabled and parsed\n    search.SolrSettings.init(config.get_value('solr_url'),\n                             config.get_value('solr_user'),\n                             config.get_value('solr_password'))\n    search.check_solr_schema_version()\n\n    lib_plugins.reset_package_plugins()\n    lib_plugins.register_package_plugins()\n    lib_plugins.reset_group_plugins()\n    lib_plugins.register_group_plugins()\n\n    # initialise the globals\n    app_globals.app_globals._init()\n\n    helpers.load_plugin_helpers()\n\n    # Templates and CSS loading from configuration\n    valid_base_templates_folder_names = ['templates', 'templates-bs3']\n    templates = config.get('ckan.base_templates_folder', 'templates')\n    config['ckan.base_templates_folder'] = templates\n\n    if templates not in valid_base_templates_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_templates_folder. '\n            'Possible values are: \"templates\" and \"templates-bs3\".'\n        )\n\n    jinja2_templates_path = os.path.join(root, templates)\n    log.info('Loading templates from %s' % jinja2_templates_path)\n    template_paths = [jinja2_templates_path]\n\n    extra_template_paths = config.get_value('extra_template_paths')\n    if extra_template_paths:\n        # must be first for them to override defaults\n        template_paths = extra_template_paths.split(',') + template_paths\n    config['computed_template_paths'] = template_paths\n\n    # Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)\n    # to eliminate database errors due to stale pooled connections\n    config.setdefault('sqlalchemy.pool_pre_ping', True)\n    # Initialize SQLAlchemy\n    engine = sqlalchemy.engine_from_config(config)\n    model.init_model(engine)\n\n    for plugin in p.PluginImplementations(p.IConfigurable):\n        plugin.configure(config)\n\n    # clear other caches\n    logic.clear_actions_cache()\n    logic.clear_validators_cache()\n    authz.clear_auth_functions_cache()\n\n    # Here we create the site user if they are not already in the database\n    try:\n        logic.get_action('get_site_user')({'ignore_auth': True}, {})\n    except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):\n        # The database is not yet initialised. It happens in `ckan db init`\n        pass\n    except sqlalchemy.exc.IntegrityError:\n        # Race condition, user already exists.\n        pass\n\n    # Close current session and open database connections to ensure a clean\n    # clean environment even if an error occurs later on\n    model.Session.remove()\n    model.Session.bind.dispose()\n", "path": "ckan/config/environment.py"}]}