utils.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # -*- coding: utf-8 -*-
  2. """EventMan(ager) utils
  3. Miscellaneous utilities.
  4. Copyright 2015-2016 Davide Alberani <da@erlug.linux.it>
  5. RaspiBO <info@raspibo.org>
  6. Licensed under the Apache License, Version 2.0 (the "License");
  7. you may not use this file except in compliance with the License.
  8. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. """
  15. import csv
  16. import json
  17. import string
  18. import random
  19. import hashlib
  20. import datetime
  21. import io
  22. from bson.objectid import ObjectId
  23. def csvParse(csvStr, remap=None, merge=None):
  24. """Parse a CSV file, optionally renaming the columns and merging other information.
  25. :param csvStr: the CSV to parse, as a string
  26. :type csvStr: str
  27. :param remap: a dictionary used to rename the columns
  28. :type remap: dict
  29. :param merge: merge these information into each line
  30. :type merge: dict
  31. :returns: tuple with a dict of total and valid lines and the data
  32. :rtype: tuple
  33. """
  34. if isinstance(csvStr, bytes):
  35. csvStr = csvStr.decode('utf-8')
  36. fd = io.StringIO(csvStr)
  37. reader = csv.reader(fd)
  38. remap = remap or {}
  39. merge = merge or {}
  40. fields = 0
  41. reply = dict(total=0, valid=0)
  42. results = []
  43. try:
  44. headers = next(reader)
  45. fields = len(headers)
  46. except (StopIteration, csv.Error):
  47. return reply, {}
  48. for idx, header in enumerate(headers):
  49. if header in remap:
  50. headers[idx] = remap[header]
  51. else:
  52. headers[idx] = header.lower().replace(' ', '_')
  53. try:
  54. for row in reader:
  55. try:
  56. reply['total'] += 1
  57. if len(row) != fields:
  58. continue
  59. values = dict(zip(headers, row))
  60. values.update(merge)
  61. results.append(values)
  62. reply['valid'] += 1
  63. except csv.Error:
  64. continue
  65. except csv.Error:
  66. pass
  67. fd.close()
  68. return reply, results
  69. def hash_password(password, salt=None):
  70. """Hash a password.
  71. :param password: the cleartext password
  72. :type password: str
  73. :param salt: the optional salt (randomly generated, if None)
  74. :type salt: str
  75. :returns: the hashed password
  76. :rtype: str"""
  77. if salt is None:
  78. salt_pool = string.ascii_letters + string.digits
  79. salt = ''.join(random.choice(salt_pool) for x in range(32))
  80. pwd = '%s%s' % (salt, password)
  81. hash_ = hashlib.sha512(pwd.encode('utf-8'))
  82. return '$%s$%s' % (salt, hash_.hexdigest())
  83. class ImprovedEncoder(json.JSONEncoder):
  84. """Enhance the default JSON encoder to serialize datetime and ObjectId instances."""
  85. def default(self, o):
  86. if isinstance(o, bytes):
  87. try:
  88. return o.decode('utf-8')
  89. except:
  90. pass
  91. elif isinstance(o, (datetime.datetime, datetime.date,
  92. datetime.time, datetime.timedelta, ObjectId)):
  93. try:
  94. return str(o)
  95. except Exception:
  96. pass
  97. elif isinstance(o, set):
  98. return list(o)
  99. return json.JSONEncoder.default(self, o)
  100. # Inject our class as the default encoder.
  101. json._default_encoder = ImprovedEncoder()