Pyjo.Reactor.Gevent - Low-level event reactor on gevent

from Pyjo.Reactor.Gevent import Gevent

# Watch if handle becomes readable or writable
reactor = Gevent()
reactor.io(first, lambda reactor, writable: print(
    'First handle is writable' if writable else 'First handle is readable'
))

# Or import the module, as in Google Python Style Guide

import Pyjo.Reactor.Gevent

# Watch if handle becomes readable or writable
reactor = Pyjo.Reactor.Gevent.new()
reactor.io(first, lambda reactor, writable: print(
    'First handle is writable' if writable else 'First handle is readable'
))

# Change to watching only if handle becomes writable
reactor.watch(first, False, True)

# Watch a file descriptor if it becomes readable
reactor.io(fd, lambda reactor, writable: print(
    'Second handle is writable' if writable else 'Second handle is readable'
)).watch(fd, True, False)

# Add a timer
def timeout(reactor):
    reactor.remove(first)
    reactor.remove(fd)
    print('Timeout!')

reactor.timer(15, timeout)

# Start reactor if necessary
if not reactor.is_running:
    reactor.start()

Pyjo.Reactor.Gevent is a low-level event reactor based on the hub of gevent, whose loop of libev or libuv watches the handles and runs the timers, so that the servers of Pyjoyment, as Pyjo.Server.Daemon, Pyjo.Server.Prefork and Pyjo.Server.Prethread, and its user agent run along with the greenlets of a program of gevent. PYJO_REACTOR selects it for Pyjo.IOLoop:

PYJO_REACTOR=Pyjo.Reactor.Gevent python myapp.py daemon

The reactor runs in the greenlet that calls start() or one_tick(), the main one or any other, which waits for the events in the hub, where the other greenlets of the program run in the meantime, and the callbacks of the reactor run in that greenlet. A callback can wait for a greenlet or for a function of gevent, as gevent.sleep, which stops the events of the reactor until it returns, but not the other greenlets. A blocking request of Pyjo.UserAgent, which runs an event loop of its own, waits in the greenlet that makes it, while the other greenlets, a server of Pyjoyment among them, run. The reactor cannot run in the hub itself, as in a callback of the loop of gevent, where gevent raises BlockingSwitchOutError.

A reactor uses the hub of the thread that makes it, so the threads of Pyjo.Server.Prethread have hubs of their own, and any number of reactors share the hub of a thread. The child of a fork, as a worker of Pyjo.Server.Prefork, reinitializes the hub, as gevent.os.fork does.

The environment variable GEVENT_LOOP of gevent selects the loop, libev (libev-cext, the default) or libuv (libuv-cffi), for which cffi is installed too:

pip install Pyjo-Reactor-Gevent cffi
GEVENT_LOOP=libuv-cffi PYJO_REACTOR=Pyjo.Reactor.Gevent python myapp.py daemon

A program that calls gevent.monkey.patch_all() runs the reactor as well, but its threads are greenlets then, and so is the thread of Pyjo.IOLoop.Pyjo_IOLoop.singleton, which each greenlet has of its own, and Pyjo.Server.Prethread and Pyjo.IOLoop.ChildProcess do not work with the threads and the subprocesses of gevent.

Events

Pyjo.Reactor.Gevent inherits all events from Pyjo.Reactor.Poll.

See also

Pyjo.Reactor.Poll, Pyjoyment, https://github.com/pyjoyment/Pyjoyment.

Classes

class Pyjo.Reactor.Gevent.Pyjo_Reactor_Gevent[source]

Pyjo.Reactor.Gevent inherits all methods from Pyjo.Reactor.Poll and implements the following new ones.

again(id: str, after: float | None = None) → None[source]
reactor.again(id)
reactor.again(id, 0.5)

Restart timer and optionally change the invocation time. Note that this method requires an active timer.

event_loop_modules: tuple[str, ...] = ('gevent',)
modules = reactor.event_loop_modules

The names of the modules of the event loop that the reactor runs on, as ('trio',), whose code a finalizer of the garbage collector may interrupt. The cleanup of a stream, a server or a user agent that is freed in a frame of such a module, or of a module of a class of the reactor, waits for the next tick of the reactor, so that it does not change the structures that the event loop is changing. Defaults to ().

class Pyjo_Reactor_MyLoop(Pyjo.Reactor.Poll.object):
    event_loop_modules = ('myloop',)
hub: Any
hub = reactor.hub

The hub of gevent of the thread that made the reactor, whose loop watches the handles and runs the timers.

io(handle: Handle, cb: IOCallback) → Self[source]
reactor = reactor.io(handle, cb)

Watch handle for I/O events, invoking the callback whenever handle becomes readable or writable.

one_tick() → None[source]
reactor.one_tick()

Run reactor until an event occurs or no events are being watched anymore, while the other greenlets run.

recurring(after: float, cb: TimerCallback) → str[source]
id = reactor.recurring(0.25, cb)

Create a new recurring timer, invoking the callback repeatedly after a given amount of time in seconds.

remove(remove: Handle | str) → bool[source]
boolean = reactor.remove(handle)
boolean = reactor.remove(id)

