Mercurial > odfcast > odfcast
view odfcast/convert.py @ 18:585904e7411a
Add html for converting a odf with a template
author | Björn Ricks <bjoern.ricks@intevation.de> |
---|---|
date | Mon, 29 Sep 2014 14:18:11 +0200 |
parents | f4920ab1d27c |
children | 2f627039d2b4 |
line wrap: on
line source
# -*- coding: utf-8 -*- import tempfile from flask import request, Response, json, render_template from flask.views import MethodView from py3o.template import Template 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 get(self): return render_template("convert.html") 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) class TemplateConvertView(ConvertView): def post(self): ffile = request.files['file'] fformat = request.form['format'] datadict = self.get_datadict() if not self.is_format_supported(fformat): return "Format %s not allowed" % fformat, 401 tfile = self.save_form_file(ffile) outfile = tempfile.NamedTemporaryFile() t = Template(tfile, outfile.name) t.render(datadict) if fformat != "odt": outfile = self.convert(outfile, fformat) mimetype = self.get_mimetype_for_format(fformat) return Response(outfile, mimetype=mimetype) def get_datadict(self): vars = request.form['datadict'] return json.loads(vars) def get(self): return render_template("template_convert.html")