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

1from threading import local 

2 

3from plain.runtime import settings as plain_settings 

4from plain.utils.functional import cached_property 

5 

6 

7class ConnectionProxy: 

8 """Proxy for accessing a connection object's attributes.""" 

9 

10 def __init__(self, connections, alias): 

11 self.__dict__["_connections"] = connections 

12 self.__dict__["_alias"] = alias 

13 

14 def __getattr__(self, item): 

15 return getattr(self._connections[self._alias], item) 

16 

17 def __setattr__(self, name, value): 

18 return setattr(self._connections[self._alias], name, value) 

19 

20 def __delattr__(self, name): 

21 return delattr(self._connections[self._alias], name) 

22 

23 def __contains__(self, key): 

24 return key in self._connections[self._alias] 

25 

26 def __eq__(self, other): 

27 return self._connections[self._alias] == other 

28 

29 

30class ConnectionDoesNotExist(Exception): 

31 pass 

32 

33 

34class BaseConnectionHandler: 

35 settings_name = None 

36 exception_class = ConnectionDoesNotExist 

37 

38 def __init__(self, settings=None): 

39 self._settings = settings 

40 self._connections = local() 

41 

42 @cached_property 

43 def settings(self): 

44 self._settings = self.configure_settings(self._settings) 

45 return self._settings 

46 

47 def configure_settings(self, settings): 

48 if settings is None: 

49 settings = getattr(plain_settings, self.settings_name) 

50 return settings 

51 

52 def create_connection(self, alias): 

53 raise NotImplementedError("Subclasses must implement create_connection().") 

54 

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 

64 

65 def __setitem__(self, key, value): 

66 setattr(self._connections, key, value) 

67 

68 def __delitem__(self, key): 

69 delattr(self._connections, key) 

70 

71 def __iter__(self): 

72 return iter(self.settings) 

73 

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 ] 

81 

82 def close_all(self): 

83 for conn in self.all(initialized_only=True): 

84 conn.close()