Coverage for /Users/davegaeddert/Developer/dropseed/plain/plain/plain/utils/connection.py: 55%
55 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-23 11:16 -0600
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-23 11:16 -0600
1from threading import local
3from plain.runtime import settings as plain_settings
4from plain.utils.functional import cached_property
7class ConnectionProxy:
8 """Proxy for accessing a connection object's attributes."""
10 def __init__(self, connections, alias):
11 self.__dict__["_connections"] = connections
12 self.__dict__["_alias"] = alias
14 def __getattr__(self, item):
15 return getattr(self._connections[self._alias], item)
17 def __setattr__(self, name, value):
18 return setattr(self._connections[self._alias], name, value)
20 def __delattr__(self, name):
21 return delattr(self._connections[self._alias], name)
23 def __contains__(self, key):
24 return key in self._connections[self._alias]
26 def __eq__(self, other):
27 return self._connections[self._alias] == other
30class ConnectionDoesNotExist(Exception):
31 pass
34class BaseConnectionHandler:
35 settings_name = None
36 exception_class = ConnectionDoesNotExist
38 def __init__(self, settings=None):
39 self._settings = settings
40 self._connections = local()
42 @cached_property
43 def settings(self):
44 self._settings = self.configure_settings(self._settings)
45 return self._settings
47 def configure_settings(self, settings):
48 if settings is None:
49 settings = getattr(plain_settings, self.settings_name)
50 return settings
52 def create_connection(self, alias):
53 raise NotImplementedError("Subclasses must implement create_connection().")
55 def __getitem__(self, alias):
56 try:
57 return getattr(self._connections, alias)
58 except AttributeError:
59 if alias not in self.settings:
60 raise self.exception_class(f"The connection '{alias}' doesn't exist.")
61 conn = self.create_connection(alias)
62 setattr(self._connections, alias, conn)
63 return conn
65 def __setitem__(self, key, value):
66 setattr(self._connections, key, value)
68 def __delitem__(self, key):
69 delattr(self._connections, key)
71 def __iter__(self):
72 return iter(self.settings)
74 def all(self, initialized_only=False):
75 return [
76 self[alias]
77 for alias in self
78 # If initialized_only is True, return only initialized connections.
79 if not initialized_only or hasattr(self._connections, alias)
80 ]
82 def close_all(self):
83 for conn in self.all(initialized_only=True):
84 conn.close()