/cms/io/PsycoGevent.py

https://github.com/cms-dev/cms · Python · 104 lines · 40 code · 19 blank · 45 comment · 9 complexity · 3f2ef4e32d9c8072fdd937c8a4588bd6 MD5 · raw file

  1. #!/usr/bin/env python3
  2. # This file was taken from
  3. # https://bitbucket.org/zzzeek/green_sqla/src/2732bb7ea9d06b9d4a61e8c \
  4. # d587a95148ce2599b/green_sqla/psyco_gevent.py?at=default
  5. """A wait callback to allow psycopg2 cooperation with gevent.
  6. Use `make_psycopg_green()` to enable gevent support in Psycopg.
  7. """
  8. # Copyright (C) 2010 Daniele Varrazzo <daniele.varrazzo@gmail.com>
  9. # Copyright (C) 2013 Giovanni Mascellani <mascellani@poisson.phc.unipi.it>
  10. # and licensed under the MIT license:
  11. #
  12. # Permission is hereby granted, free of charge, to any person obtaining a copy
  13. # of this software and associated documentation files (the "Software"), to deal
  14. # in the Software without restriction, including without limitation the rights
  15. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  16. # copies of the Software, and to permit persons to whom the Software is
  17. # furnished to do so, subject to the following conditions:
  18. #
  19. # The above copyright notice and this permission notice shall be included in
  20. # all copies or substantial portions of the Software.
  21. #
  22. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  23. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  24. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  25. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  26. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  27. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  28. # THE SOFTWARE.
  29. from contextlib import contextmanager
  30. import psycopg2
  31. from gevent.socket import wait_read, wait_write
  32. from psycopg2 import extensions
  33. def make_psycopg_green():
  34. """Configure Psycopg to be used with gevent in non-blocking way."""
  35. if not hasattr(extensions, 'set_wait_callback'):
  36. raise ImportError(
  37. "support for coroutines not available in this Psycopg version (%s)"
  38. % psycopg2.__version__)
  39. extensions.set_wait_callback(gevent_wait_callback)
  40. def unmake_psycopg_green():
  41. """Undo make_psycopg_green()."""
  42. if not hasattr(extensions, 'set_wait_callback'):
  43. raise ImportError(
  44. "support for coroutines not available in this Psycopg version (%s)"
  45. % psycopg2.__version__)
  46. extensions.set_wait_callback(None)
  47. def is_psycopg_green():
  48. """Test whether gevent compatibility layer is installed in psycopg."""
  49. if not hasattr(extensions, 'set_wait_callback'):
  50. raise ImportError(
  51. "support for coroutines not available in this Psycopg version (%s)"
  52. % psycopg2.__version__)
  53. return extensions.get_wait_callback() == gevent_wait_callback
  54. def gevent_wait_callback(conn, timeout=None):
  55. """A wait callback useful to allow gevent to work with Psycopg."""
  56. while 1:
  57. state = conn.poll()
  58. if state == extensions.POLL_OK:
  59. break
  60. elif state == extensions.POLL_READ:
  61. wait_read(conn.fileno(), timeout=timeout)
  62. elif state == extensions.POLL_WRITE:
  63. wait_write(conn.fileno(), timeout=timeout)
  64. else:
  65. raise psycopg2.OperationalError(
  66. "Bad result from poll: %r" % state)
  67. @contextmanager
  68. def ungreen_psycopg():
  69. """Temporarily disable gevent support in psycopg.
  70. Inside this context manager you can use psycopg's features that
  71. are not compatible with coroutine support, such as large
  72. objects. Of course, at the expense of being blocking, so please
  73. stay inside the context manager as short as possible.
  74. """
  75. is_green = is_psycopg_green()
  76. if is_green:
  77. unmake_psycopg_green()
  78. try:
  79. yield
  80. finally:
  81. if is_green:
  82. make_psycopg_green()