Mercurial > odfcast > odfcast
view odfcast/convert.py @ 3:15807d87930c
Refactor ConvertView to be easier reusable
author | Björn Ricks <bjoern.ricks@intevation.de> |
---|---|
date | Fri, 26 Sep 2014 15:34:46 +0200 |
parents | 4a34f72f036b |
children | 46f31348fe01 |
line wrap: on
line source
# -*- coding: utf-8 -*- import tempfile from flask import request, Response from flask.views import MethodView ALLOWED_FORMATS = ["pdf", "doc", "docx", "odt"] MIMETYPES = { "odt": "application/vnd.oasis.opendocument.text", "doc": "application/msword", "docx": "application/vnd.openxmlformats-officedocument" ".wordprocessingml.document", "pdf": "application/pdf", } DEFAULT_MIMETYPE = "application/octet-stream" class ConvertView(MethodView): def __init__(self, pyuno_driver_name="", hostname="localhost", port=2001): driver_module = self._load_driver_module(pyuno_driver_name) self.convertor = driver_module.Convertor(hostname, port) def _load_driver_module(self, pyuno_driver_name): return __import__(pyuno_driver_name, globals(), locals(), ["Convertor"]) def is_format_supported(self, fformat): return fformat and fformat.lower() in ALLOWED_FORMATS def post(self): ffile = request.files['file'] fformat = request.form['format'] if not self.is_format_supported(fformat): return "Format %s not allowed" % fformat, 401 infile = self.save_form_file(ffile) outfile = self.convert(infile, fformat) mimetype = self.get_mimetype_for_format(fformat) return Response(outfile, mimetype=mimetype) def save_form_file(self, infile): outfile = tempfile.NamedTemporaryFile() infile.save(outfile.name) return outfile def convert(self, infile, fformat): outfile = tempfile.NamedTemporaryFile() self.convertor.convert(infile.name, outfile.name, fformat) infile.close() return outfile def get_mimetype_for_format(self, fformat): return MIMETYPES.get(fformat, DEFAULT_MIMETYPE)