utils.py 9.8 KB

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