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.

context.py 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # -*- test-case-name: twisted.test.test_context -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Dynamic pseudo-scoping for Python.
  6. Call functions with context.call({key: value}, func); func and
  7. functions that it calls will be able to use 'context.get(key)' to
  8. retrieve 'value'.
  9. This is thread-safe.
  10. """
  11. from __future__ import division, absolute_import
  12. from threading import local
  13. from twisted.python._oldstyle import _oldStyle
  14. defaultContextDict = {}
  15. setDefault = defaultContextDict.__setitem__
  16. @_oldStyle
  17. class ContextTracker:
  18. """
  19. A L{ContextTracker} provides a way to pass arbitrary key/value data up and
  20. down a call stack without passing them as parameters to the functions on
  21. that call stack.
  22. This can be useful when functions on the top and bottom of the call stack
  23. need to cooperate but the functions in between them do not allow passing the
  24. necessary state. For example::
  25. from twisted.python.context import call, get
  26. def handleRequest(request):
  27. call({'request-id': request.id}, renderRequest, request.url)
  28. def renderRequest(url):
  29. renderHeader(url)
  30. renderBody(url)
  31. def renderHeader(url):
  32. return "the header"
  33. def renderBody(url):
  34. return "the body (request id=%r)" % (get("request-id"),)
  35. This should be used sparingly, since the lack of a clear connection between
  36. the two halves can result in code which is difficult to understand and
  37. maintain.
  38. @ivar contexts: A C{list} of C{dict}s tracking the context state. Each new
  39. L{ContextTracker.callWithContext} pushes a new C{dict} onto this stack
  40. for the duration of the call, making the data available to the function
  41. called and restoring the previous data once it is complete..
  42. """
  43. def __init__(self):
  44. self.contexts = [defaultContextDict]
  45. def callWithContext(self, newContext, func, *args, **kw):
  46. """
  47. Call C{func(*args, **kw)} such that the contents of C{newContext} will
  48. be available for it to retrieve using L{getContext}.
  49. @param newContext: A C{dict} of data to push onto the context for the
  50. duration of the call to C{func}.
  51. @param func: A callable which will be called.
  52. @param *args: Any additional positional arguments to pass to C{func}.
  53. @param **kw: Any additional keyword arguments to pass to C{func}.
  54. @return: Whatever is returned by C{func}
  55. @raise: Whatever is raised by C{func}.
  56. """
  57. self.contexts.append(newContext)
  58. try:
  59. return func(*args,**kw)
  60. finally:
  61. self.contexts.pop()
  62. def getContext(self, key, default=None):
  63. """
  64. Retrieve the value for a key from the context.
  65. @param key: The key to look up in the context.
  66. @param default: The value to return if C{key} is not found in the
  67. context.
  68. @return: The value most recently remembered in the context for C{key}.
  69. """
  70. for ctx in reversed(self.contexts):
  71. try:
  72. return ctx[key]
  73. except KeyError:
  74. pass
  75. return default
  76. class ThreadedContextTracker(object):
  77. def __init__(self):
  78. self.storage = local()
  79. def currentContext(self):
  80. try:
  81. return self.storage.ct
  82. except AttributeError:
  83. ct = self.storage.ct = ContextTracker()
  84. return ct
  85. def callWithContext(self, ctx, func, *args, **kw):
  86. return self.currentContext().callWithContext(ctx, func, *args, **kw)
  87. def getContext(self, key, default=None):
  88. return self.currentContext().getContext(key, default)
  89. def installContextTracker(ctr):
  90. global theContextTracker
  91. global call
  92. global get
  93. theContextTracker = ctr
  94. call = theContextTracker.callWithContext
  95. get = theContextTracker.getContext
  96. installContextTracker(ThreadedContextTracker())