utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import datetime
  2. import json
  3. from collections import OrderedDict
  4. from decimal import Decimal
  5. from itertools import count, groupby
  6. from django.core.serializers import serialize
  7. from django.db.models import Count, OuterRef, Subquery
  8. from django.db.models.functions import Coalesce
  9. from django.http import QueryDict
  10. from jinja2.sandbox import SandboxedEnvironment
  11. from mptt.models import MPTTModel
  12. from dcim.choices import CableLengthUnitChoices
  13. from extras.plugins import PluginConfig
  14. from extras.utils import is_taggable
  15. from utilities.constants import HTTP_REQUEST_META_SAFE_COPY
  16. def resolve_namespace(instance):
  17. """
  18. Get the appropriate namepsace for the app based on whether it is a Plugin or base application
  19. """
  20. if isinstance(instance._meta.app_config, PluginConfig):
  21. return f'plugins:{instance._meta.app_label}'
  22. return f'{instance._meta.app_label}'
  23. def csv_format(data):
  24. """
  25. Encapsulate any data which contains a comma within double quotes.
  26. """
  27. csv = []
  28. for value in data:
  29. # Represent None or False with empty string
  30. if value is None or value is False:
  31. csv.append('')
  32. continue
  33. # Convert dates to ISO format
  34. if isinstance(value, (datetime.date, datetime.datetime)):
  35. value = value.isoformat()
  36. # Force conversion to string first so we can check for any commas
  37. if not isinstance(value, str):
  38. value = '{}'.format(value)
  39. # Double-quote the value if it contains a comma or line break
  40. if ',' in value or '\n' in value:
  41. value = value.replace('"', '""') # Escape double-quotes
  42. csv.append('"{}"'.format(value))
  43. else:
  44. csv.append('{}'.format(value))
  45. return ','.join(csv)
  46. def foreground_color(bg_color, dark='000000', light='ffffff'):
  47. """
  48. Return the ideal foreground color (dark or light) for a given background color in hexadecimal RGB format.
  49. :param dark: RBG color code for dark text
  50. :param light: RBG color code for light text
  51. """
  52. THRESHOLD = 150
  53. bg_color = bg_color.strip('#')
  54. r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)]
  55. if r * 0.299 + g * 0.587 + b * 0.114 > THRESHOLD:
  56. return dark
  57. else:
  58. return light
  59. def dynamic_import(name):
  60. """
  61. Dynamically import a class from an absolute path string
  62. """
  63. components = name.split('.')
  64. mod = __import__(components[0])
  65. for comp in components[1:]:
  66. mod = getattr(mod, comp)
  67. return mod
  68. def count_related(model, field):
  69. """
  70. Return a Subquery suitable for annotating a child object count.
  71. """
  72. subquery = Subquery(
  73. model.objects.filter(
  74. **{field: OuterRef('pk')}
  75. ).order_by().values(
  76. field
  77. ).annotate(
  78. c=Count('*')
  79. ).values('c')
  80. )
  81. return Coalesce(subquery, 0)
  82. def serialize_object(obj, extra=None):
  83. """
  84. Return a generic JSON representation of an object using Django's built-in serializer. (This is used for things like
  85. change logging, not the REST API.) Optionally include a dictionary to supplement the object data. A list of keys
  86. can be provided to exclude them from the returned dictionary. Private fields (prefaced with an underscore) are
  87. implicitly excluded.
  88. """
  89. json_str = serialize('json', [obj])
  90. data = json.loads(json_str)[0]['fields']
  91. # Exclude any MPTTModel fields
  92. if issubclass(obj.__class__, MPTTModel):
  93. for field in ['level', 'lft', 'rght', 'tree_id']:
  94. data.pop(field)
  95. # Include custom_field_data as "custom_fields"
  96. if hasattr(obj, 'custom_field_data'):
  97. data['custom_fields'] = data.pop('custom_field_data')
  98. # Include any tags. Check for tags cached on the instance; fall back to using the manager.
  99. if is_taggable(obj):
  100. tags = getattr(obj, '_tags', None) or obj.tags.all()
  101. data['tags'] = [tag.name for tag in tags]
  102. # Append any extra data
  103. if extra is not None:
  104. data.update(extra)
  105. # Copy keys to list to avoid 'dictionary changed size during iteration' exception
  106. for key in list(data):
  107. # Private fields shouldn't be logged in the object change
  108. if isinstance(key, str) and key.startswith('_'):
  109. data.pop(key)
  110. return data
  111. def dict_to_filter_params(d, prefix=''):
  112. """
  113. Translate a dictionary of attributes to a nested set of parameters suitable for QuerySet filtering. For example:
  114. {
  115. "name": "Foo",
  116. "rack": {
  117. "facility_id": "R101"
  118. }
  119. }
  120. Becomes:
  121. {
  122. "name": "Foo",
  123. "rack__facility_id": "R101"
  124. }
  125. And can be employed as filter parameters:
  126. Device.objects.filter(**dict_to_filter(attrs_dict))
  127. """
  128. params = {}
  129. for key, val in d.items():
  130. k = prefix + key
  131. if isinstance(val, dict):
  132. params.update(dict_to_filter_params(val, k + '__'))
  133. else:
  134. params[k] = val
  135. return params
  136. def normalize_querydict(querydict):
  137. """
  138. Convert a QueryDict to a normal, mutable dictionary, preserving list values. For example,
  139. QueryDict('foo=1&bar=2&bar=3&baz=')
  140. becomes:
  141. {'foo': '1', 'bar': ['2', '3'], 'baz': ''}
  142. This function is necessary because QueryDict does not provide any built-in mechanism which preserves multiple
  143. values.
  144. """
  145. return {
  146. k: v if len(v) > 1 else v[0] for k, v in querydict.lists()
  147. }
  148. def deepmerge(original, new):
  149. """
  150. Deep merge two dictionaries (new into original) and return a new dict
  151. """
  152. merged = OrderedDict(original)
  153. for key, val in new.items():
  154. if key in original and isinstance(original[key], dict) and isinstance(val, dict):
  155. merged[key] = deepmerge(original[key], val)
  156. else:
  157. merged[key] = val
  158. return merged
  159. def to_meters(length, unit):
  160. """
  161. Convert the given length to meters.
  162. """
  163. try:
  164. if length < 0:
  165. raise ValueError("Length must be a positive number")
  166. except TypeError:
  167. raise TypeError(f"Invalid value '{length}' for length (must be a number)")
  168. valid_units = CableLengthUnitChoices.values()
  169. if unit not in valid_units:
  170. raise ValueError(f"Unknown unit {unit}. Must be one of the following: {', '.join(valid_units)}")
  171. if unit == CableLengthUnitChoices.UNIT_KILOMETER:
  172. return length * 1000
  173. if unit == CableLengthUnitChoices.UNIT_METER:
  174. return length
  175. if unit == CableLengthUnitChoices.UNIT_CENTIMETER:
  176. return length / 100
  177. if unit == CableLengthUnitChoices.UNIT_MILE:
  178. return length * Decimal(1609.344)
  179. if unit == CableLengthUnitChoices.UNIT_FOOT:
  180. return length * Decimal(0.3048)
  181. if unit == CableLengthUnitChoices.UNIT_INCH:
  182. return length * Decimal(0.3048) * 12
  183. raise ValueError(f"Unknown unit {unit}. Must be 'km', 'm', 'cm', 'mi', 'ft', or 'in'.")
  184. def render_jinja2(template_code, context):
  185. """
  186. Render a Jinja2 template with the provided context. Return the rendered content.
  187. """
  188. return SandboxedEnvironment().from_string(source=template_code).render(**context)
  189. def prepare_cloned_fields(instance):
  190. """
  191. Compile an object's `clone_fields` list into a string of URL query parameters. Tags are automatically cloned where
  192. applicable.
  193. """
  194. params = []
  195. for field_name in getattr(instance, 'clone_fields', []):
  196. field = instance._meta.get_field(field_name)
  197. field_value = field.value_from_object(instance)
  198. # Pass False as null for boolean fields
  199. if field_value is False:
  200. params.append((field_name, ''))
  201. # Omit empty values
  202. elif field_value not in (None, ''):
  203. params.append((field_name, field_value))
  204. # Copy tags
  205. if is_taggable(instance):
  206. for tag in instance.tags.all():
  207. params.append(('tags', tag.pk))
  208. # Return a QueryDict with the parameters
  209. return QueryDict('&'.join([f'{k}={v}' for k, v in params]), mutable=True)
  210. def shallow_compare_dict(source_dict, destination_dict, exclude=None):
  211. """
  212. Return a new dictionary of the different keys. The values of `destination_dict` are returned. Only the equality of
  213. the first layer of keys/values is checked. `exclude` is a list or tuple of keys to be ignored.
  214. """
  215. difference = {}
  216. for key in destination_dict:
  217. if source_dict.get(key) != destination_dict[key]:
  218. if isinstance(exclude, (list, tuple)) and key in exclude:
  219. continue
  220. difference[key] = destination_dict[key]
  221. return difference
  222. def flatten_dict(d, prefix='', separator='.'):
  223. """
  224. Flatten netsted dictionaries into a single level by joining key names with a separator.
  225. :param d: The dictionary to be flattened
  226. :param prefix: Initial prefix (if any)
  227. :param separator: The character to use when concatenating key names
  228. """
  229. ret = {}
  230. for k, v in d.items():
  231. key = separator.join([prefix, k]) if prefix else k
  232. if type(v) is dict:
  233. ret.update(flatten_dict(v, prefix=key, separator=separator))
  234. else:
  235. ret[key] = v
  236. return ret
  237. def array_to_string(array):
  238. """
  239. Generate an efficient, human-friendly string from a set of integers. Intended for use with ArrayField.
  240. For example:
  241. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  242. """
  243. group = (list(x) for _, x in groupby(sorted(array), lambda x, c=count(): next(c) - x))
  244. return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group)
  245. def content_type_name(ct):
  246. """
  247. Return a human-friendly ContentType name (e.g. "DCIM > Site").
  248. """
  249. try:
  250. meta = ct.model_class()._meta
  251. return f'{meta.app_config.verbose_name} > {meta.verbose_name}'
  252. except AttributeError:
  253. # Model no longer exists
  254. return f'{ct.app_label} > {ct.model}'
  255. def content_type_identifier(ct):
  256. """
  257. Return a "raw" ContentType identifier string suitable for bulk import/export (e.g. "dcim.site").
  258. """
  259. return f'{ct.app_label}.{ct.model}'
  260. #
  261. # Fake request object
  262. #
  263. class NetBoxFakeRequest:
  264. """
  265. A fake request object which is explicitly defined at the module level so it is able to be pickled. It simply
  266. takes what is passed to it as kwargs on init and sets them as instance variables.
  267. """
  268. def __init__(self, _dict):
  269. self.__dict__ = _dict
  270. def copy_safe_request(request):
  271. """
  272. Copy selected attributes from a request object into a new fake request object. This is needed in places where
  273. thread safe pickling of the useful request data is needed.
  274. """
  275. meta = {
  276. k: request.META[k]
  277. for k in HTTP_REQUEST_META_SAFE_COPY
  278. if k in request.META and isinstance(request.META[k], str)
  279. }
  280. return NetBoxFakeRequest({
  281. 'META': meta,
  282. 'POST': request.POST,
  283. 'GET': request.GET,
  284. 'FILES': request.FILES,
  285. 'user': request.user,
  286. 'path': request.path,
  287. 'id': getattr(request, 'id', None), # UUID assigned by middleware
  288. })