utils.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 re
  15. import csv
  16. import json
  17. import datetime
  18. import StringIO
  19. from bson.objectid import ObjectId
  20. def csvParse(csvStr, remap=None, merge=None):
  21. """Parse a CSV file, optionally renaming the columns and merging other information.
  22. :param csvStr: the CSV to parse, as a string
  23. :type csvStr: str
  24. :param remap: a dictionary used to rename the columns
  25. :type remap: dict
  26. :param merge: merge these information into each line
  27. :type merge: dict
  28. :return: tuple with a dict of total and valid lines and the data
  29. :rtype: tuple
  30. """
  31. fd = StringIO.StringIO(csvStr)
  32. reader = csv.reader(fd)
  33. remap = remap or {}
  34. merge = merge or {}
  35. fields = 0
  36. reply = dict(total=0, valid=0)
  37. results = []
  38. try:
  39. headers = reader.next()
  40. fields = len(headers)
  41. except (StopIteration, csv.Error):
  42. return reply, {}
  43. for idx, header in enumerate(headers):
  44. if header in remap:
  45. headers[idx] = remap[header]
  46. try:
  47. for row in reader:
  48. try:
  49. reply['total'] += 1
  50. if len(row) != fields:
  51. continue
  52. row = [unicode(cell, 'utf-8', 'replace') for cell in row]
  53. values = dict(map(None, headers, row))
  54. values.update(merge)
  55. results.append(values)
  56. reply['valid'] += 1
  57. except csv.Error:
  58. continue
  59. except csv.Error:
  60. pass
  61. fd.close()
  62. return reply, results
  63. class ImprovedEncoder(json.JSONEncoder):
  64. """Enhance the default JSON encoder to serialize datetime and ObjectId instances."""
  65. def default(self, o):
  66. if isinstance(o, (datetime.datetime, datetime.date,
  67. datetime.time, datetime.timedelta, ObjectId)):
  68. try:
  69. return str(o)
  70. except Exception, e:
  71. pass
  72. return json.JSONEncoder.default(self, o)
  73. # Inject our class as the default encoder.
  74. json._default_encoder = ImprovedEncoder()