本文整理汇总了Python中twisted.internet.defer.DeferredQueue.get方法的典型用法代码示例。如果您正苦于以下问题:Python DeferredQueue.get方法的具体用法?Python DeferredQueue.get怎么用?Python DeferredQueue.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer.DeferredQueue
的用法示例。
在下文中一共展示了DeferredQueue.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Game
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class Game(Protocol):
def __init__(self, users):
self.users = users
self.queue = DeferredQueue()
def connectionMade(self):
global state
connections['GAME'] = self
state = "GO"
self.flag = True
def dataReceived(self, data):
self.queue.put(data)
self.queue.get().addCallback(self.ForwardData)
def ForwardData(self, data):
positions = pickle.loads(data)
if is_client == "host":
gs.player2.rect = positions["p2_rect"]
gs.player2.image = pygame.transform.rotate(gs.player2.orig_image, positions["p2_angle"])
if positions["firing"] == True:
mx = positions["mouse_x"]
my = positions["mouse_y"]
self.laser = P2_Laser(gs.player2.rect.centerx, gs.player2.rect.centery,mx,my,gs)
self.laser.rect.x = gs.player2.rect.centerx
self.laser.rect.y = gs.player2.rect.centery
# Add the laser to the lists
gs.laser_list2.add(self.laser)
gs.all_sprites_list.add(self.laser)
else:
gs.player1.rect = positions["p1_rect"]
gs.player1.image = pygame.transform.rotate(gs.player1.orig_image, positions["p1_angle"])
if positions["firing"] == True:
mx = positions["mouse_x"]
my = positions["mouse_y"]
self.laser = P1_Laser(gs.player1.rect.centerx, gs.player1.rect.centery,mx,my,gs)
self.laser.rect.x = gs.player1.rect.centerx
self.laser.rect.y = gs.player1.rect.centery
# Add the laser to the lists
gs.laser_list1.add(self.laser)
gs.all_sprites_list.add(self.laser)
if positions["change"] == True:
gs.player2.rect.x = positions["newx"]
gs.player2.rect.y = positions["newy"]
if self.queue.waiting > 0:
self.queue.get().addCallback(self.ForwardData)
def connectionLost(self,reason):
print "Connection lost - goodbye!"
reactor.stop()
def clientConnectionLost(self, reason):
print "Connection lost - goodbye!"
reactor.stop()
示例2: TestStreamingClient
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class TestStreamingClient(VumiTestCase):
def setUp(self):
self.fake_http = FakeHttpServer(self.handle_request)
self.request_queue = DeferredQueue()
self.client = StreamingClient(self.fake_http.get_agent)
self.messages_received = DeferredQueue()
self.errors_received = DeferredQueue()
self.disconnects_received = DeferredQueue()
def reason_trapper(reason):
if reason.trap(ResponseDone):
self.disconnects_received.put(reason.getErrorMessage())
self.receiver = self.client.stream(
Message,
self.messages_received.put, self.errors_received.put,
"http://vumi-go-api.example.com/", on_disconnect=reason_trapper)
def handle_request(self, request):
self.request_queue.put(request)
return NOT_DONE_YET
def test_default_agent_factory(self):
"""
If `None` is passed as the `agent_factory`, `Agent` is used instead.
"""
self.assertNotIsInstance(self.client.agent, Agent)
self.assertIsInstance(StreamingClient(None).agent, Agent)
self.assertIsInstance(StreamingClient().agent, Agent)
@inlineCallbacks
def test_callback_on_disconnect(self):
req = yield self.request_queue.get()
req.write(
'%s\n' % (Message(foo='bar').to_json().encode('utf-8'),))
req.finish()
message = yield self.messages_received.get()
self.assertEqual(message['foo'], 'bar')
reason = yield self.disconnects_received.get()
# this is the error message we get when a ResponseDone is raised
# which happens when the remote server closes the connection.
self.assertEqual(reason, 'Response body fully received')
@inlineCallbacks
def test_invalid_json(self):
req = yield self.request_queue.get()
req.write("Hello\n")
req.finish()
err = yield self.assertFailure(
self.errors_received.get(), VumiBridgeInvalidJsonError)
self.assertEqual(err.args, ("Hello",))
示例3: TcpProxyProtocol
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class TcpProxyProtocol(Protocol, object):
"""A simple TCP proxy"""
def __init__(self):
"""Create a new TCP proxy.
`self.server_queue` contains messages from end server to client.
`self.client_queue` contains messages from client to end server.
"""
self.server_queue = DeferredQueue()
self.client_queue = DeferredQueue()
self.server_queue.get().addCallback(self.serverQueueCallback)
def connectServer(self, hostname, port):
"""Tell the proxy what the end server is and start the connection.
The messages in `self.client_queue` will automatically be consumed.
This method should only be called once.
:param str hostname:
:param int port:
"""
endpoint = TCP4ClientEndpoint(reactor, hostname, port)
protocol = ServerProtocol(
self.server_queue, self.client_queue)
connectProtocol(endpoint, protocol)
def serverQueueCallback(self, data):
"""A callback for `self.server_queue`
:param str data: data from server queue
"""
if data is False:
self.transport.loseConnection()
return
self.transport.write(data)
self.server_queue.get().addCallback(self.serverQueueCallback)
def dataReceived(self, data):
"""Received data from client, put into client queue
"""
self.client_queue.put(data)
def connectionLost(self, why):
"""Client closed connection, or some other issue. close connection
to server
"""
self.client_queue.put(False)
示例4: TestStreamingClient
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class TestStreamingClient(VumiTestCase):
@inlineCallbacks
def setUp(self):
self.mock_server = MockHttpServer(self.handle_request)
self.add_cleanup(self.mock_server.stop)
yield self.mock_server.start()
self.url = self.mock_server.url
self.client = StreamingClient()
self.messages_received = DeferredQueue()
self.errors_received = DeferredQueue()
self.disconnects_received = DeferredQueue()
def reason_trapper(reason):
if reason.trap(ResponseDone):
self.disconnects_received.put(reason.getErrorMessage())
self.receiver = self.client.stream(
Message,
self.messages_received.put, self.errors_received.put,
self.url, on_disconnect=reason_trapper)
def handle_request(self, request):
self.mock_server.queue.put(request)
return NOT_DONE_YET
@inlineCallbacks
def test_callback_on_disconnect(self):
req = yield self.mock_server.queue.get()
req.write(
'%s\n' % (Message(foo='bar').to_json().encode('utf-8'),))
req.finish()
message = yield self.messages_received.get()
self.assertEqual(message['foo'], 'bar')
reason = yield self.disconnects_received.get()
# this is the error message we get when a ResponseDone is raised
# which happens when the remote server closes the connection.
self.assertEqual(reason, 'Response body fully received')
@inlineCallbacks
def test_invalid_json(self):
req = yield self.mock_server.queue.get()
req.write("Hello\n")
req.finish()
try:
yield self.errors_received.get()
except VumiBridgeInvalidJsonError, e:
self.assertEqual(e.args, ("Hello",))
else:
示例5: home_DataConn
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class home_DataConn(protocol.Protocol):
def __init__(self):
print 'home listening for data connection from work'
self.queue = DeferredQueue()
def connectionMade(self):
home_connections['data_conn'] = self
self.queue.get().addCallback(self.forwardData)
def dataReceived(self, data):
self.queue.put(data)
def forwardData(self, data):
home_connections['client_conn'].transport.write(data)
self.queue.get().addCallback(self.forwardData)
示例6: work_ServiceConn
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class work_ServiceConn(protocol.Protocol):
def __init__(self):
print 'service connection established'
self.queue = DeferredQueue()
def connectionMade(self):
work_connections['service_conn'] = self
self.queue.get().addCallback(self.forwardData)
def dataReceived(self, data):
self.queue.put(data)
def forwardData(self, data):
work_connections['data_conn'].transport.write(data)
self.queue.get().addCallback(self.forwardData)
示例7: ProcessPool
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class ProcessPool(object):
def __init__(self, count=10):
self.limiter = DeferredSemaphore(count)
self.processes = [spawnProcess() for _ in xrange(count)]
self.workQueue = DeferredQueue()
for process in self.processes:
process.onconnect.addCallback(self._prepareForWork)
@inlineCallbacks
def _prepareForWork(self, proto):
deferred, func, args = yield self.workQueue.get()
proto.queueWork(deferred, func, *args)
def requeue(result):
self._prepareForWork(proto)
return result
deferred.addCallback(requeue)
returnValue(proto)
def queueWork(self, function, *args):
resultDeferred = Deferred()
innerDeferred = Deferred()
self.workQueue.put((innerDeferred, function, args))
def callResult(obj):
resultDeferred.callback(obj)
return obj
innerDeferred.addCallback(callResult)
return resultDeferred
def stop(self):
for process in self.processes:
process.protocol.kill()
process.transport.loseConnection()
示例8: QueuePoller
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class QueuePoller(object):
implements(IPoller)
def __init__(self, settings):
self.q = RedisSpiderQueue(settings)
self.dq = DeferredQueue(size=1)
@inlineCallbacks
def poll(self):
if self.dq.pending:
return
c = yield maybeDeferred(self.q.count)
if c:
msg = yield maybeDeferred(self.q.pop)
returnValue(self.dq.put(self._message(msg)))
def next(self):
return self.dq.get()
def _message(self, queue_msg):
d = queue_msg.copy()
d['_project'] = SCRAPY_PROJECT
d['_spider'] = d.pop('name')
d['_job'] = d.pop('jobid', uuid.uuid1().hex)
return d
示例9: QueuePoller
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class QueuePoller(object):
def __init__(self, config):
self.config = config
self.update_projects()
self.dq = DeferredQueue()
@inlineCallbacks
def poll(self):
if not self.dq.waiting:
return
for p, q in iteritems(self.queues):
c = yield maybeDeferred(q.count)
if c:
msg = yield maybeDeferred(q.pop)
if msg is not None: # In case of a concurrently accessed queue
returnValue(self.dq.put(self._message(msg, p)))
def next(self):
return self.dq.get()
def update_projects(self):
self.queues = get_spider_queues(self.config)
def _message(self, queue_msg, project):
d = queue_msg.copy()
d['_project'] = project
d['_spider'] = d.pop('name')
return d
示例10: SSMIServerProtocol
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class SSMIServerProtocol(Protocol):
delimiter = TruteqTransportProtocol.delimiter
def __init__(self):
self.receive_queue = DeferredQueue()
self._buf = b""
def dataReceived(self, data):
self._buf += data
self.parse_commands()
def parse_commands(self):
while self.delimiter in self._buf:
line, _, self._buf = self._buf.partition(self.delimiter)
if line:
self.receive_queue.put(SSMIRequest.parse(line))
def send(self, command):
self.transport.write(str(command))
self.transport.write(self.delimiter)
return wait0()
def receive(self):
return self.receive_queue.get()
def disconnect(self):
self.transport.loseConnection()
示例11: test_messages_stream
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
def test_messages_stream(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
messages = DeferredQueue()
errors = DeferredQueue()
receiver = self.client.stream(
TransportUserMessage, messages.put, errors.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
msg2 = yield self.app_helper.make_dispatch_inbound(
'in 2', message_id='2', conv=self.conversation)
rm1 = yield messages.get()
rm2 = yield messages.get()
receiver.disconnect()
# Sometimes messages arrive out of order if we're hitting real redis.
rm1, rm2 = sorted([rm1, rm2], key=lambda m: m['message_id'])
self.assertEqual(msg1['message_id'], rm1['message_id'])
self.assertEqual(msg2['message_id'], rm2['message_id'])
self.assertEqual(errors.size, None)
示例12: test_events_stream
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
def test_events_stream(self):
url = '%s/%s/events.json' % (self.url, self.conversation.key)
events = DeferredQueue()
errors = DeferredQueue()
receiver = yield self.client.stream(TransportEvent, events.put,
events.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 1', message_id='1')
ack1 = yield self.app_helper.make_dispatch_ack(
msg1, conv=self.conversation)
msg2 = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 2', message_id='2')
ack2 = yield self.app_helper.make_dispatch_ack(
msg2, conv=self.conversation)
ra1 = yield events.get()
ra2 = yield events.get()
receiver.disconnect()
self.assertEqual(ack1['event_id'], ra1['event_id'])
self.assertEqual(ack2['event_id'], ra2['event_id'])
self.assertEqual(errors.size, None)
示例13: test_health_response
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
def test_health_response(self):
health_url = 'http://%s:%s%s' % (
self.addr.host, self.addr.port, self.config['health_path'])
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
yield self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
queue = DeferredQueue()
stream_url = '%s/%s/messages.json' % (self.url, self.conversation.key)
stream_receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, stream_url,
Headers(self.auth_headers))
yield queue.get()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '1')
stream_receiver.disconnect()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
self.assertEqual(self.app.client_manager.clients, {
'sphex.stream.message.%s' % (self.conversation.key,): []
})
示例14: QueuePoller
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class QueuePoller(object):
implements(IPoller)
def __init__(self, config):
self.config = config
self.update_projects()
self.dq = DeferredQueue(size=1)
@inlineCallbacks
def poll(self):
if self.dq.pending:
return
for p, q in self.queues.iteritems():
c = yield maybeDeferred(q.count)
if c:
msg = yield maybeDeferred(q.pop)
returnValue(self.dq.put(self._message(msg, p)))
def next(self):
return self.dq.get()
def update_projects(self):
self.queues = get_spider_queues(self.config)
def _message(self, queue_msg, project):
d = queue_msg.copy()
d['_project'] = project
d['_spider'] = d.pop('name')
return d
示例15: home_ClientConn
# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import get [as 别名]
class home_ClientConn(protocol.Protocol):
def __init__(self):
print 'client connection established'
self.queue = DeferredQueue()
def connectionMade(self):
home_connections['client_conn'] = self
home_connections['command_conn'].transport.write('begin data connect')
reactor.listenTCP(80061, DataConnFactory())
self.queue.get().addCallback(self.forwardData)
def dataReceived(self, data):
self.queue.put(data)
def forwardData(self, data):
home_connections['data_conn'].transport.write(data)
self.queue.get().addCallback(self.forwardData)