如何从websocket autobahnpython中获取数据

时间:2014-12-28 17:10:40

标签: python-2.7 autobahn

您好我使用autobahnpython连接到websocket并检索数据,但我很难将数据输出。基本上我想使用队列将数据发送到另一个处理数据本身的消费者线程。我发现的例子,只是将收到的数据打印到stdout或生成一些随机数,然后发送到套接字。这是我得到的错误

2014-12-28 18:07:04+0100 [-]     factory.protocol.set_ask_order_queue(Cryptsy_ask_Queue)
2014-12-28 18:07:04+0100 [-] TypeError: unbound method set_ask_order_queue() must be called 
with Cryptsy_socket instance as first argument (got LifoQueue instance instead)

这是我的WebSocketClientProtocol派生类:

import json
from decimal import *
from autobahn.twisted.websocket import  WebSocketClientProtocol
import time


class Cryptsy_socket(WebSocketClientProtocol):
    _ask_order_queue = []
    _bid_order_queue = []
    _old_bid_order = {}
    _old_ask_order = {}
    _bid_order = {}
    _ask_order = {}


def set_ask_order_queue(self,queue):
    self._ask_order_queue = queue

def set_bid_order_queue(self,queue):
    self._bid_order_queue = queue

def onOpen(self):
    #subscribe for ltc/btc
    self.sendMessage(u"{\"event\": \"pusher:subscribe\",\"data\": {\"channel\": \"ticker.3\"}}".encode("utf8"))

def onConnect(self,response):
    print ("Server connectred: {0}".format(response.peer))

def onMessage(self, payload, isBinary):

    print("Text message received: {0}".format(payload.decode('utf8')))


    json_receive = json.loads(payload.decode('utf8'))

    if "event" in json_receive:
        if "message" in json_receive["event"]:
            json_data = json.loads(json_receive["data"])
            buy_order = json_data["trade"]["topbuy"]
            sell_order = json_data["trade"]["topsell"]

            sell_order_price_as_decimal = Decimal(sell_order["price"])
            sell_order_amount_as_decimal = Decimal(sell_order["quantity"])
            sell_order_quote_currency_amount = sell_order_price_as_decimal*sell_order_amount_as_decimal  

            ask_as_decimal = {"price" : sell_order_price_as_decimal,\
                              "amount": sell_order_amount_as_decimal,\
                              "amount_of_second_currency": sell_order_quote_currency_amount,\
                              "name_of_exchange" : "Cryptsy",\
                              "fee_in_percent"  : Decimal("0.25")}

            buy_order_price_as_decimal = Decimal(buy_order["price"])
            buy_order_amount_as_decimal = Decimal(buy_order["quantity"])
            buy_order_quote_currency_amount = buy_order_price_as_decimal*buy_order_amount_as_decimal

            bid_as_decimal = {"price" : buy_order_price_as_decimal,\
                              "amount" : buy_order_amount_as_decimal,\
                              "amount_of_second_currency" : buy_order_quote_currency_amount,\
                              "name_of_exchange" : "Cryptsy",\
                              "fee_in_percent" : Decimal("0.25")}

            self._bid_order["order"] = bid_as_decimal
            self._ask_order["order"] = ask_as_decimal


            if self._old_ask_order == {} or \
                self._ask_order["order"]["price"] != self._old_ask_order["order"]["price"] or\
                self._ask_order["order"]["amount"] != self._old_ask_order["order"]["amount"]:

                ask_order_for_consumer = self._old_ask_order
                ask_order_for_consumer["time"] = time.time()
                self._ask_order_queue.put(ask_order_for_consumer)
                self._old_ask_order = self._ask_order

            if self._old_bid_order == {} or \
                self._bid_order["order"]["price"] != self._old_bid_order["order"]["price"] or\
                self._bid_order["order"]["amount"] != self._old_bid_order["order"]["amount"]:

                bid_order_for_consumer = self._old_bid_order
                bid_order_for_consumer["time"] = time.time()
                self._bid_order_queue.put(bid_order_for_consumer)
                self._old_bid_order = self._bid_order

这是我的主要创建队列和连接,在这里你可以看到我的问题。 这里没有调用Cryptsy_socket构造函数,这就是为什么当我尝试调用set_ask_order_queue和set_bid_order_queue时出现错误的原因。

import sys
from thread_handling.websocket_process_orders import Cryptsy_socket

from twisted.python import log
from twisted.internet import reactor, ssl
from autobahn.twisted.websocket import  WebSocketClientFactory, \
                                    connectWS

import Queue


if __name__ == '__main__':

    Cryptsy_ask_Queue = Queue.LifoQueue()
    Cryptsy_bid_Queue = Queue.LifoQueue()
    log.startLogging(sys.stdout)
    factory = WebSocketClientFactory("wss://ws.pusherapp.com:443/app/cb65d0a7a72cd94adf1f?client=PythonPusherClient&version=0.2.0&protocol=6")
    factory.protocol = Cryptsy_socket
    factory.protocol.set_ask_order_queue(Cryptsy_ask_Queue)
    factory.protocol.set_bid_order_queue(Cryptsy_bid_Queue)

    ## SSL client context: default
    ##
    if factory.isSecure:
        contextFactory = ssl.ClientContextFactory()
    else:
        contextFactory = None

connectWS(factory, contextFactory)
reactor.run()

那么如何使用队列完成数据输出?

1 个答案:

答案 0 :(得分:0)

好的我在旧帖子中找到了答案,其中添加了一个队列以与其他线程进行通信,这正是我所寻找的。 override websocketclientprotocol