pandoc-service/server.py

61 lines
1.7 KiB
Python
Raw Normal View History

2018-11-04 10:54:21 +00:00
import logging
import uuid
import tempfile
import os
from flask import Flask, abort, request, Response, send_file
from celery import Celery
2018-11-04 10:54:21 +00:00
import pypandoc
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
# Celery setup and init
celery = Celery(app.import_name)
celery.conf.broker_url = 'redis://redis:6379/0'
celery.conf.worker_concurrency = 2
@celery.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
sender.add_periodic_task(10.0, clean_up.s(), name="Cleanup")
app.logger.info('Cleanup periodic task setup')
2018-11-04 10:54:21 +00:00
@app.route('/')
def index():
return 'Hello'
2018-11-04 10:54:21 +00:00
@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)
2018-11-05 19:34:12 +00:00
logger.info('Converting {0} to {1}'.format(input_path, output_path))
2018-11-04 10:54:21 +00:00
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))
@celery.task()
def clean_up():
pass