utils.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import random
  4. import string
  5. from redis import Redis
  6. from rq import Queue
  7. from tracim_backend.config import CFG
  8. DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
  9. DEFAULT_WEBDAV_CONFIG_FILE = "wsgidav.conf"
  10. DEFAULT_TRACIM_CONFIG_FILE = "development.ini"
  11. def get_redis_connection(config: CFG) -> Redis:
  12. """
  13. :param config: current app_config
  14. :return: redis connection
  15. """
  16. return Redis(
  17. host=config.EMAIL_SENDER_REDIS_HOST,
  18. port=config.EMAIL_SENDER_REDIS_PORT,
  19. db=config.EMAIL_SENDER_REDIS_DB,
  20. )
  21. def get_rq_queue(redis_connection: Redis, queue_name: str ='default') -> Queue:
  22. """
  23. :param queue_name: name of queue
  24. :return: wanted queue
  25. """
  26. return Queue(name=queue_name, connection=redis_connection)
  27. def cmp_to_key(mycmp):
  28. """
  29. List sort related function
  30. Convert a cmp= function into a key= function
  31. """
  32. class K(object):
  33. def __init__(self, obj, *args):
  34. self.obj = obj
  35. def __lt__(self, other):
  36. return mycmp(self.obj, other.obj) < 0
  37. def __gt__(self, other):
  38. return mycmp(self.obj, other.obj) > 0
  39. def __eq__(self, other):
  40. return mycmp(self.obj, other.obj) == 0
  41. def __le__(self, other):
  42. return mycmp(self.obj, other.obj) <= 0
  43. def __ge__(self, other):
  44. return mycmp(self.obj, other.obj) >= 0
  45. def __ne__(self, other):
  46. return mycmp(self.obj, other.obj) != 0
  47. return K
  48. def current_date_for_filename() -> str:
  49. """
  50. ISO8601 current date, adapted to be used in filename (for
  51. webdav feature for example), with trouble-free characters.
  52. :return: current date as string like "2018-03-19T15.49.27.246592"
  53. """
  54. # INFO - G.M - 19-03-2018 - As ':' is in transform_to_bdd method in
  55. # webdav utils, it may cause trouble. So, it should be replaced to
  56. # a character which will not change in bdd.
  57. return datetime.datetime.now().isoformat().replace(':', '.')
  58. # INFO - G.M - 2018-08-02 - Simple password generator, inspired by
  59. # https://gist.github.com/23maverick23/4131896
  60. ALLOWED_AUTOGEN_PASSWORD_CHAR = string.ascii_letters + \
  61. string.digits + \
  62. string.punctuation
  63. DEFAULT_PASSWORD_GEN_CHAR_LENGTH = 12
  64. def password_generator(
  65. length: int=DEFAULT_PASSWORD_GEN_CHAR_LENGTH,
  66. chars: str=ALLOWED_AUTOGEN_PASSWORD_CHAR
  67. ) -> str:
  68. """
  69. :param length: length of the new password
  70. :param chars: characters allowed
  71. :return: password as string
  72. """
  73. return ''.join(random.choice(chars) for char_number in range(length))