Twisted Asynchronous Networking Framework
Twisted is a powerful, event-driven networking framework for Python, enabling asynchronous programming with a strong emphasis on protocols and concurrency. It provides abstractions for common network programming tasks, including TCP/UDP, HTTP, DNS, and more. It is actively maintained with frequent releases, typically every 1-3 months. The current stable version is 25.5.0.
Warnings
- breaking The methods `deferSetUp`, `deferTestMethod`, `deferTearDown`, and `deferRunCleanups` on `twisted.trial.unittest.TestCase` have been removed.
- gotcha Any blocking call (e.g., `time.sleep()`, synchronous I/O, long-running computations) will halt the entire Twisted reactor and block all other active connections and operations.
- gotcha The `twisted.python.failure.Failure` object, which encapsulates tracebacks for error handling, no longer records the exact point of its creation for performance reasons.
- gotcha Understanding and correctly chaining `defer.Deferred` objects, especially handling errors (errbacks), can be complex. Unhandled errors in a Deferred chain can silently disappear or lead to unexpected behavior.
Install
-
pip install twisted
Imports
- reactor
from twisted.internet import reactor
- protocol
from twisted.internet import protocol
- defer
from twisted.internet import defer
- server
from twisted.web import server, resource
Quickstart
from twisted.internet import reactor, protocol
class Echo(protocol.Protocol):
"""As soon as any data is received, send it back."""
def dataReceived(self, data):
self.transport.write(data)
class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()
if __name__ == '__main__':
# This will run the protocol on port 8000
reactor.listenTCP(8000, EchoFactory())
print("Echo server started on port 8000. Press Ctrl+C to stop.")
reactor.run()