Remove handle or timer.

reset() → None[source]
reactor.reset()

Remove all handles and timers.

stop() → None[source]
reactor.stop()

Stop watching for I/O and timer events, also from another greenlet than the one that runs the reactor.

timer(after: float, cb: TimerCallback) → str[source]
id = reactor.timer(0.5, cb)

Create a new timer, invoking the callback after a given amount of time in seconds.

watch(handle: Handle, read: bool, write: bool) → Self[source]
reactor = reactor.watch(handle, readable, writable)

Change I/O events to watch handle for with true and false values. Note that this method requires an active I/O watcher.

Examples

examples/hello_world_gevent.py runs Pyjo.HelloWorld on the server of Pyjoyment on gevent until the signal INT or TERM, in a with block, which closes the listen sockets of the server at its end:

import os


# The reactor of Pyjoyment on gevent, selected before Pyjo.IOLoop is loaded
os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Gevent'

import Pyjo.HelloWorld  # noqa: E402
import Pyjo.Server.Daemon  # noqa: E402


# The server of Pyjoyment on gevent, until the signal INT or TERM, which closes its listen sockets at the end of the block
with Pyjo.Server.Daemon.new(app=Pyjo.HelloWorld.new(), listen=['http://*:3000']) as daemon:
    daemon.run()
$ python examples/hello_world_gevent.py
Web application available at http://127.0.0.1:3000
$ curl http://127.0.0.1:3000/
Your Pyjo is working!

examples/loopback_gevent.py is a server of Pyjoyment and its user agent on the hub of gevent, a blocking request, which runs the event loop until the response, and the class of the reactor and whether it runs on the hub of gevent:

import os


# The reactor of Pyjoyment on gevent, selected before Pyjo.IOLoop is loaded
os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Gevent'

import Pyjo.HelloWorld  # noqa: E402
import Pyjo.IOLoop  # noqa: E402
import Pyjo.Server.Daemon  # noqa: E402
import Pyjo.UserAgent  # noqa: E402

import gevent  # noqa: E402


# The server, on a port that the system picks, and the user agent, in the same event loop, which close their sockets at
# the end of the block
with (
    Pyjo.Server.Daemon.new(app=Pyjo.HelloWorld.new(), listen=['http://127.0.0.1'], silent=True) as daemon,
    Pyjo.UserAgent.new(ioloop=Pyjo.IOLoop.singleton) as ua,
):
    # A blocking request, which runs the event loop of the server on the hub of gevent until the response
    tx = ua.get(f'http://127.0.0.1:{daemon.start().ports()[0]}/')
    reactor = Pyjo.IOLoop.singleton.reactor
    print(type(reactor).__name__, 'gevent' if getattr(reactor, 'hub', None) is gevent.get_hub() else 'other')
    print(tx.result.code, tx.result.text)
$ python examples/loopback_gevent.py
Pyjo_Reactor_Gevent gevent
200 Your Pyjo is working!

examples/greenlets_gevent.py is a server of Pyjoyment in the main greenlet, along with two greenlets of the application that request it, one with a socket of gevent and one with a blocking request of the user agent of Pyjoyment:

import os


# The reactor of Pyjoyment on gevent, selected before Pyjo.IOLoop is loaded
os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Gevent'

import Pyjo.HelloWorld  # noqa: E402
import Pyjo.IOLoop  # noqa: E402
import Pyjo.Server.Daemon  # noqa: E402
import Pyjo.UserAgent  # noqa: E402

import gevent  # noqa: E402
import gevent.socket  # noqa: E402


# A greenlet with a socket of gevent, which waits in the hub of gevent, where the server of Pyjoyment runs
def with_socket(port):
    with gevent.socket.create_connection(('127.0.0.1', port)) as sock:
        sock.sendall(b'GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n')
        response = b''
        while b'\r\n' not in response and (chunk := sock.recv(4096)):
            response += chunk
    status = response.split(b'\r\n')[0].decode()
    return f'gevent.socket: {status}'


# A greenlet with a blocking request of the user agent of Pyjoyment, whose event loop of its own waits in the greenlet
def with_user_agent(port):
    with Pyjo.UserAgent.new() as ua:
        tx = ua.get(f'http://127.0.0.1:{port}/')
    return f'Pyjo.UserAgent: {tx.result.code} {tx.result.text}'


# The server, on a port that the system picks, which runs in the main greenlet until the greenlets are done, and closes its
# listen sockets at the end of the block
with Pyjo.Server.Daemon.new(app=Pyjo.HelloWorld.new(), listen=['http://127.0.0.1'], silent=True) as daemon:
    port = daemon.start().ports()[0]
    greenlets = [gevent.spawn(with_socket, port), gevent.spawn(with_user_agent, port)]
    gevent.spawn(lambda: (gevent.joinall(greenlets), Pyjo.IOLoop.stop()))
    Pyjo.IOLoop.start()
    for greenlet in greenlets:
        print(greenlet.value)
$ python examples/greenlets_gevent.py
gevent.socket: HTTP/1.1 200 OK
Pyjo.UserAgent: 200 Your Pyjo is working!