utils.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. from __future__ import unicode_literals
  2. import datetime
  3. import json
  4. import six
  5. from django.core.serializers import serialize
  6. from django.http import HttpResponse
  7. def csv_format(data):
  8. """
  9. Encapsulate any data which contains a comma within double quotes.
  10. """
  11. csv = []
  12. for value in data:
  13. # Represent None or False with empty string
  14. if value is None or value is False:
  15. csv.append('')
  16. continue
  17. # Convert dates to ISO format
  18. if isinstance(value, (datetime.date, datetime.datetime)):
  19. value = value.isoformat()
  20. # Force conversion to string first so we can check for any commas
  21. if not isinstance(value, six.string_types):
  22. value = '{}'.format(value)
  23. # Double-quote the value if it contains a comma
  24. if ',' in value or '\n' in value:
  25. csv.append('"{}"'.format(value))
  26. else:
  27. csv.append('{}'.format(value))
  28. return ','.join(csv)
  29. def queryset_to_csv(queryset):
  30. """
  31. Export a queryset of objects as CSV, using the model's to_csv() method.
  32. """
  33. output = []
  34. # Start with the column headers
  35. headers = ','.join(queryset.model.csv_headers)
  36. output.append(headers)
  37. # Iterate through the queryset
  38. for obj in queryset:
  39. data = csv_format(obj.to_csv())
  40. output.append(data)
  41. # Build the HTTP response
  42. response = HttpResponse(
  43. '\n'.join(output),
  44. content_type='text/csv'
  45. )
  46. filename = 'netbox_{}.csv'.format(queryset.model._meta.verbose_name_plural)
  47. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  48. return response
  49. def foreground_color(bg_color):
  50. """
  51. Return the ideal foreground color (black or white) for a given background color in hexadecimal RGB format.
  52. """
  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 > 186:
  56. return '000000'
  57. else:
  58. return 'ffffff'
  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 serialize_object(obj, extra=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.
  72. """
  73. json_str = serialize('json', [obj])
  74. data = json.loads(json_str)[0]['fields']
  75. # Include any custom fields
  76. if hasattr(obj, 'get_custom_fields'):
  77. data['custom_fields'] = {
  78. field.name: value for field, value in obj.get_custom_fields().items()
  79. }
  80. # Include any tags
  81. if hasattr(obj, 'tags'):
  82. data['tags'] = [tag.name for tag in obj.tags.all()]
  83. # Append any extra data
  84. if extra is not None:
  85. data.update(extra)
  86. return data