config.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from flask import Blueprint, jsonify, abort, Response
  2. from apps.deploy.models import History
  3. from apps.configuration.models import ConfigKey, ConfigValue, AppConfigRel
  4. from libs.tools import JsonParser, Argument
  5. from apps.apis.utils import MapConfigValues
  6. blueprint = Blueprint(__name__, __name__)
  7. @blueprint.route('/<string:api_token>', methods=['GET'])
  8. def get(api_token):
  9. form, error = JsonParser(Argument('format', default='json', filter=lambda x: x in ['json', 'kv'])).parse()
  10. if error is not None:
  11. return abort(400)
  12. hit = History.query.filter_by(api_token=api_token).order_by(History.created.desc()).first()
  13. if hit is None:
  14. return abort(403)
  15. # 获取自身的keys
  16. self_keys = ConfigKey.query.filter_by(owner_id=hit.app_id, owner_type='app').filter(
  17. ConfigKey.type.in_(('private', 'public'))).all()
  18. # 通过配置关系表获取关联的所有对象
  19. link_objs = AppConfigRel.query.filter_by(s_id=hit.app_id).all()
  20. # 获取关联的应用的public类型keys
  21. link_app_ids = [x.d_id for x in link_objs if x.d_type == 'app']
  22. link_app_keys = ConfigKey.query.filter(
  23. ConfigKey.owner_id.in_(link_app_ids),
  24. ConfigKey.owner_type == 'app',
  25. ConfigKey.type == 'public'
  26. ).all() if link_app_ids else []
  27. # 获取关联的服务的keys
  28. link_ser_ids = [x.d_id for x in link_objs if x.d_type == 'ser']
  29. link_ser_keys = ConfigKey.query.filter(
  30. ConfigKey.owner_id.in_(link_ser_ids),
  31. ConfigKey.owner_type == 'ser'
  32. ).all() if link_ser_ids else []
  33. # 获取key对应的values
  34. all_keys = sorted(list(self_keys) + list(link_app_keys) + list(link_ser_keys), key=lambda x: x.name)
  35. all_values = ConfigValue.query.filter(
  36. ConfigValue.key_id.in_([x.id for x in all_keys])
  37. ).all() if all_keys else []
  38. # 遍历key组合最终结果
  39. map_values = MapConfigValues(all_values, hit.env_id)
  40. if form.format == 'kv':
  41. result = ''
  42. for key in all_keys:
  43. result += '%s=%s\n' % (key.name, map_values.get(key.id))
  44. return Response(result)
  45. else:
  46. result = {}
  47. for key in all_keys:
  48. result[key.name] = map_values.get(key.id)
  49. return jsonify(result)