Cameron Simpson avatar Cameron Simpson committed 06ce859

cs.app.aws: .connection() context manager wrapping .connect()

Comments (0)

Files changed (1)

lib/python/cs/app/aws.py

 #       - Cameron Simpson <cs@zip.com.au> 17nov2012
 #
 
+from contextlib import contextmanager
 from threading import RLock
 from boto.ec2.connection import EC2Connection
 from cs.logutils import D
     self._lock = RLock()
     self._O_omit = ('conn', 'regions', 'instances')
 
+  @contextmanager
+  def connection(self, **kwargs):
+    conn = self.connect(**kwargs)
+    yield conn
+    conn.close()
+
   def connect(self, **kwargs):
     ''' Get a boto.ec2.connection.EC2Connection.
         Missing `aws_access_key_id`, `aws_secret_access_key`, `region`
   def regions(self):
     ''' Return a mapping from Region name to Region.
     '''
-    ec2 = self.connect(region=None)
-    RS = dict( [ (R.name, R) for R in ec2.get_all_regions() ] )
-    ec2.close()
+    with self.connection(region=None) as ec2:
+      RS = dict( [ (R.name, R) for R in ec2.get_all_regions() ] )
     return RS
 
   def region(self, name):
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.