changeset 213:1c835a7297ea

file handling: use context managers to make sure files are closed
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Wed, 04 May 2011 01:32:54 +0200
parents 74ed2b466080
children 0f501a426b50 661a57c747bd
files MoinMoin/script/maint/create_item.py MoinMoin/storage/backends/flatfile.py MoinMoin/storage/backends/fs.py MoinMoin/storage/backends/fs19.py
diffstat 4 files changed, 38 insertions(+), 42 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/script/maint/create_item.py	Wed May 04 00:02:14 2011 +0200
+++ b/MoinMoin/script/maint/create_item.py	Wed May 04 01:32:54 2011 +0200
@@ -41,7 +41,6 @@
         rev['action'] = u'SAVE'
         rev['name'] = name
         rev['mimetype'] = mimetype
-        data = open(data_file, 'rb')
-        rev.write(data.read())
-        item.commit()
-        data.close()
+        with open(data_file, 'rb') as data:
+            rev.write(data.read())
+            item.commit()
--- a/MoinMoin/storage/backends/flatfile.py	Wed May 04 00:02:14 2011 +0200
+++ b/MoinMoin/storage/backends/flatfile.py	Wed May 04 01:32:54 2011 +0200
@@ -101,7 +101,8 @@
             raise NoSuchRevisionError("No Revision #%d on Item %s" % (revno, item.name))
 
         rev = StoredRevision(item, 0)
-        data = open(revpath, 'rb').read()
+        with open(revpath, 'rb') as f:
+            data = f.read()
         rev._metadata, data = split_body(data)
         rev._metadata[ACTION] = 'SAVE'
         rev._metadata[SIZE] = len(data)
@@ -139,12 +140,11 @@
 
     def _commit_item(self, rev):
         revpath = self._rev_path(rev.item.name)
-        f = open(revpath, 'wb')
         rev._data.seek(0)
         data = rev._data.read()
         data = add_metadata_to_body(rev, data)
-        f.write(data)
-        f.close()
+        with open(revpath, 'wb') as f:
+            f.write(data)
 
     def _destroy_item(self, item):
         revpath = self._rev_path(item.name)
--- a/MoinMoin/storage/backends/fs.py	Wed May 04 00:02:14 2011 +0200
+++ b/MoinMoin/storage/backends/fs.py	Wed May 04 01:32:54 2011 +0200
@@ -224,9 +224,8 @@
                     r = c.each()
 
         filesys.rename(self._name_db + '.ndb', self._name_db)
-        nf = open(npath, mode='wb')
-        nf.write(nn)
-        nf.close()
+        with open(npath, mode='wb') as nf:
+            nf.write(nn)
 
     def _rename_item(self, item, newname):
         self._do_locked(os.path.join(self._path, 'name-mapping.lock'),
@@ -288,15 +287,13 @@
         if metadata:
             # only write metadata file if we have any
             meta = os.path.join(self._path, itemid, 'meta')
-            f = open(meta, 'wb')
-            pickle.dump(metadata, f, protocol=PICKLEPROTOCOL)
-            f.close()
+            with open(meta, 'wb') as f:
+                pickle.dump(metadata, f, protocol=PICKLEPROTOCOL)
 
         # write 'name' file of item
         npath = os.path.join(ipath, 'name')
-        nf = open(npath, mode='wb')
-        nf.write(nn)
-        nf.close()
+        with open(npath, mode='wb') as nf:
+            nf.write(nn)
 
         # make item retrievable (by putting the name-mapping in place)
         filesys.rename(self._name_db + '.ndb', self._name_db)
@@ -412,9 +409,8 @@
                     # ignore, there might not have been metadata
             else:
                 tmp = os.path.join(self._path, item._fs_item_id, 'meta.tmp')
-                f = open(tmp, 'wb')
-                pickle.dump(md, f, protocol=PICKLEPROTOCOL)
-                f.close()
+                with open(tmp, 'wb') as f:
+                    pickle.dump(md, f, protocol=PICKLEPROTOCOL)
 
                 filesys.rename(tmp, os.path.join(self._path, item._fs_item_id, 'meta'))
             item._fs_metadata_lock.release()
@@ -432,9 +428,8 @@
         if item._fs_item_id is not None:
             p = os.path.join(self._path, item._fs_item_id, 'meta')
             try:
-                f = open(p, 'rb')
-                metadata = pickle.load(f)
-                f.close()
+                with open(p, 'rb') as f:
+                    metadata = pickle.load(f)
             except IOError as err:
                 if err.errno != errno.ENOENT:
                     raise
--- a/MoinMoin/storage/backends/fs19.py	Wed May 04 00:02:14 2011 +0200
+++ b/MoinMoin/storage/backends/fs19.py	Wed May 04 01:32:54 2011 +0200
@@ -286,7 +286,8 @@
         editlogpath = self._backend._get_item_path(itemname, 'edit-log')
         self._fs_meta = {} # 'current' is the only page metadata and handled elsewhere
         try:
-            current = int(open(currentpath, 'r').read().strip()) - 1 # new api is 0-based, old is 1-based
+            with open(currentpath, 'r') as f:
+                current = int(f.read().strip()) - 1 # new api is 0-based, old is 1-based
         except (OSError, IOError):
             # no current file means no item
             raise NoSuchItemError("No such item, %r" % itemname)
@@ -333,7 +334,8 @@
         editlog = item._fs_editlog
         # we just read the page and parse it here, makes the rest of the code simpler:
         try:
-            content = codecs.open(revpath, 'r', config.charset).read()
+            with codecs.open(revpath, 'r', config.charset) as f:
+                content = f.read()
         except (IOError, OSError):
             if revno == item._fs_current and item._backend.deleted_mode == DELETED_MODE_KILL:
                 raise NoSuchRevisionError('deleted_mode wants killing/ignoring')
@@ -491,7 +493,8 @@
         if item._fs_parent_acl is not None:
             meta[ACL] = item._fs_parent_acl # XXX not needed for acl_hierarchic
         meta[MIMETYPE] = unicode(MimeType(filename=item._fs_attachname).mime_type())
-        size, hash_name, hash_digest = hash_hexdigest(open(attpath, 'rb'))
+        with open(attpath, 'rb') as f:
+            size, hash_name, hash_digest = hash_hexdigest(f)
         meta[hash_name] = hash_digest
         meta[SIZE] = size
         if item._syspages:
@@ -684,24 +687,23 @@
         self.uuid = meta[UUID] = uuid
 
     def _parse_userprofile(self, old_id):
-        meta_file = codecs.open(self._backend._get_item_path(old_id), "r", config.charset)
-        metadata = {}
-        for line in meta_file:
-            if line.startswith('#') or line.strip() == "":
-                continue
-            key, value = line.strip().split('=', 1)
-            # Decode list values
-            if key.endswith('[]'):
-                key = key[:-2]
-                value = _decode_list(value)
+        with codecs.open(self._backend._get_item_path(old_id), "r", config.charset) as meta_file:
+            metadata = {}
+            for line in meta_file:
+                if line.startswith('#') or line.strip() == "":
+                    continue
+                key, value = line.strip().split('=', 1)
+                # Decode list values
+                if key.endswith('[]'):
+                    key = key[:-2]
+                    value = _decode_list(value)
 
-            # Decode dict values
-            elif key.endswith('{}'):
-                key = key[:-2]
-                value = _decode_dict(value)
+                # Decode dict values
+                elif key.endswith('{}'):
+                    key = key[:-2]
+                    value = _decode_dict(value)
 
-            metadata[key] = value
-        meta_file.close()
+                metadata[key] = value
         return metadata
 
     def _process_usermeta(self, metadata):