Skip to content
Snippets Groups Projects
api.py 3.09 KiB
import os
import atexit
import argparse
import uuid
import json

from flask import Flask, jsonify, Response

from flask import request, send_file
from flask_executor import Executor

from apscheduler.schedulers.background import BackgroundScheduler

from main import main
from lib.my_logging import logging
from lib.geonetwork_helper import RecordNotFound

from yaml import load, dump
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

from lib.read_status_logs import ReadLogger
from lib.get_most_recent_status_logs import GetLatestLog


# read 'n' parse the configuration
with open("config.yaml", 'r') as yamlfile:
    cfg = load(yamlfile, Loader=Loader)

cfg['rabbitmq']['host'] = os.environ['RMQ_HOST']

try:
    cfg['rabbitmq']['port'] = os.environ['RMQ_PORT']
except KeyError:
    cfg['rabbitmq']['port'] = 5672

cfg['rabbitmq']['exchange'] = os.environ['RMQ_EXCHANGE']

logging.getLogger().setLevel(os.environ['LOGLEVEL'])


# def say_hi(n):
#     import time
#     time.sleep(n)
#     logging.debug("Hi!")
#     return

# scheduler = BackgroundScheduler()
# #scheduler.add_job(refresh_cache, 'cron', hour='6', minute='0')
# scheduler.add_job(say_hi, 'interval', seconds=3)
# scheduler.start()
#
# # Shut down the scheduler when exiting the app
# atexit.register(lambda: scheduler.shutdown())
# #from main import refresh_cache


api = Flask(__name__, static_url_path='')
api.config['EXECUTOR_PROPAGATE_EXCEPTIONS'] = True
executor = Executor(api)


@api.route("/test")
def test():

    return jsonify({'test': "ok"})

# @api.before_first_request
# def init_scheduler():
#     scheduler = BackgroundScheduler()
#     #scheduler.add_job(refresh_cache, 'cron', hour='6', minute='0')
#     scheduler.add_job(say_hi, 'interval', seconds=3)
#     scheduler.start()
#
#     # Shut down the scheduler when exiting the app
#     atexit.register(lambda: scheduler.shutdown())


@api.route("/uuid/<the_uuid>", methods=["GET"])
def _main(the_uuid):

    this_session_id = str(uuid.uuid4())

    cfg['metadata_getter']['uuids_to_get'] = [the_uuid]
    cfg['session']['id'] = this_session_id

    executor.submit(main, cfg)

    return jsonify({'id': this_session_id}), 200

    # try:
    #     main(cfg)
    #     return jsonify({'result': 'ok'}), 200
    # except RecordNotFound as e:
    #     logging.error(e)
    #     return jsonify({'result': str(e)}), 404
    # except Exception as e:
    #     logging.error(e)
    #     return jsonify({'result': e}), 400


@api.route('/status/<session_id>')
def taskstatus(session_id):
    my_process_logger = ReadLogger(session_id=session_id, cfg=cfg)
    body = my_process_logger.main()

    return Response(json.dumps(body, indent=4, sort_keys=True, default=str), mimetype='application/json')


@api.route('/status/latest/<session_id>')
def lateststatus(session_id):
    my_latest_log = GetLatestLog(session_id=session_id, cfg=cfg)
    body = my_latest_log.main()

    return Response(json.dumps(body, indent=4, sort_keys=True, default=str), mimetype='application/json')


if __name__ == '__main__':
    api.run(host='0.0.0.0', port=8000, debug=True)