Twisted and python 3

Porting to Python 3¶

Twisted is currently being ported to work with Python 3.5+. This document covers Twisted-specific issues in porting your code to Python 3.

Most, but not all, of Twisted has been ported, and therefore only a subset of modules are installed under Python 3. You can see the remaining modules that need to be ported at twisted.python._setup.notPortedModules, if it is not listed there, then most of all of that module will be ported.

API Differences¶

twisted.python.failure¶

Failure.trap raises itself (i.e. a Failure ) in Python 2. In Python 3, the wrapped exception will be re-raised.

Byte Strings and Text Strings¶

Several APIs which on Python 2 accepted or produced byte strings (instances of str , sometimes just called bytes ) have changed to accept or produce text strings (instances of str , sometimes just called text or unicode ) on Python 3.

From twisted.internet.address , the IPv4Address and IPv6Address classes have had two attributes change from byte strings to text strings: type and host .

twisted.python.log has shifted significantly towards text strings from byte strings. Logging events, particular those produced by a call like msg(«foo») , must now be text strings. Consequently, on Python 3, event dictionaries passed to log observes will contain text strings where they previously contained byte strings.

twisted.python.runtime.platformType and the return value from twisted.python.runtime.Platform.getType are now both text strings.

twisted.python.filepath.FilePath has not changed. It supports only byte strings. This will probably require applications to update their usage of FilePath , at least to pass explicit byte string literals rather than “native” string literals (which are text on Python 3).

reactor.addSystemEventTrigger arguments that were previously byte strings are now native strings.

twisted.names.dns deals with strings with a wide range of meanings, often several for each DNS record type. Most of these strings have remained as byte strings, which will probably require application updates (for the reason given in the FilePath section above). Some strings have changed to text strings, though. Any string representing a human readable address (for example, Record_A ‘s address parameter) is now a text string. Additionally, time-to-live (ttl) values given as strings must now be given as text strings.

twisted.web.resource.IResource continues to deal with URLs and all URL-derived values as byte strings.

Читайте также:  Java thread is active

twisted.web.resource.ErrorPage has several string attributes ( template , brief , and detail ) which were previously byte strings. On Python 3 only, these must now be text strings.

© Copyright 2017, Twisted Matrix Labs Revision 121c98e0 .

Источник

An event-driven networking engine

Twisted makes it easy to implement custom network applications. Here’s a TCP server that echoes back everything that’s written to it:

 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, writing clients and the core networking libraries, 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:

 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() 

Here’s a simple publish/subscribe server, where clients see all messages posted by other clients:

 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.

 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, generate one for fastmail), and client endpoint description for your IMAP4 server. You’ll see the subject of the first message in your mailbox printed.

See the TwistedMail documentation for more information.

Twisted includes an SSH client & server, «conch» (i.e.: the Twisted Shell).

 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.

Читайте также:  Map object python to array

Источник

Porting to Python 3¶

Twisted is currently being ported to work with Python 3.4+. This document covers Twisted-specific issues in porting your code to Python 3.

Most, but not all, of Twisted has been ported, and therefore only a subset of modules are installed under Python 3. You can see the remaining modules that need to be ported at twisted.python._setup.notPortedModules, if it is not listed there, then most of all of that module will be ported.

API Differences¶

twisted.python.failure¶

Failure.trap raises itself (i.e. a Failure ) in Python 2. In Python 3, the wrapped exception will be re-raised.

Byte Strings and Text Strings¶

Several APIs which on Python 2 accepted or produced byte strings (instances of str , sometimes just called bytes ) have changed to accept or produce text strings (instances of str , sometimes just called text or unicode ) on Python 3.

From twisted.internet.address , the IPv4Address and IPv6Address classes have had two attributes change from byte strings to text strings: type and host .

twisted.python.log has shifted significantly towards text strings from byte strings. Logging events, particular those produced by a call like msg(«foo») , must now be text strings. Consequently, on Python 3, event dictionaries passed to log observes will contain text strings where they previously contained byte strings.

twisted.python.runtime.platformType and the return value from twisted.python.runtime.Platform.getType are now both text strings.

twisted.python.filepath.FilePath has not changed. It supports only byte strings. This will probably require applications to update their usage of FilePath , at least to pass explicit byte string literals rather than “native” string literals (which are text on Python 3).

reactor.addSystemEventTrigger arguments that were previously byte strings are now native strings.

twisted.names.dns deals with strings with a wide range of meanings, often several for each DNS record type. Most of these strings have remained as byte strings, which will probably require application updates (for the reason given in the FilePath section above). Some strings have changed to text strings, though. Any string representing a human readable address (for example, Record_A ‘s address parameter) is now a text string. Additionally, time-to-live (ttl) values given as strings must now be given as text strings.

Читайте также:  Структура html страницы основные теги таблицы html

twisted.web.resource.IResource continues to deal with URLs and all URL-derived values as byte strings.

twisted.web.resource.ErrorPage has several string attributes ( template , brief , and detail ) which were previously byte strings. On Python 3 only, these must now be text strings.

© Copyright 2017, Twisted Matrix Labs. Revision 6bee026e .

Источник

Porting to Python 3¶

Twisted currently supports only Python 3.6+. This document covers Twisted-specific issues in porting your code to Python 3.

API Differences¶

twisted.python.failure¶

Failure.trap raises itself (i.e. a Failure ) in Python 2. In Python 3, the wrapped exception will be re-raised.

Byte Strings and Text Strings¶

Several APIs which on Python 2 accepted or produced byte strings (instances of str , sometimes just called bytes ) have changed to accept or produce text strings (instances of str , sometimes just called text or unicode ) on Python 3.

From twisted.internet.address , the IPv4Address and IPv6Address classes have had two attributes change from byte strings to text strings: type and host .

twisted.python.log has shifted significantly towards text strings from byte strings. Logging events, particular those produced by a call like msg(«foo») , must now be text strings. Consequently, on Python 3, event dictionaries passed to log observes will contain text strings where they previously contained byte strings.

twisted.python.runtime.platformType and the return value from twisted.python.runtime.Platform.getType are now both text strings.

twisted.python.filepath.FilePath has not changed. It supports only byte strings. This will probably require applications to update their usage of FilePath , at least to pass explicit byte string literals rather than “native” string literals (which are text on Python 3).

reactor.addSystemEventTrigger arguments that were previously byte strings are now native strings.

twisted.names.dns deals with strings with a wide range of meanings, often several for each DNS record type. Most of these strings have remained as byte strings, which will probably require application updates (for the reason given in the FilePath section above). Some strings have changed to text strings, though. Any string representing a human readable address (for example, Record_A ‘s address parameter) is now a text string. Additionally, time-to-live (ttl) values given as strings must now be given as text strings.

twisted.web.resource.IResource continues to deal with URLs and all URL-derived values as byte strings.

twisted.web.resource.ErrorPage has several string attributes ( template , brief , and detail ) which were previously byte strings. On Python 3 only, these must now be text strings.

© Copyright 2022, Twisted Matrix Labs. Ver 22.10.0. Built on 2022-11-03. Revision 39ee213f .

Источник

Оцените статью