An event-driven networking engine
=================================
Written in Python
-----------------
Licensed under the open source MIT License
[View Github](https://github.com/twisted/twisted) [View Documentation](https://docs.twisted.org/)
[Check PyPi download page](https://pypi.org/project/Twisted/)
`$ virtualenv try-twisted $ . try-twisted/bin/activate $ pip install twisted[tls] $ twist --help`
Premium Sponsors
[](https://thinkst.com/)
Twisted makes it easy to implement custom network applications. Here's a TCP server that echoes back everything that's written to it:
Copy
`from twisted.internet import protocol, reactor, endpoints class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(protocol.Factory): def buildProtocol(self, addr): return Echo() endpoints.serverFromString(reactor, "tcp:1234").listen(EchoFactory()) reactor.run()`
Learn more about [writing servers](https://docs.twisted.org/en/stable/core/howto/servers.html), [writing clients](https://docs.twisted.org/en/stable/core/howto/clients.html) and the [core networking libraries](https://docs.twisted.org/en/stable/core/howto/index.html), including support for SSL, UDP, scheduled events, unit testing infrastructure, and much more.
Twisted includes an event-driven web server. Here's a sample web application; notice how the resource object persists in memory, rather than being recreated on each request:
Copy
`from twisted.web import server, resource from twisted.internet import reactor, endpoints class Counter(resource.Resource): isLeaf = True numberRequests = 0 def render_GET(self, request): self.numberRequests += 1 request.setHeader(b"content-type", b"text/plain") content = u"I am request #{}\n".format(self.numberRequests) return content.encode("ascii") endpoints.serverFromString(reactor, "tcp:8080").listen(server.Site(Counter())) reactor.run()`
Learn more about [web application development](https://docs.twisted.org/en/stable/web/howto/web-in-60/index.html), [templates](https://docs.twisted.org/en/stable/web/howto/twisted-templates.html) and Twisted' [HTTP client](https://docs.twisted.org/en/stable/web/howto/client.html).
Here's a simple publish/subscribe server, where clients see all messages posted by other clients:
Copy
`from twisted.internet import reactor, protocol, endpoints from twisted.protocols import basic class PubProtocol(basic.LineReceiver): def __init__(self, factory): self.factory = factory def connectionMade(self): self.factory.clients.add(self) def connectionLost(self, reason): self.factory.clients.remove(self) def lineReceived(self, line): for c in self.factory.clients: source = u"<{}> ".format(self.transport.getHost()).encode("ascii") c.sendLine(source + line) class PubFactory(protocol.Factory): def __init__(self): self.clients = set() def buildProtocol(self, addr): return PubProtocol(self) endpoints.serverFromString(reactor, "tcp:1025").listen(PubFactory()) reactor.run()`
You can test this out by opening two terminals and doing telnet localhost 1025 in each, then typing things.
Twisted includes a sophisticated IMAP4 client library.
Copy
`import sys from twisted.internet import protocol, defer, endpoints, task from twisted.mail import imap4 from twisted.python import failure async def main( reactor, username="alice", password="secret", strport="tls:example.com:993" ): endpoint = endpoints.clientFromString(reactor, strport) factory = protocol.Factory.forProtocol(imap4.IMAP4Client) try: client = await endpoint.connect(factory) await client.login(username.encode("utf-8"), password.encode("utf-8")) await client.select("INBOX") info = await client.fetchEnvelope(imap4.MessageSet(1)) print("First message subject:", info[1]["ENVELOPE"][1]) except: print("IMAP4 client interaction failed") print(failure.Failure().getTraceback()) task.react(lambda *a, **k: defer.ensureDeferred(main(*a, **k)), sys.argv[1:])`
Give this a try, supplying your IMAP4 username, app password ([generate one for gmail](https://support.google.com/accounts/answer/185833?hl=en), [generate one for fastmail](https://www.fastmail.com/help/clients/apppassword.html)), and [client endpoint description](https://docs.twisted.org/en/stable/core/howto/endpoints.html) for your IMAP4 server. You'll see the subject of the first message in your mailbox printed.
See the [TwistedMail](https://github.com/twisted/trac-wiki-archive/blob/trunk/TwistedMail.mediawiki) documentation for more information.
Twisted includes an SSH client & server, "conch" (i.e.: the Twisted Shell).
Copy
`import sys, os from twisted.internet import protocol, defer, endpoints, task from twisted.conch.endpoints import SSHCommandClientEndpoint async def main(reactor, username="alice", sshhost="example.com", portno="22"): envAgent = endpoints.UNIXClientEndpoint(reactor, os.environ["SSH_AUTH_SOCK"]) endpoint = SSHCommandClientEndpoint.newConnection( reactor, "echo 'hello world'", username, sshhost, int(portno), agentEndpoint=envAgent, ) class ShowOutput(protocol.Protocol): received = b"" def dataReceived(self, data): self.received += data def connectionLost(self, reason): finished.callback(self.received) finished = defer.Deferred() factory = protocol.Factory.forProtocol(ShowOutput) await endpoint.connect(factory) print("SSH response:", await finished) task.react(lambda *a, **k: defer.ensureDeferred(main(*a, **k)), sys.argv[1:])`
You can use this client to run "hello world" on any SSH server that your local SSH agent can authenticate to, if you pass your username, host name, and optionally port number on the command line.
About Twisted
=============
### More Protocols
Twisted also supports many common network protocols, including SMTP, POP3, IMAP, SSHv2, and DNS.
For more information see our [documentation](https://docs.twisted.org/) and [API reference](https://docs.twisted.org/en/stable/api/).
### Community
Get in touch with the [Twisted community](https://docs.twisted.org/en/latest/community.html) through [email](https://docs.twisted.org/en/latest/community.html#mail-lists), [Stack Overflow](https://stackoverflow.com/questions/tagged/twisted) or [Gitter / IRC](https://docs.twisted.org/en/latest/community.html#real-time-chat).
### Contribute
Learn about the Twisted [development process](https://github.com/twisted/trac-wiki-archive/blob/trunk/TwistedDevelopment.mediawiki) and how to [contribute](https://github.com/twisted/trac-wiki-archive/blob/trunk/ContributingToTwistedLabs.mediawiki).
Help improve Twisted on [Windows](https://github.com/twisted/trac-wiki-archive/blob/trunk/Windows.mediawiki)!
### Wiki
Read about [software using](https://github.com/twisted/trac-wiki-archive/blob/trunk/ProjectsUsingTwisted.mediawiki) Twisted and their [success stories](https://github.com/twisted/trac-wiki-archive/blob/trunk/SuccessStories.mediawiki).
### Sponsors
Learn about the [individuals and organisations](https://docs.twisted.org/en/latest/development/sponsorship.html) that sponsor Twisted development.
### Twisted Matrix Laboratories
Find out what [Twisted Matrix Laboratories](https://github.com/twisted/trac-wiki-archive/blob/trunk/TwistedMatrixLaboratories.mediawiki) is.
#### See our code on Github
See the code [for Twisted](https://github.com/twisted/twisted) ([and more](https://github.com/twisted)) on GitHub.
#### Supported Python
It supports CPython 3.7+ and PyPy3.
[Twisted 20.3.0](https://labs.twistedmatrix.com/2020/03/twisted-drops-python-27-support.html) was the last version with Python 2.7 and PyPy2 support.
#### Join the [discussion list](https://mail.python.org/mailman3/lists/twisted.python.org/)
#### Report a [security issue](https://github.com/twisted/twisted/security/policy)
#### Ask on [Stack Overflow](https://stackoverflow.com/questions/tagged/twisted)
Twisted Sponsors
[](https://thinkst.com/)
[](https://www.sftpplus.com/)
Financial support can be provided for the Twisted project via [the Python Software Foundation](https://psfmember.org/civicrm/contribute/transact/?reset=1&id=44) or via [GitHub Sponsors](https://github.com/sponsors/twisted/) !
For donations greater than $400 per month, we will display your logo at the top of the page. For donations greater than $200 per month, we will display your logo on this page. Check [GitHub Sponsors](https://github.com/sponsors/twisted/) for more information about sponsoring perks.
Donate to Twisted
=================
Donations are tax-deductible in USA
[via the Python Software Foundation](https://www.python.org/psf-landing/).
[Donate (via PSF)](https://psfmember.org/civicrm/contribute/transact/?reset=1&id=44)