图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

159 lines
3.7 KiB

  1. import logging
  2. import sys
  3. from contextlib import contextmanager
  4. from functools import wraps
  5. from typing import Any, Dict, Mapping, Union
  6. try:
  7. import hiredis # noqa
  8. # Only support Hiredis >= 1.0:
  9. HIREDIS_AVAILABLE = not hiredis.__version__.startswith("0.")
  10. HIREDIS_PACK_AVAILABLE = hasattr(hiredis, "pack_command")
  11. except ImportError:
  12. HIREDIS_AVAILABLE = False
  13. HIREDIS_PACK_AVAILABLE = False
  14. try:
  15. import ssl # noqa
  16. SSL_AVAILABLE = True
  17. except ImportError:
  18. SSL_AVAILABLE = False
  19. try:
  20. import cryptography # noqa
  21. CRYPTOGRAPHY_AVAILABLE = True
  22. except ImportError:
  23. CRYPTOGRAPHY_AVAILABLE = False
  24. if sys.version_info >= (3, 8):
  25. from importlib import metadata
  26. else:
  27. import importlib_metadata as metadata
  28. def from_url(url, **kwargs):
  29. """
  30. Returns an active Redis client generated from the given database URL.
  31. Will attempt to extract the database id from the path url fragment, if
  32. none is provided.
  33. """
  34. from redis.client import Redis
  35. return Redis.from_url(url, **kwargs)
  36. @contextmanager
  37. def pipeline(redis_obj):
  38. p = redis_obj.pipeline()
  39. yield p
  40. p.execute()
  41. def str_if_bytes(value: Union[str, bytes]) -> str:
  42. return (
  43. value.decode("utf-8", errors="replace") if isinstance(value, bytes) else value
  44. )
  45. def safe_str(value):
  46. return str(str_if_bytes(value))
  47. def dict_merge(*dicts: Mapping[str, Any]) -> Dict[str, Any]:
  48. """
  49. Merge all provided dicts into 1 dict.
  50. *dicts : `dict`
  51. dictionaries to merge
  52. """
  53. merged = {}
  54. for d in dicts:
  55. merged.update(d)
  56. return merged
  57. def list_keys_to_dict(key_list, callback):
  58. return dict.fromkeys(key_list, callback)
  59. def merge_result(command, res):
  60. """
  61. Merge all items in `res` into a list.
  62. This command is used when sending a command to multiple nodes
  63. and the result from each node should be merged into a single list.
  64. res : 'dict'
  65. """
  66. result = set()
  67. for v in res.values():
  68. for value in v:
  69. result.add(value)
  70. return list(result)
  71. def warn_deprecated(name, reason="", version="", stacklevel=2):
  72. import warnings
  73. msg = f"Call to deprecated {name}."
  74. if reason:
  75. msg += f" ({reason})"
  76. if version:
  77. msg += f" -- Deprecated since version {version}."
  78. warnings.warn(msg, category=DeprecationWarning, stacklevel=stacklevel)
  79. def deprecated_function(reason="", version="", name=None):
  80. """
  81. Decorator to mark a function as deprecated.
  82. """
  83. def decorator(func):
  84. @wraps(func)
  85. def wrapper(*args, **kwargs):
  86. warn_deprecated(name or func.__name__, reason, version, stacklevel=3)
  87. return func(*args, **kwargs)
  88. return wrapper
  89. return decorator
  90. def _set_info_logger():
  91. """
  92. Set up a logger that log info logs to stdout.
  93. (This is used by the default push response handler)
  94. """
  95. if "push_response" not in logging.root.manager.loggerDict.keys():
  96. logger = logging.getLogger("push_response")
  97. logger.setLevel(logging.INFO)
  98. handler = logging.StreamHandler()
  99. handler.setLevel(logging.INFO)
  100. logger.addHandler(handler)
  101. def get_lib_version():
  102. try:
  103. libver = metadata.version("redis")
  104. except metadata.PackageNotFoundError:
  105. libver = "99.99.99"
  106. return libver
  107. def format_error_message(host_error: str, exception: BaseException) -> str:
  108. if not exception.args:
  109. return f"Error connecting to {host_error}."
  110. elif len(exception.args) == 1:
  111. return f"Error {exception.args[0]} connecting to {host_error}."
  112. else:
  113. return (
  114. f"Error {exception.args[0]} connecting to {host_error}. "
  115. f"{exception.args[1]}."
  116. )