utils.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Event Man(ager) utils
  2. Miscellaneous utilities.
  3. Copyright 2015 Davide Alberani <da@erlug.linux.it>
  4. RaspiBO <info@raspibo.org>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. """
  14. import csv
  15. import json
  16. import datetime
  17. import StringIO
  18. from bson.objectid import ObjectId
  19. def csvParse(csvStr, remap=None, merge=None):
  20. """Parse a CSV file, optionally renaming the columns and merging other information.
  21. :param csvStr: the CSV to parse, as a string
  22. :type csvStr: str
  23. :param remap: a dictionary used to rename the columns
  24. :type remap: dict
  25. :param merge: merge these information into each line
  26. :type merge: dict
  27. :return: tuple with a dict of total and valid lines and the data
  28. :rtype: tuple
  29. """
  30. fd = StringIO.StringIO(csvStr)
  31. reader = csv.reader(fd)
  32. remap = remap or {}
  33. merge = merge or {}
  34. fields = 0
  35. reply = dict(total=0, valid=0)
  36. results = []
  37. try:
  38. headers = reader.next()
  39. fields = len(headers)
  40. except (StopIteration, csv.Error):
  41. return reply, {}
  42. for idx, header in enumerate(headers):
  43. if header in remap:
  44. headers[idx] = remap[header]
  45. else:
  46. headers[idx] = header.lower().replace(' ', '_')
  47. try:
  48. for row in reader:
  49. try:
  50. reply['total'] += 1
  51. if len(row) != fields:
  52. continue
  53. row = [unicode(cell, 'utf-8', 'replace') for cell in row]
  54. values = dict(map(None, headers, row))
  55. values.update(merge)
  56. results.append(values)
  57. reply['valid'] += 1
  58. except csv.Error:
  59. continue
  60. except csv.Error:
  61. pass
  62. fd.close()
  63. return reply, results
  64. class ImprovedEncoder(json.JSONEncoder):
  65. """Enhance the default JSON encoder to serialize datetime and ObjectId instances."""
  66. def default(self, o):
  67. if isinstance(o, (datetime.datetime, datetime.date,
  68. datetime.time, datetime.timedelta, ObjectId)):
  69. try:
  70. return str(o)
  71. except Exception, e:
  72. pass
  73. return json.JSONEncoder.default(self, o)
  74. # Inject our class as the default encoder.
  75. json._default_encoder = ImprovedEncoder()