Highly concurrent networking library
npx @tessl/cli install tessl/pypi-eventlet@0.40.0A concurrent networking library for Python that enables developers to write scalable network applications using coroutines and non-blocking I/O. Eventlet provides a blocking programming style similar to threading while delivering the performance benefits of asynchronous I/O through epoll or libevent.
pip install eventletimport eventletCommon imports for networking and concurrency:
from eventlet import GreenPool, spawn, sleep
from eventlet.green import socket, ssl
import eventlet.wsgiimport eventlet
# Enable monkey patching for cooperative networking
eventlet.monkey_patch()
def handle_client(sock, addr):
"""Handle a client connection"""
try:
data = sock.recv(1024)
sock.send(b"Echo: " + data)
finally:
sock.close()
def server():
"""Simple echo server"""
server_sock = eventlet.listen(('localhost', 8080))
print("Server listening on localhost:8080")
pool = eventlet.GreenPool(1000) # Max 1000 concurrent connections
try:
while True:
client_sock, addr = server_sock.accept()
pool.spawn(handle_client, client_sock, addr)
except KeyboardInterrupt:
print("Server shutting down")
finally:
server_sock.close()
if __name__ == "__main__":
server()Eventlet is built around several core concepts:
This design enables high-concurrency applications while maintaining familiar blocking programming patterns, making it easy to integrate into existing applications without requiring significant code restructuring.
Essential green threading primitives for managing cooperative concurrency, including spawning greenthreads, controlling execution flow, and managing lifecycle.
def spawn(func, *args, **kwargs): ...
def spawn_n(func, *args, **kwargs): ...
def spawn_after(seconds, func, *args, **kwargs): ...
def spawn_after_local(seconds, func, *args, **kwargs): ...
def sleep(seconds=0): ...
def kill(gt, exc_type=None): ...
def getcurrent(): ...Thread-safe synchronization tools including events, semaphores, queues, and timeouts for coordinating between greenthreads.
class Event:
def send(self, result=None): ...
def wait(self, timeout=None): ...
def ready(self): ...
def has_exception(self): ...
def has_result(self): ...
def poll(self, notready=None): ...
def send_exception(self, *args): ...
class Semaphore:
def acquire(self, blocking=True): ...
def release(self): ...
class Queue:
def put(self, item, block=True, timeout=None): ...
def get(self, block=True, timeout=None): ...Managed pools of green threads for controlling concurrency levels and resource usage in high-throughput applications.
class GreenPool:
def __init__(self, size=1000): ...
def spawn(self, func, *args, **kwargs): ...
def spawn_n(self, func, *args, **kwargs): ...
def waitall(self): ...
def resize(self, new_size): ...
def imap(self, func, *iterables): ...
def starmap(self, func, iterable): ...
class GreenPile:
def spawn(self, func, *args, **kwargs): ...
def __iter__(self): ...
def next(self): ...High-level networking functions and utilities for creating client and server applications with SSL/TLS support.
def connect(addr, family=socket.AF_INET, bind=None): ...
def listen(addr, family=socket.AF_INET, backlog=50, reuse_addr=True, reuse_port=None): ...
def serve(sock, handle, concurrency=1000): ...
def wrap_ssl(sock, *args, **kw): ...Production-ready WSGI server implementation for hosting web applications with built-in support for WebSocket upgrades.
def server(sock, site, log=None, environ=None, max_size=None,
max_http_version=None, protocol=wsgi.HttpProtocol,
server_event=None, minimum_chunk_size=None,
log_x_forwarded_for=True, custom_pool=None,
keepalive=True, log_output=True, log_format=None,
url_length_limit=8192, debug=True, socket_timeout=60,
capitalize_response_headers=True): ...System for transparently replacing standard library modules with green cooperative versions.
def monkey_patch(os=True, select=True, socket=True, thread=True,
time=True, ssl=True, httplib=False,
subprocess=False, all=None, profile=False,
aggressive=True): ...
def import_patched(modulename, *additional_modules, **kw_additional_modules): ...
def is_monkey_patched(module): ...Cooperative versions of Python standard library modules that work seamlessly with eventlet's green threading model.
# Available green modules
import eventlet.green.socket
import eventlet.green.ssl
import eventlet.green.urllib.request
import eventlet.green.http.client
import eventlet.green.threading
import eventlet.green.subprocess
# ... and many moreGeneric resource pooling for managing expensive resources like database connections with automatic lifecycle management.
class Pool:
def __init__(self, min_size=0, max_size=4, order_as_stack=False, create=None): ...
def get(self): ...
def put(self, item): ...
def item(self): ...
class TokenPool(Pool):
def __init__(self, max_size=4): ...
def create(self): ...
class ConnectionPool:
def __init__(self, db_module, *args, **kwargs): ...
def get(self): ...
def put(self, conn): ...Tools for debugging, introspection, and monitoring eventlet applications including tracing, hub inspection, and performance analysis.
def spew(): ...
def unspew(): ...
def format_hub_listeners(): ...
def format_hub_timers(): ...
def hub_blocking_detection(state): ...class GreenThread:
"""A greenlet subclass that can be used to retrieve return values."""
def wait(self): ...
def kill(self, exc_type=None): ...
def link(self, func, *curried_args, **curried_kwargs): ...
def unlink(self, func, *curried_args, **curried_kwargs): ...
class StopServe(Exception):
"""Exception class used to gracefully stop a serve() loop."""
pass
class Timeout(Exception):
"""A timeout context manager and exception."""
def __init__(self, seconds=None, exception=None): ...
def __enter__(self): ...
def __exit__(self, typ, value, tb): ...