当前位置: 首页>>代码示例>>Python>>正文


Python DeferredQueue.put方法代码示例

本文整理汇总了Python中twisted.internet.defer.DeferredQueue.put方法的典型用法代码示例。如果您正苦于以下问题:Python DeferredQueue.put方法的具体用法?Python DeferredQueue.put怎么用?Python DeferredQueue.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.defer.DeferredQueue的用法示例。


在下文中一共展示了DeferredQueue.put方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: WeChatTestCase

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class WeChatTestCase(VumiTestCase):

    def setUp(self):
        self.tx_helper = self.add_helper(TransportHelper(WeChatTransport))
        self.request_queue = DeferredQueue()
        self.mock_server = MockHttpServer(self.handle_api_request)
        self.add_cleanup(self.mock_server.stop)
        return self.mock_server.start()

    def handle_api_request(self, request):
        self.request_queue.put(request)
        return NOT_DONE_YET

    def get_transport(self, **config):
        defaults = {
            'api_url': self.mock_server.url,
            'auth_token': 'token',
            'twisted_endpoint': 'tcp:0',
            'wechat_appid': 'appid',
            'wechat_secret': 'secret',
            'embed_user_profile': False,
        }
        defaults.update(config)
        return self.tx_helper.get_transport(defaults)

    @inlineCallbacks
    def get_transport_with_access_token(self, access_token, **config):
        transport = yield self.get_transport(**config)
        yield transport.redis.set(WeChatTransport.ACCESS_TOKEN_KEY,
                                  access_token)
        returnValue(transport)
开发者ID:Nagato23,项目名称:vumi,代码行数:33,代码来源:test_wechat.py

