utils.py 3.0 KB

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