pandoc-service/server.py

47 lines
1.3 KiB
Python

import logging
import uuid
import tempfile
import os
import flask_fs as fs
from flask import Flask, abort, request, Response, send_file
import pypandoc
app = Flask(__name__)
fs.init_app(app)
app.logger.setLevel(logging.INFO)
@app.route('/')
def index():
return 'Hello'
@app.route('/convert', methods=['POST'])
def convert():
if 'input' not in request.files:
abort(400)
if 'outputs' not in request.form:
abort(400)
job_name = uuid.uuid4().hex
job_dir = tempfile.mkdtemp(suffix='-' + job_name)
input_file = request.files['input']
input_base, input_ext = input_file.filename.rsplit('.')
input_path = os.path.join(job_dir, 'input.' + input_ext)
input_file.save(input_path)
outputs = request.form['outputs'].split(',')
results = []
for output in outputs:
output_filename = '{0}.{1}'.format(input_base, output)
output_path = os.path.join(job_dir, output_filename)
print('Converting {0} to {1}'.format(input_path, output_path))
pypandoc.convert(input_path, output, outputfile=output_path)
results.append({
'input': input_path,
'output': output_path,
'format': output,
})
if len(results) == 1:
return send_file(results[0]['output'])
return Response(str(results))