示例2: SSMIServerProtocol

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [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()
开发者ID:caiobertacco,项目名称:vumi,代码行数:29,代码来源:test_truteq.py

示例3: ProcessPool

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [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()
开发者ID:systocrat,项目名称:armada,代码行数:35,代码来源:pool.py

示例4: MockHttpServer

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class MockHttpServer(object):
    """
    NOTE: This is deprecated.
          Please use :class:`vumi.tests.http_helpers.MockHttpHelper` instead.
    """

    def __init__(self, handler=None):
        self.queue = DeferredQueue()
        self._handler = handler or self.handle_request
        self._webserver = None
        self.addr = None
        self.url = None

    def handle_request(self, request):
        self.queue.put(request)

    @inlineCallbacks
    def start(self):
        root = MockResource(self._handler)
        site_factory = LogFilterSite(root)
        self._webserver = yield reactor.listenTCP(
            0, site_factory, interface='127.0.0.1')
        self.addr = self._webserver.getHost()
        self.url = "http://%s:%s/" % (self.addr.host, self.addr.port)

    @inlineCallbacks
    def stop(self):
        yield self._webserver.stopListening()
        yield self._webserver.loseConnection()
开发者ID:AndrewCvekl,项目名称:vumi,代码行数:31,代码来源:utils.py

示例5: WeChatTestCase

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class WeChatTestCase(VumiTestCase):

    def setUp(self):
        self.tx_helper = self.add_helper(TransportHelper(WeChatTransport))
        self.request_queue = DeferredQueue()
        self.fake_http = FakeHttpServer(self.handle_api_request)
        self.api_url = 'https://api.wechat.com/cgi-bin/'

    def handle_api_request(self, request):
        self.assertEqual(request.path[:len(self.api_url)], self.api_url)
        self.request_queue.put(request)
        return NOT_DONE_YET

    @inlineCallbacks
    def get_transport(self, **config):
        defaults = {
            'auth_token': 'token',
            'twisted_endpoint': 'tcp:0',
            'wechat_appid': 'appid',
            'wechat_secret': 'secret',
            'embed_user_profile': False,
        }
        defaults.update(config)
        transport = yield self.tx_helper.get_transport(defaults)
        transport.agent_factory = self.fake_http.get_agent
        returnValue(transport)

    @inlineCallbacks
    def get_transport_with_access_token(self, access_token, **config):
        transport = yield self.get_transport(**config)
        yield transport.redis.set(WeChatTransport.ACCESS_TOKEN_KEY,
                                  access_token)
        returnValue(transport)
开发者ID:caiobertacco,项目名称:vumi,代码行数:35,代码来源:test_wechat.py

示例6: TestHTTPClientBase

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class TestHTTPClientBase(TestCase):
    # TODO: Run client tests synchronously with treq.testing tools (#38)
    run_tests_with = AsynchronousDeferredRunTest.make_factory(timeout=0.1)

    def setUp(self):
        super(TestHTTPClientBase, self).setUp()

        self.requests = DeferredQueue()
        self.fake_server = FakeHttpServer(self.handle_request)

        fake_client = treq_HTTPClient(self.fake_server.get_agent())
        self.client = self.get_client(fake_client)

        # Spin the reactor once at the end of each test to clean up any
        # cancelled deferreds
        self.addCleanup(wait0)

    def handle_request(self, request):
        self.requests.put(request)
        return NOT_DONE_YET

    def get_client(self, client):
        """To be implemented by subclass"""
        raise NotImplementedError()

    def uri(self, path):
        return '%s%s' % (self.client.url, path,)

    def cleanup_d(self, d):
        self.addCleanup(lambda: d)
        return d
开发者ID:praekeltfoundation,项目名称:marathon-acme,代码行数:33,代码来源:test_clients.py

示例7: DataConnection

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class DataConnection(Protocol):
	def __init__(self):
		self.queue = DeferredQueue()
	def dataReceived(self, data):
		self.queue.put(data) # put data from client into queue
	def connectionMade(self):
		reactor.connectTCP(SSH_HOST, SSH_PORT, ServiceConnFactory(self))
	def forwardData(self, data):
		self.transport.write(data) # send data to Home through data connection
开发者ID:rosalyntan,项目名称:cse30332,代码行数:11,代码来源:work.py

示例8: ClientProtocol

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class ClientProtocol(LineReceiver):

    def __init__(self):
        self.queue = DeferredQueue()

    def lineReceived(self, line):
        self.queue.put(line)

    def connectionLost(self, reason):
        self.queue.put("DONE")
开发者ID:BantouTelecom,项目名称:vumi,代码行数:12,代码来源:test_telnet.py

示例9: DataConn

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class DataConn(Protocol):
	def __init__(self):
		self.serv_stream_live = False
		self.dq = DeferredQueue()
		
	def dataReceived(self, data):
		if self.serv_stream_live:
			conndict['servConn'].transport.write(data)
		else:
			self.dq.put(data)
开发者ID:tDeranek117,项目名称:CSE-Notre-Dame,代码行数:12,代码来源:work.py

示例10: PatchedMessengerTransport

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class PatchedMessengerTransport(MessengerTransport):

    def __init__(self, *args, **kwargs):
        super(PatchedMessengerTransport, self).__init__(*args, **kwargs)
        self.request_queue = DeferredQueue()

    def request(self, method, url, data, **kwargs):
        d = Deferred()
        self.request_queue.put((d, (method, url, data), kwargs))
        return d
开发者ID:praekeltfoundation,项目名称:vumi-messenger,代码行数:12,代码来源:test_transport.py

示例11: Game

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [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()
开发者ID:kkozy,项目名称:Pygame-Twisted-Assignment,代码行数:56,代码来源:game.py

示例12: FakeCellulant

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class FakeCellulant(object):
    def __init__(self):
        self.cellulant_sms_calls = DeferredQueue()
        self.fake_http = FakeHttpServer(self.handle_request)
        self.response = ''
        self.get_agent = self.fake_http.get_agent
        self.get = self.cellulant_sms_calls.get

    def handle_request(self, request):
        self.cellulant_sms_calls.put(request)
        return self.response
开发者ID:AndrewCvekl,项目名称:vumi,代码行数:13,代码来源:test_cellulant_sms.py

示例13: BenchTransport

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class BenchTransport(Transport):

    WORKER_QUEUE = DeferredQueue()

    @inlineCallbacks
    def startWorker(self):
        yield Transport.startWorker(self)
        self.message_queue = DeferredQueue()
        self.WORKER_QUEUE.put(self)

    def handle_outbound_message(self, msg):
        self.message_queue.put(msg)
开发者ID:AndrewCvekl,项目名称:vumi,代码行数:14,代码来源:sandbox.py

示例14: TestTransport

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [as 别名]
class TestTransport(TestCase):

    @inlineCallbacks
    def setUp(self):
        DelayedCall.debug = True
        self.ok_transport_calls = DeferredQueue()
        self.mock_service = MockHttpServer(self.handle_request)
        yield self.mock_service.start()
        config = {
            'transport_name': 'test_ok_transport',
            'transport_type': 'ok',
            'ussd_string_prefix': '',
            'web_path': "foo",
            'web_port': 0,
            'url': self.mock_service.url,
            'username': 'testuser',
            'password': 'testpass',
            }
        self.worker = get_stubbed_worker(OkTransport, config)
        self.broker = self.worker._amqp_client.broker
        yield self.worker.startWorker()
        self.worker_url = self.worker.get_transport_url()

    @inlineCallbacks
    def tearDown(self):
        yield self.worker.stopWorker()
        yield self.mock_service.stop()

    def handle_request(self, request):
        self.ok_transport_calls.put(request)
        return ''

    @inlineCallbacks
    def test_health(self):
        result = yield http_request(self.worker_url + "health", "",
                                    method='GET')
        self.assertEqual(json.loads(result), {
            'pending_requests': 0
        })

    @inlineCallbacks
    def test_inbound(self):
        d = http_request(self.worker_url + "foo", '', method='GET')
        msg, = yield self.broker.wait_messages("vumi",
            "test_ok_transport.inbound", 1)
        payload = msg.payload
        tum = TransportUserMessage(**payload)
        rep = tum.reply("OK")
        self.broker.publish_message("vumi", "test_ok_transport.outbound",
                rep)
        response = yield d
        self.assertEqual(response, 'OK')
开发者ID:BantouTelecom,项目名称:vumi,代码行数:54,代码来源:test_httprpc.py

示例15: TestStreamingClient

# 需要导入模块: from twisted.internet.defer import DeferredQueue [as 别名]
# 或者: from twisted.internet.defer.DeferredQueue import put [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",))
开发者ID:caiobertacco,项目名称:vumi,代码行数:54,代码来源:test_client.py


注:本文中的twisted.internet.defer.DeferredQueue.put方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。