>From cd2391f295af96646ee49c2b5e7f37c8442d8547 Mon Sep 17 00:00:00 2001
From: Abhishek Koneru <akoneru@redhat.com>
Date: Mon, 20 May 2013 16:07:21 -0400
Subject: [PATCH] Use 'with' construct for file operations.

Replace try-except with with construct in python code in applicable
places where there is no exception handling required. Also added
finally block to close resources opened in a try except block.

Ticket #560
---
 base/kra/functional/drmclient.py      |   16 ++++++++------
 base/server/src/engine/pkihelper.py   |   30 +++++++++++++-------------
 base/server/src/engine/pkimanifest.py |   37 +++++++++++++++------------------
 base/server/src/engine/pkiparser.py   |   31 +++++++++++++--------------
 4 files changed, 56 insertions(+), 58 deletions(-)

diff --git a/base/kra/functional/drmclient.py b/base/kra/functional/drmclient.py
index ea9514dce625bf59b4d51c5746de6ebb005b0bd4..4622c539f2dbe00df0c75bf66e1a68ed2f5ba3ef 100644
--- a/base/kra/functional/drmclient.py
+++ b/base/kra/functional/drmclient.py
@@ -318,7 +318,8 @@ def https_request(host, port, url, secdir, password, nickname, operation, args,
         elif kw != None:
             post = urlencode(kw)
             request_headers = {"Content-type": "application/x-www-form-urlencoded",
-                               "Accept": "text/plain"}     
+                               "Accept": "text/plain"}
+    conn = None
     try:
         conn = nsslib.NSSConnection(host, port, dbdir=secdir)
         conn.set_debuglevel(0)
@@ -338,9 +339,11 @@ def https_request(host, port, url, secdir, password, nickname, operation, args,
         http_reason_phrase = unicode(res.reason, 'utf-8')
         http_headers = res.msg.dict
         http_body = res.read()
-        conn.close()
     except Exception, e:
         raise NetworkError(uri=uri, error=str(e))
+    finally:
+        if conn is not None:
+            conn.close()
 
     return http_status, http_reason_phrase, http_headers, http_body
 
@@ -380,9 +383,11 @@ def http_request(host, port, url, operation, args):
         http_reason_phrase = unicode(res.reason, 'utf-8')
         http_headers = res.msg.dict
         http_body = res.read()
-        conn.close()
     except NSPRError, e:
         raise NetworkError(uri=uri, error=str(e))
+    finally:
+        if conn is not None:
+            conn.close()
 
     logging.debug('request status %d',        http_status)
     logging.debug('request reason_phrase %r', http_reason_phrase)
@@ -411,9 +416,8 @@ class kra:
         self.transport_cert_nickname = kra_nickname
         self.mechanism = nss.CKM_DES3_CBC_PAD
         try:
-            f = open(self.pwd_file, "r")
-            self.password = f.readline().strip()
-            f.close()
+            with open(self.pwd_file, "r") as f: 
+                self.password = f.readline().strip()
         except IOError:
             self.password = ''
             
diff --git a/base/server/src/engine/pkihelper.py b/base/server/src/engine/pkihelper.py
index df36583079cea16a0d199de3e0007bc7a1a12e12..9c775f65d0bd736d6befab281939c1deb5a2fbd8 100644
--- a/base/server/src/engine/pkihelper.py
+++ b/base/server/src/engine/pkihelper.py
@@ -1692,17 +1692,16 @@ class file:
                 config.pki_log.info(log.PKIHELPER_COPY_WITH_SLOT_SUBSTITUTION_2,
                                     old_name, new_name,
                                     extra = config.PKI_INDENTATION_LEVEL_2)
-                FILE = open(new_name, "w")
-                for line in fileinput.FileInput(old_name):
-                    for slot in slots:
-                        if slot != '__name__' and slots[slot] in line:
-                            config.pki_log.debug(
-                                log.PKIHELPER_SLOT_SUBSTITUTION_2,
-                                slots[slot], master[slot],
-                                extra = config.PKI_INDENTATION_LEVEL_3)
-                            line = line.replace(slots[slot], master[slot])
-                    FILE.write(line)
-                FILE.close()
+                with open(new_name, "w") as FILE:
+                    for line in fileinput.FileInput(old_name):
+                        for slot in slots:
+                            if slot != '__name__' and slots[slot] in line:
+                                config.pki_log.debug(
+                                    log.PKIHELPER_SLOT_SUBSTITUTION_2,
+                                    slots[slot], master[slot],
+                                    extra = config.PKI_INDENTATION_LEVEL_3)
+                                line = line.replace(slots[slot], master[slot])
+                        FILE.write(line)
                 if uid == None:
                     uid = identity.get_uid()
                 if gid == None:
@@ -1750,11 +1749,10 @@ class file:
                 config.pki_log.info(log.PKIHELPER_NOISE_FILE_2, name, bytes,
                                     extra = config.PKI_INDENTATION_LEVEL_2)
                 open(name, "w").close()
-                FILE = open(name, "w")
-                noise = ''.join(random.choice(string.ascii_letters + \
-                        string.digits) for x in range(bytes))
-                FILE.write(noise)
-                FILE.close()
+                with open(name, "w") as FILE:
+                    noise = ''.join(random.choice(string.ascii_letters +\
+                                    string.digits) for x in range(bytes))
+                    FILE.write(noise)
                 # chmod <perms> <name>
                 config.pki_log.debug(log.PKIHELPER_CHMOD_2, perms, name,
                                      extra = config.PKI_INDENTATION_LEVEL_3)
diff --git a/base/server/src/engine/pkimanifest.py b/base/server/src/engine/pkimanifest.py
index f53b76492cbc8aa50033d8307f192e545c900dba..addc5a7d8ffe2c742530c37a2410353909dafbc0 100644
--- a/base/server/src/engine/pkimanifest.py
+++ b/base/server/src/engine/pkimanifest.py
@@ -38,13 +38,13 @@ RECORD_TYPE_SYMLINK = "symlink"
 
 # PKI Deployment Manifest Record Class
 class record(object):
-    __slots__= "name",\
-               "type",\
-               "user",\
-               "group",\
-               "uid",\
-               "gid",\
-               "permissions",\
+    __slots__ = "name", \
+               "type", \
+               "user", \
+               "group", \
+               "uid", \
+               "gid", \
+               "permissions", \
                "acls",
 
     def items(self):
@@ -73,29 +73,26 @@ class file:
 
     def write(self):
         try:
-            fd = open(self.filename, "wt")
-            c = csv.writer(fd)
-            for record in database:
-                c.writerow(tuple(record))
-            fd.close()
+            with open(self.filename, "wt") as fd:
+                c = csv.writer(fd)
+                for record in database:
+                    c.writerow(tuple(record))
         except IOError as exc:
             config.pki_log.error(log.PKI_IOERROR_1, exc,
-                                 extra=config.PKI_INDENTATION_LEVEL_1)
+                                 extra = config.PKI_INDENTATION_LEVEL_1)
             raise
 
     def read(self):
         try:
