@contextmanager
    def open_for_write(self, image_id):
        incomplete_path = self.get_image_filepath(image_id, 'incomplete')

        def commit():
            with self.get_db() as db:
                final_path = self.get_image_filepath(image_id)
                logger.debug(_("Fetch finished, moving "
                             "'%(incomplete_path)s' to '%(final_path)s'"),
                             dict(incomplete_path=incomplete_path,
                                  final_path=final_path))
                os.rename(incomplete_path, final_path)

                # Make sure that we "pop" the image from the queue...
                if self.is_queued(image_id):
                    os.unlink(self.get_image_filepath(image_id, 'queue'))

                filesize = os.path.getsize(final_path)
                now = time.time()

                db.execute("""INSERT INTO cached_images
                           (image_id, last_accessed, last_modified, hits, size)
                           VALUES (?, 0, ?, 0, ?)""",
                           (image_id, now, filesize))
                db.commit()

        def rollback(e):
            with self.get_db() as db:
                if os.path.exists(incomplete_path):
                    invalid_path = self.get_image_filepath(image_id, 'invalid')

                    logger.debug(_("Fetch of cache file failed, rolling back "
                                   "by moving '%(incomplete_path)s' to "
                                   "'%(invalid_path)s'") % locals())
                    os.rename(incomplete_path, invalid_path)

                db.execute("""DELETE FROM cached_images
                           WHERE image_id = ?""", (image_id, ))
                db.commit()

        try:
            with open(incomplete_path, 'wb') as cache_file:
                yield cache_file
        except Exception as e:
            rollback(e)
            raise
        else:
            commit()
Creates a unique-enough cache key.
dataset/ETHPy150Open rcbops/glance-buildpackage/glance/image_cache/drivers/sqlite.py/Driver.open_for_write--crossover with--dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.generate_cache_key