diff options
author | Thiago da Silva <thiago@redhat.com> | 2014-03-19 11:09:10 -0400 |
---|---|---|
committer | Thiago da Silva <thiago@redhat.com> | 2014-03-21 11:47:43 -0400 |
commit | df17e0bc245ce3c7e58f384a3a2f6e02b999d50b (patch) | |
tree | cc87a1b80f85ed3b7e2226cec37731cb54976ce8 /glusterfs/gfapi.py | |
parent | c268302dd4dcd22a503e21f30d5bbfb2df3013f6 (diff) |
merging creat and open function to be more pythonic
the os python module does not offer a creat function,
new files are created using the open function and
by passing O_CREAT flag. We are changing gfapi.py to
function the same way.
Change-Id: I5e084b200bb657e3124d3e620a47160e790cd1fe
Signed-off-by: Thiago da Silva <thiago@redhat.com>
Diffstat (limited to 'glusterfs/gfapi.py')
-rw-r--r-- | glusterfs/gfapi.py | 42 |
1 files changed, 17 insertions, 25 deletions
diff --git a/glusterfs/gfapi.py b/glusterfs/gfapi.py index 8eeb3d6..6ca2ad7 100644 --- a/glusterfs/gfapi.py +++ b/glusterfs/gfapi.py @@ -19,8 +19,6 @@ import os import stat import errno -from contextlib import contextmanager - # Disclaimer: many of the helper functions (e.g., exists, isdir) where copied # from the python source code @@ -92,6 +90,17 @@ class File(object): def __init__(self, fd): self.fd = fd + def __enter__(self): + if self.fd is None: + # __enter__ should only be called within the context + # of a 'with' statement when opening a file through + # Volume.open() + raise ValueError("I/O operation on closed file") + return self + + def __exit__(self, type, value, tb): + self.close() + def close(self): ret = api.glfs_close(self.fd) if ret < 0: @@ -243,20 +252,6 @@ class Volume(object): raise OSError(err, os.strerror(err)) return ret - @contextmanager - def creat(self, path, flags, mode): - fd = api.glfs_creat(self.fs, path, flags, mode) - if not fd: - err = ctypes.get_errno() - raise OSError(err, os.strerror(err)) - - fileobj = None - try: - fileobj = File(fd) - yield fileobj - finally: - fileobj.close() - def exists(self, path): """ Test whether a path exists. @@ -384,19 +379,16 @@ class Volume(object): raise OSError(err, os.strerror(err)) return ret - @contextmanager - def open(self, path, flags): - fd = api.glfs_open(self.fs, path, flags) + def open(self, path, flags, mode=0777): + if (os.O_CREAT & flags) == os.O_CREAT: + fd = api.glfs_creat(self.fs, path, flags, mode) + else: + fd = api.glfs_open(self.fs, path, flags) if not fd: err = ctypes.get_errno() raise OSError(err, os.strerror(err)) - fileobj = None - try: - fileobj = File(fd) - yield fileobj - finally: - fileobj.close() + return File(fd) def opendir(self, path): fd = api.glfs_opendir(self.fs, path) |