'Return the e-book format as a bytestring or `None` if the format doesn\'t exist,
or we don\'t have permission to write to the e-book file.
:param as_file: If True the e-book format is returned as a file object. Note
that the file object is a SpooledTemporaryFile, so if what you want to
do is copy the format to another file, use :meth:`copy_format_to`
instead for performance.
:param as_path: Copies the format file to a temp file and returns the
path to the temp file
:param preserve_filename: If True and returning a path the filename is
the same as that used in the library. Note that using
this means that repeated calls yield the same
temp file (which is re-created each time)'

@api
def format(self, book_id, fmt, as_file=False, as_path=False, preserve_filename=False):

    fmt = (fmt or u'').upper()
    ext = ((u'.' + fmt.lower()) if fmt else u'')
    if as_path:
        if preserve_filename:
            with self.safe_read_lock:
                try:
                    fname = self.fields[u'formats'].format_fname(book_id, fmt)
                except:
                    return None
                fname += ext
            bd = base_dir()
            d = os.path.join(bd, u'format_abspath')
            try:
                os.makedirs(d)
            except:
                pass
            ret = os.path.join(d, fname)
            try:
                self.copy_format_to(book_id, fmt, ret)
            except NoSuchFormat:
                return None
        else:
            with PersistentTemporaryFile(ext) as pt:
                try:
                    self.copy_format_to(book_id, fmt, pt)
                except NoSuchFormat:
                    return None
                ret = pt.name
    elif as_file:
        with self.safe_read_lock:
            try:
                fname = self.fields[u'formats'].format_fname(book_id, fmt)
            except:
                return None
            fname += ext
        ret = SpooledTemporaryFile(SPOOL_SIZE)
        try:
            self.copy_format_to(book_id, fmt, ret)
        except NoSuchFormat:
            return None
        ret.seek(0)
        ret.name = fname
    else:
        buf = BytesIO()
        try:
            self.copy_format_to(book_id, fmt, buf)
        except NoSuchFormat:
            return None
        ret = buf.getvalue()
    return ret
