diff odfcast/convert.py @ 0:4a34f72f036b

Add initial conversion service
author Björn Ricks <bjoern.ricks@intevation.de>
date Fri, 26 Sep 2014 14:21:21 +0200
parents
children 15807d87930c
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/odfcast/convert.py	Fri Sep 26 14:21:21 2014 +0200
@@ -0,0 +1,53 @@
+# -*- 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 post(self):
+        file = request.files['file']
+        format = request.form['format']
+
+        if format not in ALLOWED_FORMATS:
+            return "Format %s not allowed" % format, 401
+
+        outfile = self.convert(file, format)
+        mimetype = self.get_mimetype_for_format(format)
+        return Response(outfile, mimetype=mimetype)
+
+    def convert(self, file, format):
+        infile = tempfile.NamedTemporaryFile()
+        file.save(infile.name)
+        outfile = tempfile.NamedTemporaryFile()
+
+        self.convertor.convert(infile.name, outfile.name, format)
+
+        infile.close()
+        return outfile
+
+    def get_mimetype_for_format(self, format):
+        return MIMETYPES.get(format, DEFAULT_MIMETYPE)
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)