utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import hashlib
  2. from typing import List, Optional, Union
  3. from django.core.cache import cache
  4. from apps.issue_events.models import IssueEventType
  5. from .schema import EventMessage
  6. def default_hash_input(title: str, culprit: str, type: IssueEventType) -> str:
  7. return title + culprit + str(type)
  8. def generate_hash(
  9. title: str, culprit: str, type: IssueEventType, extra: Optional[List[str]] = None
  10. ) -> str:
  11. """Generate insecure hash used for grouping issues"""
  12. if extra:
  13. hash_input = "".join(
  14. [
  15. default_hash_input(title, culprit, type)
  16. if part == "{{ default }}"
  17. else part
  18. for part in extra
  19. ]
  20. )
  21. else:
  22. hash_input = default_hash_input(title, culprit, type)
  23. return hashlib.md5(hash_input.encode()).hexdigest()
  24. def transform_parameterized_message(message: Union[str, EventMessage]) -> str:
  25. """
  26. Accept str or Event Message interface
  27. Returns formatted string with interpolation
  28. Both examples would return "Hello there":
  29. {
  30. "message": "Hello %s",
  31. "params": ["there"]
  32. }
  33. {
  34. "message": "Hello {foo}",
  35. "params": {"foo": "there"}
  36. }
  37. """
  38. if isinstance(message, str):
  39. return message
  40. if not message.formatted and message.message:
  41. params = message.params
  42. if isinstance(params, list) and params:
  43. return message.message % tuple(params)
  44. elif isinstance(params, dict):
  45. return message.message.format(**params)
  46. else:
  47. # Params not provided, return message as is
  48. return message.message
  49. return message.formatted
  50. def cache_set_nx(key, value, timeout: Optional[int] = 300) -> bool:
  51. """
  52. django-redis style cache set with nx, but with fallback for non-redis
  53. """
  54. try:
  55. return cache.set(key, value, timeout, nx=True)
  56. except TypeError:
  57. if cache.get(key):
  58. return False
  59. cache.set(key, value, timeout)
  60. return True