utils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 StringIO
  16. def csvParse(csvStr, remap=None, merge=None):
  17. """Parse a CSV file, optionally renaming the columns and merging other information.
  18. :param csvStr: the CSV to parse, as a string
  19. :type csvStr: str
  20. :param remap: a dictionary used to rename the columns
  21. :type remap: dict
  22. :param merge: merge these information into each line
  23. :type merge: dict
  24. :return: tuple with a dict of total and valid lines and the data
  25. :rtype: tuple
  26. """
  27. fd = StringIO.StringIO(csvStr)
  28. reader = csv.reader(fd)
  29. remap = remap or {}
  30. merge = merge or {}
  31. fields = 0
  32. reply = dict(total=0, valid=0)
  33. results = []
  34. try:
  35. headers = reader.next()
  36. fields = len(headers)
  37. except (StopIteration, csv.Error):
  38. return reply, {}
  39. for idx, header in enumerate(headers):
  40. if header in remap:
  41. headers[idx] = remap[header]
  42. try:
  43. for row in reader:
  44. try:
  45. reply['total'] += 1
  46. if len(row) != fields:
  47. continue
  48. row = [unicode(cell, 'utf-8', 'replace') for cell in row]
  49. values = dict(map(None, headers, row))
  50. values.update(merge)
  51. results.append(values)
  52. reply['valid'] += 1
  53. except csv.Error:
  54. continue
  55. except csv.Error:
  56. pass
  57. fd.close()
  58. return reply, results