from flask_restplus import Resource from flask import request from app.api.decorators import post_response, get_response, delete_response from app.celery.replicate import replicate_task from app.api.master.models import api, request_append_model, response_apppend_model, response_get_model, \ delete_response_model from logger_tools import setup_logger from general_config import general_config INMEMORY_LIST = list() logger = setup_logger("Master") @api.header('Content-Type', 'application/json') class POST(Resource): @api.expect(request_append_model) @api.response(200, 'Success', response_apppend_model) @post_response def post(self): global INMEMORY_LIST logger.info('Parsing post data') post_data = request.get_json(force=True, silent=True) or {} data = post_data.get('data') task_fst_response = replicate_task.apply( (data, general_config.first_hosts, 'append')) if task_fst_response.result['status'] != 'success': return task_fst_response.result
from __future__ import absolute_import, unicode_literals import requests from app.celery.app import app from logger_tools import setup_logger from general_config import general_config logger = setup_logger("Replicate_task") @app.task(bind=True) def replicate_task(self, data, hosts, mode): instance_map = {True: 'first instance', False: 'second instance'} mode_map = {'append': 'post', 'delete': 'delete'} node = 'secondary' instance = instance_map[hosts == general_config.first_hosts] url = f'http://{hosts}/api/v1/{node}/{mode_map[mode]}' header = {'content-type': 'application/json'} body = {'data': data} logger.info(f'URL {url}') logger.info(f'Body {body}') logger.info(f'Header {header}') logger.info(f'Making request for {instance}') if mode_map[mode] == 'post': request = requests.post(url, json=body, headers=header).json() elif mode_map[mode] == 'delete': request = requests.delete(url, headers=header).json() if request['status'] != 'success':
import traceback from logger_tools import setup_logger logger = setup_logger(__name__) def post_response(f): def wrapped(*args, **kwargs): try: result = f(*args, **kwargs) except: logger.exception("Fatal error during processing.") result = {'status': 'fail', 'message': f'Something went wrong - {traceback.format_exc()}'}, 500 return result return wrapped def get_response(f): def wrapped(*args, **kwargs): try: result = f(*args, **kwargs) except: logger.exception("Fatal error during processing.") result = {'status': 'fail', 'message': f'Something went wrong - {traceback.format_exc()}'}, 500 return result return wrapped def delete_response(f):