-            fd = open(self.filename, "rt")
-            cr = csv.reader(fd)
-            for row in cr:
-                print tuple(row)
-            fd.close()
+            with open(self.filename, "rt") as fd:
+                cr = csv.reader(fd)
+                for row in cr:
+                    print tuple(row)
         except IOError as exc:
             config.pki_log.error(log.PKI_IOERROR_1, exc,
-                                 extra=config.PKI_INDENTATION_LEVEL_1)
+                                 extra = config.PKI_INDENTATION_LEVEL_1)
             raise
 
-
 # PKI Deployment Global Named Tuples
 database = []
 file = file()
diff --git a/base/server/src/engine/pkiparser.py b/base/server/src/engine/pkiparser.py
index 65eb2a4570ed817382ff93acf42828c91cb34415..40f29f188d2c19b2b672ded09bff051eaa8107b3 100644
--- a/base/server/src/engine/pkiparser.py
+++ b/base/server/src/engine/pkiparser.py
@@ -208,22 +208,21 @@ class PKIConfigParser:
     @staticmethod
     def read_simple_configuration_file(filename):
         values = {}
-        f = open(filename)
-        for line in f:
-            # First, remove comments:
-            if PKIConfigParser.COMMENT_CHAR in line:
-                # split on comment char, keep only the part before
-                line, comment = line.split(PKIConfigParser.COMMENT_CHAR, 1)
-            # Second, find lines with an name=value:
-            if PKIConfigParser.OPTION_CHAR in line:
-                # split on name char:
-                name, value = line.split(PKIConfigParser.OPTION_CHAR, 1)
-                # strip spaces:
-                name = name.strip()
-                value = value.strip()
-                # store in dictionary:
-                values[name] = value
-        f.close()
+        with open(filename) as f:
+            for line in f:
+                # First, remove comments:
+                if PKIConfigParser.COMMENT_CHAR in line:
+                    # split on comment char, keep only the part before
+                    line, comment = line.split(PKIConfigParser.COMMENT_CHAR, 1)
+                # Second, find lines with an name=value:
+                if PKIConfigParser.OPTION_CHAR in line:
+                    # split on name char:
+                    name, value = line.split(PKIConfigParser.OPTION_CHAR, 1)
+                    # strip spaces:
+                    name = name.strip()
+                    value = value.strip()
+                    # store in dictionary:
+                    values[name] = value
         return values
 
 
-- 
1.7.10.2

