utils.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. """EventMan(ager) utils
  2. Miscellaneous utilities.
  3. Copyright 2015-2016 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 io
  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. :returns: tuple with a dict of total and valid lines and the data
  31. :rtype: tuple
  32. """
  33. if isinstance(csvStr, bytes):
  34. csvStr = csvStr.decode('utf-8')
  35. fd = io.StringIO(csvStr)
  36. reader = csv.reader(fd)
  37. remap = remap or {}
  38. merge = merge or {}
  39. fields = 0
  40. reply = dict(total=0, valid=0)
  41. results = []
  42. try:
  43. headers = next(reader)
  44. fields = len(headers)
  45. except (StopIteration, csv.Error):
  46. return reply, {}
  47. for idx, header in enumerate(headers):
  48. if header in remap:
  49. headers[idx] = remap[header]
  50. else:
  51. headers[idx] = header.lower().replace(' ', '_')
  52. try:
  53. for row in reader:
  54. try:
  55. reply['total'] += 1
  56. if len(row) != fields:
  57. continue
  58. values = dict(zip(headers, row))
  59. values.update(merge)
  60. results.append(values)
  61. reply['valid'] += 1
  62. except csv.Error:
  63. continue
  64. except csv.Error:
  65. pass
  66. fd.close()
  67. return reply, results
  68. def hash_password(password, salt=None):
  69. """Hash a password.
  70. :param password: the cleartext password
  71. :type password: str
  72. :param salt: the optional salt (randomly generated, if None)
  73. :type salt: str
  74. :returns: the hashed password
  75. :rtype: str"""
  76. if salt is None:
  77. salt_pool = string.ascii_letters + string.digits
  78. salt = ''.join(random.choice(salt_pool) for x in range(32))
  79. pwd = '%s%s' % (salt, password)
  80. hash_ = hashlib.sha512(pwd.encode('utf-8'))
  81. return '$%s$%s' % (salt, hash_.hexdigest())
  82. class ImprovedEncoder(json.JSONEncoder):
  83. """Enhance the default JSON encoder to serialize datetime and ObjectId instances."""
  84. def default(self, o):
  85. if isinstance(o, bytes):
  86. try:
  87. return o.decode('utf-8')
  88. except:
  89. pass
  90. elif isinstance(o, (datetime.datetime, datetime.date,
  91. datetime.time, datetime.timedelta, ObjectId)):
  92. try:
  93. return str(o)
  94. except Exception as e:
  95. pass
  96. elif isinstance(o, set):
  97. return list(o)
  98. return json.JSONEncoder.default(self, o)
  99. # Inject our class as the default encoder.
  100. json._default_encoder = ImprovedEncoder()