import functools import json from flask import Blueprint, request, Response, current_app import redis routes = Blueprint("inventory-data-query-routes", __name__) VERSION = { "api": "0.1", "module": "0.1" } def require_accepts_json(f): """ used as a route handler decorator to return an error unless the request allows responses with type "application/json" :param f: the function to be decorated :return: the decorated function """ @functools.wraps(f) def decorated_function(*args, **kwargs): # TODO: use best_match to disallow */* ...? if not request.accept_mimetypes.accept_json: return Response( response="response will be json", status=406, mimetype="text/html") return f(*args, **kwargs) return decorated_function @routes.route("/version", methods=['GET', 'POST']) @require_accepts_json def version(): return Response( json.dumps(VERSION), mimetype="application/json" ) @routes.route("/routers", methods=['GET', 'POST']) @require_accepts_json def routers(): redis_config = current_app.config["INVENTORY_PROVIDER_CONFIG"]["redis"] r = redis.StrictRedis( host=redis_config["hostname"], port=redis_config["port"]) return Response( json.dumps(list([k.decode("utf-8") for k in r.keys("*")])), mimetype="application/json") @routes.route("/interfaces/<hostname>", methods=['GET', 'POST']) @require_accepts_json def router_interfaces(hostname): redis_config = current_app.config["INVENTORY_PROVIDER_CONFIG"]["redis"] r = redis.StrictRedis( host=redis_config["hostname"], port=redis_config["port"]) ifc_data_string = r.hget(hostname, 'interfaces') if not ifc_data_string: return Response( response="no available info for '%s'" % hostname, status=404, mimetype="text/html") def _interfaces(s): for ifc in json.loads(s): if 'v4InterfaceName' in ifc: yield ifc['v4InterfaceName'] if 'v6InterfaceName' in ifc: yield ifc['v6InterfaceName'] interfaces = list(_interfaces(ifc_data_string.decode('utf-8'))) if not interfaces: return Response( response="no interfaces found for '%s'" % hostname, status=404, mimetype="text/html") return Response( json.dumps(interfaces), mimetype="application/json")