您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

77 行
2.0 KiB

  1. # -*- coding: utf-8 -*-
  2. from __future__ import (absolute_import, division, print_function,
  3. unicode_literals)
  4. from contextlib import contextmanager
  5. from redis import Redis
  6. from .local import LocalStack, release_local
  7. class NoRedisConnectionException(Exception):
  8. pass
  9. @contextmanager
  10. def Connection(connection=None): # noqa
  11. if connection is None:
  12. connection = Redis()
  13. push_connection(connection)
  14. try:
  15. yield
  16. finally:
  17. popped = pop_connection()
  18. assert popped == connection, \
  19. 'Unexpected Redis connection was popped off the stack. ' \
  20. 'Check your Redis connection setup.'
  21. def push_connection(redis):
  22. """Pushes the given connection on the stack."""
  23. _connection_stack.push(redis)
  24. def pop_connection():
  25. """Pops the topmost connection from the stack."""
  26. return _connection_stack.pop()
  27. def use_connection(redis=None):
  28. """Clears the stack and uses the given connection. Protects against mixed
  29. use of use_connection() and stacked connection contexts.
  30. """
  31. assert len(_connection_stack) <= 1, \
  32. 'You should not mix Connection contexts with use_connection()'
  33. release_local(_connection_stack)
  34. if redis is None:
  35. redis = Redis()
  36. push_connection(redis)
  37. def get_current_connection():
  38. """Returns the current Redis connection (i.e. the topmost on the
  39. connection stack).
  40. """
  41. return _connection_stack.top
  42. def resolve_connection(connection=None):
  43. """Convenience function to resolve the given or the current connection.
  44. Raises an exception if it cannot resolve a connection now.
  45. """
  46. if connection is not None:
  47. return connection
  48. connection = get_current_connection()
  49. if connection is None:
  50. raise NoRedisConnectionException('Could not resolve a Redis connection')
  51. return connection
  52. _connection_stack = LocalStack()
  53. __all__ = ['Connection', 'get_current_connection', 'push_connection',
  54. 'pop_connection', 'use_connection']