def test_guess_extension(self): self.assertEqual(file.guess_extension(filename="Test.png"), "png") self.assertEqual(file.guess_extension(mimetype="image/png"), "png")
def _compute_extension(self): for record in self: record.extension = file.guess_extension(record.name)
def convert(self, binary, mimetype=None, filename=None, export="binary", doctype="document", format="pdf"): """ Converts a binary value to the given format. :param binary: The binary value. :param mimetype: The mimetype of the binary value. :param filename: The filename of the binary value. :param export: The output format (binary, file, base64). :param doctype: Specify the document type (document, graphics, presentation, spreadsheet). :param format: Specify the output format for the document. :return: Returns the output depending on the given format. :raises ValueError: The file extension could not be determined or the format is invalid. """ extension = guess_extension(filename=filename, mimetype=mimetype, binary=binary) if not extension: raise ValueError("The file extension could not be determined.") if format not in self.formats: raise ValueError("Invalid export format.") if extension not in self.imports: raise ValueError("Invalid import format.") tmp_dir = tempfile.mkdtemp() try: tmp_wpath = os.path.join(tmp_dir, "tmpfile." + extension) tmp_ppath = os.path.join(tmp_dir, "tmpfile." + format) if os.name == 'nt': tmp_wpath = tmp_wpath.replace("\\", "/") tmp_ppath = tmp_ppath.replace("\\", "/") with closing(open(tmp_wpath, 'wb')) as file: file.write(binary) shell = True if os.name in ('nt', 'os2') else False args = [ 'unoconv', '--format=%s' % format, '--output=%s' % tmp_ppath, tmp_wpath ] process = Popen(args, stdout=PIPE, env=self.environ(), shell=shell) outs, errs = process.communicate() return_code = process.wait() if return_code: raise CalledProcessError(return_code, args, outs, errs) with closing(open(tmp_ppath, 'rb')) as file: if export == 'file': output = io.BytesIO() output.write(file.read()) output.close() return output elif export == 'base64': return base64.b64encode(file.read()) else: return file.read() except CalledProcessError: _logger.exception("Error while running unoconv.") raise except OSError: _logger.exception("Error while running unoconv.") raise finally: shutil.rmtree(tmp_dir)