PageRenderTime 23ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/eventlet/api.py

https://github.com/HolodeckJizzmopper/bitHopper
Python | 209 lines | 195 code | 9 blank | 5 comment | 1 complexity | 586eea77004162ea2aa9298f1ef25df3 MD5 | raw file
  1. import errno
  2. import sys
  3. import socket
  4. import string
  5. import linecache
  6. import inspect
  7. import warnings
  8. from eventlet.support import greenlets as greenlet, BaseException
  9. from eventlet import hubs
  10. from eventlet import greenthread
  11. from eventlet import debug
  12. from eventlet import Timeout
  13. __all__ = [
  14. 'call_after', 'exc_after', 'getcurrent', 'get_default_hub', 'get_hub',
  15. 'GreenletExit', 'kill', 'sleep', 'spawn', 'spew', 'switch',
  16. 'ssl_listener', 'tcp_listener', 'trampoline',
  17. 'unspew', 'use_hub', 'with_timeout', 'timeout']
  18. warnings.warn("eventlet.api is deprecated! Nearly everything in it has moved "
  19. "to the eventlet module.", DeprecationWarning, stacklevel=2)
  20. def get_hub(*a, **kw):
  21. warnings.warn("eventlet.api.get_hub has moved to eventlet.hubs.get_hub",
  22. DeprecationWarning, stacklevel=2)
  23. return hubs.get_hub(*a, **kw)
  24. def get_default_hub(*a, **kw):
  25. warnings.warn("eventlet.api.get_default_hub has moved to"
  26. " eventlet.hubs.get_default_hub",
  27. DeprecationWarning, stacklevel=2)
  28. return hubs.get_default_hub(*a, **kw)
  29. def use_hub(*a, **kw):
  30. warnings.warn("eventlet.api.use_hub has moved to eventlet.hubs.use_hub",
  31. DeprecationWarning, stacklevel=2)
  32. return hubs.use_hub(*a, **kw)
  33. def switch(coro, result=None, exc=None):
  34. if exc is not None:
  35. return coro.throw(exc)
  36. return coro.switch(result)
  37. Greenlet = greenlet.greenlet
  38. def tcp_listener(address, backlog=50):
  39. """
  40. Listen on the given ``(ip, port)`` *address* with a TCP socket. Returns a
  41. socket object on which one should call ``accept()`` to accept a connection
  42. on the newly bound socket.
  43. """
  44. warnings.warn("""eventlet.api.tcp_listener is deprecated. Please use eventlet.listen instead.""",
  45. DeprecationWarning, stacklevel=2)
  46. from eventlet import greenio, util
  47. socket = greenio.GreenSocket(util.tcp_socket())
  48. util.socket_bind_and_listen(socket, address, backlog=backlog)
  49. return socket
  50. def ssl_listener(address, certificate, private_key):
  51. """Listen on the given (ip, port) *address* with a TCP socket that
  52. can do SSL. Primarily useful for unit tests, don't use in production.
  53. *certificate* and *private_key* should be the filenames of the appropriate
  54. certificate and private key files to use with the SSL socket.
  55. Returns a socket object on which one should call ``accept()`` to
  56. accept a connection on the newly bound socket.
  57. """
  58. warnings.warn("""eventlet.api.ssl_listener is deprecated. Please use eventlet.wrap_ssl(eventlet.listen()) instead.""",
  59. DeprecationWarning, stacklevel=2)
  60. from eventlet import util
  61. import socket
  62. socket = util.wrap_ssl(socket.socket(), certificate, private_key, True)
  63. socket.bind(address)
  64. socket.listen(50)
  65. return socket
  66. def connect_tcp(address, localaddr=None):
  67. """
  68. Create a TCP connection to address ``(host, port)`` and return the socket.
  69. Optionally, bind to localaddr ``(host, port)`` first.
  70. """
  71. warnings.warn("""eventlet.api.connect_tcp is deprecated. Please use eventlet.connect instead.""",
  72. DeprecationWarning, stacklevel=2)
  73. from eventlet import greenio, util
  74. desc = greenio.GreenSocket(util.tcp_socket())
  75. if localaddr is not None:
  76. desc.bind(localaddr)
  77. desc.connect(address)
  78. return desc
  79. TimeoutError = greenthread.TimeoutError
  80. trampoline = hubs.trampoline
  81. spawn = greenthread.spawn
  82. spawn_n = greenthread.spawn_n
  83. kill = greenthread.kill
  84. call_after = greenthread.call_after
  85. call_after_local = greenthread.call_after_local
  86. call_after_global = greenthread.call_after_global
  87. class _SilentException(BaseException):
  88. pass
  89. class FakeTimer(object):
  90. def cancel(self):
  91. pass
  92. class timeout(object):
  93. """Raise an exception in the block after timeout.
  94. Example::
  95. with timeout(10):
  96. urllib2.open('http://example.com')
  97. Assuming code block is yielding (i.e. gives up control to the hub),
  98. an exception provided in *exc* argument will be raised
  99. (:class:`~eventlet.api.TimeoutError` if *exc* is omitted)::
  100. try:
  101. with timeout(10, MySpecialError, error_arg_1):
  102. urllib2.open('http://example.com')
  103. except MySpecialError, e:
  104. print "special error received"
  105. When *exc* is ``None``, code block is interrupted silently.
  106. """
  107. def __init__(self, seconds, *throw_args):
  108. self.seconds = seconds
  109. if seconds is None:
  110. return
  111. if not throw_args:
  112. self.throw_args = (TimeoutError(), )
  113. elif throw_args == (None, ):
  114. self.throw_args = (_SilentException(), )
  115. else:
  116. self.throw_args = throw_args
  117. def __enter__(self):
  118. if self.seconds is None:
  119. self.timer = FakeTimer()
  120. else:
  121. self.timer = exc_after(self.seconds, *self.throw_args)
  122. return self.timer
  123. def __exit__(self, typ, value, tb):
  124. self.timer.cancel()
  125. if typ is _SilentException and value in self.throw_args:
  126. return True
  127. with_timeout = greenthread.with_timeout
  128. exc_after = greenthread.exc_after
  129. sleep = greenthread.sleep
  130. getcurrent = greenlet.getcurrent
  131. GreenletExit = greenlet.GreenletExit
  132. spew = debug.spew
  133. unspew = debug.unspew
  134. def named(name):
  135. """Return an object given its name.
  136. The name uses a module-like syntax, eg::
  137. os.path.join
  138. or::
  139. mulib.mu.Resource
  140. """
  141. toimport = name
  142. obj = None
  143. import_err_strings = []
  144. while toimport:
  145. try:
  146. obj = __import__(toimport)
  147. break
  148. except ImportError, err:
  149. # print 'Import error on %s: %s' % (toimport, err) # debugging spam
  150. import_err_strings.append(err.__str__())
  151. toimport = '.'.join(toimport.split('.')[:-1])
  152. if obj is None:
  153. raise ImportError('%s could not be imported. Import errors: %r' % (name, import_err_strings))
  154. for seg in name.split('.')[1:]:
  155. try:
  156. obj = getattr(obj, seg)
  157. except AttributeError:
  158. dirobj = dir(obj)
  159. dirobj.sort()
  160. raise AttributeError('attribute %r missing from %r (%r) %r. Import errors: %r' % (
  161. seg, obj, dirobj, name, import_err_strings))
  162. return obj