utils.py 11 KB

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