dispatch.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from django.conf import settings
  4. from django.db import connection
  5. from django.core.cache import cache
  6. from dvadmin.utils.validator import CustomValidationError
  7. from django.db.models import Q
  8. dispatch_db_type = getattr(settings, 'DISPATCH_DB_TYPE', 'memory') # redis
  9. def is_tenants_mode():
  10. """
  11. 判断是否为租户模式
  12. :return:
  13. """
  14. return hasattr(connection, "tenant") and connection.tenant.schema_name
  15. # ================================================= #
  16. # ******************** 初始化 ******************** #
  17. # ================================================= #
  18. def _get_all_dictionary():
  19. from dvadmin.system.models import Dictionary
  20. queryset = Dictionary.objects.filter(status=True, is_value=False)
  21. data = []
  22. for instance in queryset:
  23. data.append(
  24. {
  25. "id": instance.id,
  26. "value": instance.value,
  27. "children": list(
  28. Dictionary.objects.filter(parent=instance.id)
  29. .filter(status=1)
  30. .values("label", "value", "type", "color")
  31. ),
  32. }
  33. )
  34. return {ele.get("value"): ele for ele in data}
  35. def _get_all_system_config():
  36. data = {}
  37. from dvadmin.system.models import SystemConfig
  38. system_config_obj = (
  39. SystemConfig.objects.filter(~Q(parent_id__form_item_type=11), parent_id__isnull=False)
  40. .values("parent__key", "key", "value", "form_item_type")
  41. .order_by("sort")
  42. )
  43. for system_config in system_config_obj:
  44. value = system_config.get("value", "")
  45. if value and system_config.get("form_item_type") == 7:
  46. value = value[0].get("url")
  47. if value and system_config.get("form_item_type") == 11:
  48. new_value = []
  49. for ele in value:
  50. new_value.append({
  51. "key": ele.get('key'),
  52. "title": ele.get('title'),
  53. "value": ele.get('value'),
  54. })
  55. new_value.sort(key=lambda s: s["key"])
  56. value = new_value
  57. data[f"{system_config.get('parent__key')}.{system_config.get('key')}"] = value
  58. return data
  59. def init_dictionary():
  60. """
  61. 初始化字典配置
  62. :return:
  63. """
  64. try:
  65. if dispatch_db_type == 'redis':
  66. cache.set(f"init_dictionary", _get_all_dictionary())
  67. return
  68. if is_tenants_mode():
  69. from django_tenants.utils import tenant_context, get_tenant_model
  70. for tenant in get_tenant_model().objects.filter():
  71. with tenant_context(tenant):
  72. settings.DICTIONARY_CONFIG[connection.tenant.schema_name] = _get_all_dictionary()
  73. else:
  74. settings.DICTIONARY_CONFIG = _get_all_dictionary()
  75. except Exception as e:
  76. print("请先进行数据库迁移!")
  77. return
  78. def init_system_config():
  79. """
  80. 初始化系统配置
  81. :param name:
  82. :return:
  83. """
  84. try:
  85. if dispatch_db_type == 'redis':
  86. cache.set(f"init_system_config", _get_all_system_config())
  87. return
  88. if is_tenants_mode():
  89. from django_tenants.utils import tenant_context, get_tenant_model
  90. for tenant in get_tenant_model().objects.filter():
  91. with tenant_context(tenant):
  92. settings.SYSTEM_CONFIG[connection.tenant.schema_name] = _get_all_system_config()
  93. else:
  94. settings.SYSTEM_CONFIG = _get_all_system_config()
  95. except Exception as e:
  96. print("请先进行数据库迁移!")
  97. return
  98. def refresh_dictionary():
  99. """
  100. 刷新字典配置
  101. :return:
  102. """
  103. if dispatch_db_type == 'redis':
  104. cache.set(f"init_dictionary", _get_all_dictionary())
  105. return
  106. if is_tenants_mode():
  107. from django_tenants.utils import tenant_context, get_tenant_model
  108. for tenant in get_tenant_model().objects.filter():
  109. with tenant_context(tenant):
  110. settings.DICTIONARY_CONFIG[connection.tenant.schema_name] = _get_all_dictionary()
  111. else:
  112. settings.DICTIONARY_CONFIG = _get_all_dictionary()
  113. def refresh_system_config():
  114. """
  115. 刷新系统配置
  116. :return:
  117. """
  118. if dispatch_db_type == 'redis':
  119. cache.set(f"init_system_config", _get_all_system_config())
  120. return
  121. if is_tenants_mode():
  122. from django_tenants.utils import tenant_context, get_tenant_model
  123. for tenant in get_tenant_model().objects.filter():
  124. with tenant_context(tenant):
  125. settings.SYSTEM_CONFIG[connection.tenant.schema_name] = _get_all_system_config()
  126. else:
  127. settings.SYSTEM_CONFIG = _get_all_system_config()
  128. # ================================================= #
  129. # ******************** 字典管理 ******************** #
  130. # ================================================= #
  131. def get_dictionary_config(schema_name=None):
  132. """
  133. 获取字典所有配置
  134. :param schema_name: 对应字典配置的租户schema_name值
  135. :return:
  136. """
  137. if dispatch_db_type == 'redis':
  138. init_dictionary_data = cache.get(f"init_dictionary")
  139. if not init_dictionary_data:
  140. refresh_dictionary()
  141. return cache.get(f"init_dictionary") or {}
  142. if not settings.DICTIONARY_CONFIG:
  143. refresh_dictionary()
  144. if is_tenants_mode():
  145. dictionary_config = settings.DICTIONARY_CONFIG[schema_name or connection.tenant.schema_name]
  146. else:
  147. dictionary_config = settings.DICTIONARY_CONFIG
  148. return dictionary_config or {}
  149. def get_dictionary_values(key, schema_name=None):
  150. """
  151. 获取字典数据数组
  152. :param key: 对应字典配置的key值(字典编号)
  153. :param schema_name: 对应字典配置的租户schema_name值
  154. :return:
  155. """
  156. if dispatch_db_type == 'redis':
  157. dictionary_config = cache.get(f"init_dictionary")
  158. if not dictionary_config:
  159. refresh_dictionary()
  160. dictionary_config = cache.get(f"init_dictionary")
  161. return dictionary_config.get(key)
  162. dictionary_config = get_dictionary_config(schema_name)
  163. return dictionary_config.get(key)
  164. def get_dictionary_label(key, name, schema_name=None):
  165. """
  166. 获取获取字典label值
  167. :param key: 字典管理中的key值(字典编号)
  168. :param name: 对应字典配置的value值
  169. :param schema_name: 对应字典配置的租户schema_name值
  170. :return:
  171. """
  172. res = get_dictionary_values(key, schema_name) or []
  173. for ele in res.get('children'):
  174. if ele.get("value") == str(name):
  175. return ele.get("label")
  176. return ""
  177. # ================================================= #
  178. # ******************** 系统配置 ******************** #
  179. # ================================================= #
  180. def get_system_config(schema_name=None):
  181. """
  182. 获取系统配置中所有配置
  183. 1.只传父级的key,返回全部子级,{ "父级key.子级key" : "值" }
  184. 2."父级key.子级key",返回子级值
  185. :param schema_name: 对应字典配置的租户schema_name值
  186. :return:
  187. """
  188. if dispatch_db_type == 'redis':
  189. init_dictionary_data = cache.get(f"init_system_config")
  190. if not init_dictionary_data:
  191. refresh_system_config()
  192. return cache.get(f"init_system_config") or {}
  193. if not settings.SYSTEM_CONFIG:
  194. refresh_system_config()
  195. if is_tenants_mode():
  196. dictionary_config = settings.SYSTEM_CONFIG[schema_name or connection.tenant.schema_name]
  197. else:
  198. dictionary_config = settings.SYSTEM_CONFIG
  199. return dictionary_config or {}
  200. def get_system_config_values(key, schema_name=None):
  201. """
  202. 获取系统配置数据数组
  203. :param key: 对应系统配置的key值(字典编号)
  204. :param schema_name: 对应系统配置的租户schema_name值
  205. :return:
  206. """
  207. if dispatch_db_type == 'redis':
  208. system_config = cache.get(f"init_system_config")
  209. if not system_config:
  210. refresh_system_config()
  211. system_config = cache.get(f"init_system_config")
  212. return system_config.get(key)
  213. system_config = get_system_config(schema_name)
  214. return system_config.get(key)
  215. def get_system_config_values_to_dict(key, schema_name=None):
  216. """
  217. 获取系统配置数据并转换为字典 **仅限于数组类型系统配置
  218. :param key: 对应系统配置的key值(字典编号)
  219. :param schema_name: 对应系统配置的租户schema_name值
  220. :return:
  221. """
  222. values_dict = {}
  223. config_values = get_system_config_values(key, schema_name)
  224. if not isinstance(config_values, list):
  225. raise CustomValidationError("该方式仅限于数组类型系统配置")
  226. for ele in get_system_config_values(key, schema_name):
  227. values_dict[ele.get('key')] = ele.get('value')
  228. return values_dict
  229. def get_system_config_label(key, name, schema_name=None):
  230. """
  231. 获取获取系统配置label值
  232. :param key: 系统配置中的key值(字典编号)
  233. :param name: 对应系统配置的value值
  234. :param schema_name: 对应系统配置的租户schema_name值
  235. :return:
  236. """
  237. children = get_system_config_values(key, schema_name) or []
  238. for ele in children:
  239. if ele.get("value") == str(name):
  240. return ele.get("label")
  241. return ""