import logging import uuid import tempfile import os from celery import Celery from datetime import datetime, timedelta from flask import Flask, abort, request, Response, send_file 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): app.logger.info('Cleanup periodic task setup') @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) later = datetime.utcnow() + timedelta(hours=1) clean_up.apply_async((job_dir, ), eta=later) 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) app.logger.info('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)) @celery.task() def clean_up(path): app.logger.info('Deleting work dir %s', path) pass