本文整理汇总了Python中twisted.internet.protocol.Protocol方法的典型用法代码示例。如果您正苦于以下问题:Python protocol.Protocol方法的具体用法?Python protocol.Protocol怎么用?Python protocol.Protocol使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.protocol
的用法示例。
在下文中一共展示了protocol.Protocol方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: twisted_coroutine_fetch
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def twisted_coroutine_fetch(self, url, runner):
body = [None]
@gen.coroutine
def f():
# This is simpler than the non-coroutine version, but it cheats
# by reading the body in one blob instead of streaming it with
# a Protocol.
client = Agent(self.reactor)
response = yield client.request(b'GET', utf8(url))
with warnings.catch_warnings():
# readBody has a buggy DeprecationWarning in Twisted 15.0:
# https://twistedmatrix.com/trac/changeset/43379
warnings.simplefilter('ignore', category=DeprecationWarning)
body[0] = yield readBody(response)
self.stop_loop()
self.io_loop.add_callback(f)
runner()
return body[0]
示例2: parseVersion
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def parseVersion(self, strversion):
"""
Parse version strings of the form Protocol '/' Major '.' Minor. E.g.
b'HTTP/1.1'. Returns (protocol, major, minor). Will raise ValueError
on bad syntax.
"""
try:
proto, strnumber = strversion.split(b'/')
major, minor = strnumber.split(b'.')
major, minor = int(major), int(minor)
except ValueError as e:
raise BadResponseVersion(str(e), strversion)
if major < 0 or minor < 0:
raise BadResponseVersion(u"version may not be negative",
strversion)
return (proto, major, minor)
示例3: test_makeConnection
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_makeConnection(self):
"""
The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{makeConnection} method called with an L{IPushProducer} provider
hooked up to the response as an argument.
"""
producers = []
transport = StringTransport()
class SomeProtocol(Protocol):
def makeConnection(self, producer):
producers.append(producer)
consumer = SomeProtocol()
response = justTransportResponse(transport)
response.deliverBody(consumer)
[theProducer] = producers
theProducer.pauseProducing()
self.assertEqual(transport.producerState, u'paused')
theProducer.resumeProducing()
self.assertEqual(transport.producerState, u'producing')
示例4: test_connectionLost
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_connectionLost(self):
"""
The L{IProtocol} provider passed to L{Response.deliverBody} has its
C{connectionLost} method called with a L{Failure} wrapping
L{ResponseDone} when the response's C{_bodyDataFinished} method is
called.
"""
lost = []
class ListConsumer(Protocol):
def connectionLost(self, reason):
lost.append(reason)
consumer = ListConsumer()
response = justTransportResponse(StringTransport())
response.deliverBody(consumer)
response._bodyDataFinished()
lost[0].trap(ResponseDone)
self.assertEqual(len(lost), 1)
# The protocol reference should be dropped, too, to facilitate GC or
# whatever.
self.assertIdentical(response._bodyProtocol, None)
示例5: test_bufferEarlyData
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_bufferEarlyData(self):
"""
If data is delivered to the L{Response} before a protocol is registered
with C{deliverBody}, that data is buffered until the protocol is
registered and then is delivered.
"""
bytes = []
class ListConsumer(Protocol):
def dataReceived(self, data):
bytes.append(data)
protocol = ListConsumer()
response = justTransportResponse(StringTransport())
response._bodyDataReceived(b'foo')
response._bodyDataReceived(b'bar')
response.deliverBody(protocol)
response._bodyDataReceived(b'baz')
self.assertEqual(bytes, [b'foo', b'bar', b'baz'])
# Make sure the implementation-detail-byte-buffer is cleared because
# not clearing it wastes memory.
self.assertIdentical(response._bodyBuffer, None)
示例6: test_transportResumed
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_transportResumed(self):
"""
L{Response.deliverBody} resumes the HTTP connection's transport
after passing it to the consumer's C{makeConnection} method.
"""
transportState = []
class ListConsumer(Protocol):
def makeConnection(self, transport):
transportState.append(transport.producerState)
transport = StringTransport()
transport.pauseProducing()
protocol = ListConsumer()
response = justTransportResponse(transport)
self.assertEqual(transport.producerState, u'paused')
response.deliverBody(protocol)
self.assertEqual(transportState, [u'paused'])
self.assertEqual(transport.producerState, u'producing')
示例7: setUp
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def setUp(self):
"""
Construct a L{StandardIOEndpoint} with a dummy reactor and a fake
L{stdio.StandardIO} like object. Listening on it with a
L{SpecificFactory}.
"""
self.reactor = object()
endpoint = endpoints.StandardIOEndpoint(self.reactor)
self.assertIs(endpoint._stdio, stdio.StandardIO)
endpoint._stdio = FakeStdio
self.specificProtocol = Protocol()
self.fakeStdio = self.successResultOf(
endpoint.listen(SpecificFactory(self.specificProtocol))
)
示例8: test_deferBadEncodingToConnect
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_deferBadEncodingToConnect(self):
"""
Since any client of L{IStreamClientEndpoint} needs to handle Deferred
failures from C{connect}, L{HostnameEndpoint}'s constructor will not
raise exceptions when given bad host names, instead deferring to
returning a failing L{Deferred} from C{connect}.
"""
endpoint = endpoints.HostnameEndpoint(
deterministicResolvingReactor(MemoryReactor(), ['127.0.0.1']),
b'\xff-garbage-\xff', 80
)
deferred = endpoint.connect(Factory.forProtocol(Protocol))
err = self.failureResultOf(deferred, ValueError)
self.assertIn("\\xff-garbage-\\xff", str(err))
endpoint = endpoints.HostnameEndpoint(
deterministicResolvingReactor(MemoryReactor(), ['127.0.0.1']),
u'\u2ff0-garbage-\u2ff0', 80
)
deferred = endpoint.connect(Factory())
err = self.failureResultOf(deferred, ValueError)
self.assertIn("\\u2ff0-garbage-\\u2ff0", str(err))
示例9: test_removeWriter
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_removeWriter(self):
"""
Removing a filesystem file writer from a reactor will make sure it is
no longer polled.
"""
reactor = self.buildReactor()
self.addCleanup(self.unbuildReactor, reactor)
# Cleanup might fail if file is GCed too soon:
self.f = f = open(self.mktemp(), "wb")
# Have the reader added:
protocol = Protocol()
stdio = StandardIO(protocol, stdout=f.fileno(),
stdin=self.extraFile.fileno(),
reactor=reactor)
protocol.transport.write(b"hello")
self.assertIn(stdio._writer, reactor.getWriters())
stdio._writer.stopWriting()
self.assertNotIn(stdio._writer, reactor.getWriters())
示例10: test_removeAll
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_removeAll(self):
"""
Calling C{removeAll} on a reactor includes descriptors that are
filesystem files.
"""
reactor = self.buildReactor()
self.addCleanup(self.unbuildReactor, reactor)
path = self.mktemp()
open(path, "wb").close()
# Cleanup might fail if file is GCed too soon:
self.f = f = open(path, "rb")
# Have the reader added:
stdio = StandardIO(Protocol(), stdin=f.fileno(),
stdout=self.extraFile.fileno(), reactor=reactor)
# And then removed:
removed = reactor.removeAll()
self.assertIn(stdio._reader, removed)
self.assertNotIn(stdio._reader, reactor.getReaders())
示例11: test_getReaders
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_getReaders(self):
"""
C{reactor.getReaders} includes descriptors that are filesystem files.
"""
reactor = self.buildReactor()
self.addCleanup(self.unbuildReactor, reactor)
path = self.mktemp()
open(path, "wb").close()
# Cleanup might fail if file is GCed too soon:
with open(path, "rb") as f:
# Have the reader added:
stdio = StandardIO(Protocol(), stdin=f.fileno(),
stdout=self.extraFile.fileno(), reactor=reactor)
self.assertIn(stdio._reader, reactor.getReaders())
示例12: test_getWriters
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_getWriters(self):
"""
C{reactor.getWriters} includes descriptors that are filesystem files.
"""
reactor = self.buildReactor()
self.addCleanup(self.unbuildReactor, reactor)
# Cleanup might fail if file is GCed too soon:
self.f = f = open(self.mktemp(), "wb")
# Have the reader added:
stdio = StandardIO(Protocol(), stdout=f.fileno(),
stdin=self.extraFile.fileno(), reactor=reactor)
self.assertNotIn(stdio._writer, reactor.getWriters())
stdio._writer.startWriting()
self.assertIn(stdio._writer, reactor.getWriters())
示例13: test_interfacesForTransport
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def test_interfacesForTransport(self):
"""
If the protocol objects returned by the factory given to
L{ClientService} provide special "marker" interfaces for their
transport - L{IHalfCloseableProtocol} or L{IFileDescriptorReceiver} -
those interfaces will be provided by the protocol objects passed on to
the reactor.
"""
@implementer(IHalfCloseableProtocol, IFileDescriptorReceiver)
class FancyProtocol(Protocol, object):
"""
Provider of various interfaces.
"""
cq, service = self.makeReconnector(protocolType=FancyProtocol)
reactorFacing = cq.constructedProtocols[0]
self.assertTrue(IFileDescriptorReceiver.providedBy(reactorFacing))
self.assertTrue(IHalfCloseableProtocol.providedBy(reactorFacing))
示例14: retrieveFile
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def retrieveFile(self, path, protocol, offset=0):
"""
Retrieve a file from the given path
This method issues the 'RETR' FTP command.
The file is fed into the given Protocol instance. The data connection
will be passive if self.passive is set.
@param path: path to file that you wish to receive.
@param protocol: a L{Protocol} instance.
@param offset: offset to start downloading from
@return: L{Deferred}
"""
cmds = ['RETR ' + self.escapePath(path)]
if offset:
cmds.insert(0, ('REST ' + str(offset)))
return self.receiveFromConnection(cmds, protocol)
示例15: list
# 需要导入模块: from twisted.internet import protocol [as 别名]
# 或者: from twisted.internet.protocol import Protocol [as 别名]
def list(self, path, protocol):
"""
Retrieve a file listing into the given protocol instance.
This method issues the 'LIST' FTP command.
@param path: path to get a file listing for.
@param protocol: a L{Protocol} instance, probably a
L{FTPFileListProtocol} instance. It can cope with most common file
listing formats.
@return: L{Deferred}
"""
if path is None:
path = ''
return self.receiveFromConnection(['LIST ' + self.escapePath(path)], protocol)