def test_from_file_to_file(self): with tempdir() as dpath: fpath = osp.join(dpath, 'binary.bin') with open(fpath, 'wb') as fobj: Binary(b'binaryblob').to_file(fobj) bobj = Binary.from_file(fpath) self.assertEqual(bobj.getvalue(), b'binaryblob')
def callback(self, source, cnx, value): """sql generator callback when some attribute with a custom storage is accessed """ fpath = source.binary_to_str(value) try: return Binary.from_file(fpath) except EnvironmentError as ex: source.critical("can't open %s: %s", value, ex) return None
def entity_added(self, entity, attr): """an entity using this storage for attr has been added""" if entity._cw.transaction_data.get('fs_importing'): binary = Binary.from_file(entity.cw_edited[attr].getvalue()) entity._cw_dont_cache_attribute(attr, repo_side=True) else: binary = entity.cw_edited.pop(attr) if binary is not None: fd, fpath = self.new_fs_path(entity, attr) # bytes storage used to store file's path binary_obj = Binary(fpath.encode('utf-8')) entity.cw_edited.edited_attribute(attr, binary_obj) self._writecontent(fd, binary) AddFileOp.get_instance(entity._cw).add_data(fpath) return binary
def entity_updated(self, entity, attr): """an entity using this storage for attr has been updated""" # get the name of the previous file containing the value oldpath = self.current_fs_path(entity, attr) if entity._cw.transaction_data.get('fs_importing'): # If we are importing from the filesystem, the file already exists. # We do not need to create it but we need to fetch the content of # the file as the actual content of the attribute fpath = entity.cw_edited[attr].getvalue() entity._cw_dont_cache_attribute(attr, repo_side=True) assert fpath is not None binary = Binary.from_file(fpath) else: # We must store the content of the attributes # into a file to stay consistent with the behaviour of entity_add. # Moreover, the BytesFileSystemStorage expects to be able to # retrieve the current value of the attribute at anytime by reading # the file on disk. To be able to rollback things, use a new file # and keep the old one that will be removed on commit if everything # went ok. # # fetch the current attribute value in memory binary = entity.cw_edited.pop(attr) if binary is None: fpath = None else: # Get filename for it fd, fpath = self.new_fs_path(entity, attr) # write attribute value on disk self._writecontent(fd, binary) # Mark the new file as added during the transaction. # The file will be removed on rollback AddFileOp.get_instance(entity._cw).add_data(fpath) # reinstall poped value if fpath is None: entity.cw_edited.edited_attribute(attr, None) else: # register the new location for the file. binary_obj = Binary(fpath.encode('utf-8')) entity.cw_edited.edited_attribute(attr, binary_obj) if oldpath is not None and oldpath != fpath: # Mark the old file as useless so the file will be removed at # commit. DeleteFileOp.get_instance(entity._cw).add_data(oldpath) return binary