'Save a cached tile.'

def save(self, body, layer, coord, format):

    fullpath = self._fullpath(layer, coord, format)
    try:
        umask_old = os.umask(self.umask)
        os.makedirs(dirname(fullpath), (511 & (~ self.umask)))
    except OSError as e:
        if (e.errno != 17):
            raise
    finally:
        os.umask(umask_old)
    suffix = ('.' + format.lower())
    suffix += ((self._is_compressed(format) and '.gz') or '')
    (fh, tmp_path) = mkstemp(dir=self.cachepath, suffix=suffix)
    if self._is_compressed(format):
        os.close(fh)
        tmp_file = gzip.open(tmp_path, 'w')
        tmp_file.write(body)
        tmp_file.close()
    else:
        os.write(fh, body)
        os.close(fh)
    try:
        os.rename(tmp_path, fullpath)
    except OSError:
        os.unlink(fullpath)
        os.rename(tmp_path, fullpath)
    os.chmod(fullpath, (438 & (~ self.umask)))
