@@ -59,17 +59,8 @@ class CertificateFile(object):
5959 that with the ``build`` method.
6060 """
6161 def __init__ (self ):
62- self ._path = None
63-
64- @property
65- def path (self ):
66- """
67- The path to the file containing the PEM data.
68- """
69- if self ._path is None :
70- self .build ()
71-
72- return self ._path
62+ self .path = None
63+ self ._fobj = None
7364
7465 def build (self ):
7566 """
@@ -79,48 +70,61 @@ def build(self):
7970 file with the updated values. Otherwise, will allocate a temporary
8071 file.
8172 """
82- if self ._path is None :
73+ if self ._fobj is not None :
74+ self ._fobj .close ()
75+ self ._fobj = None
76+
77+ if self .path is None :
8378 self ._get_tempfile ()
84- assert self ._path is not None
79+ assert self .path is not None
8580
86- with open (self ._path , 'wb' ) as f :
81+ with open (self .path , 'wb' ) as f :
8782 f .write (certificate_string ())
8883 f .truncate ()
8984
90- def close (self ):
85+ self ._fobj = open (self .path , 'rb' )
86+
87+ def destroy (self ):
9188 """
9289 Destroys the temporary file.
9390 """
94- if self ._path is not None :
95- self ._destroy_tempfile ()
91+ if self ._fobj is not None :
92+ self ._fobj .close ()
93+ self ._fobj = None
9694
97- self ._path = None
95+ if self .path is not None :
96+ self ._destroy_tempfile ()
97+ self .path = None
9898
9999 def _get_tempfile (self ):
100100 """
101101 Allocates a temporary file.
102102 """
103103 fd , path = tempfile .mkstemp (suffix = '.pem' )
104104
105- # Don't hold the file open, we don't need it.
105+ # Don't hold the file descriptor open, we don't need it.
106106 os .close (fd )
107- self ._path = path
107+ self .path = path
108108
109109 def _destroy_tempfile (self ):
110110 """
111111 Actually destroys the temporary file.
112112 """
113- os .remove (self ._path )
113+ os .remove (self .path )
114114
115115 # Context Manager Protocol
116116 def __enter__ (self ):
117117 self .build ()
118118 return self
119119
120120 def __exit__ (self , type , value , traceback ):
121- self .close ()
121+ self .destroy ()
122122 return False # Never swallow exceptions
123123
124124 # Proxy
125125 def __getattr__ (self , name ):
126126 return getattr (self ._fobj , name )
127+
128+ # Annoyingly, a finalizer
129+ def __del__ (self ):
130+ self .destroy ()
0 commit comments