Re: コマンドラインと JSON-RPC

人物: dwdollar

シンプルな Python API のコードを置いておく。各メソッドはサーバーに接続し、リクエストを送り、レスポンスを受け取って、JSON に相当する Python の辞書を返す。標準の Python モジュールしか使っていない。エラーチェックは一切しておらず、rpc.cpp からは 3 つの関数しか実装していない。需要があればもっと書くこともできる。

使い方としては、Python のコードはこんな感じになる… access = BitcoinAPI() access.getInfo() access.getAmountReceived(“1JyEmxiMso2RsFVfBcCa616npBvGgxiBX”) access.sendToAddress(“1JyEmxiMso2RsFVfBcCa616npBvGgxiBX”, 100.00) # 自分のアドレスに 100 ビットコイン送る 😁

これが自分のサイトでの自動トランザクションの土台になる。何か質問や懸念があれば言ってくれ。ひどく間違っている点があれば、遠慮なく教えてくれ。

import httplib, simplejson

class BitcoinAPI(object):

    def __init__(self, host = "127.0.0.1", port = 8332, timeout = 3):
        self.host = host
        self.port = port
        self.timeout = timeout
        self.httpHeader = {"Content-type": "application/json"}    # I don't know what needs to be in the header, but this works
        return

    def connect(self):
        self.connection = httplib.HTTPConnection(self.host, self.port, timeout = self.timeout)
        return

    def disconnect(self):
        self.connection.close()
        return

    # Functions return a python dictionary which should be equivalent to the JSON syntax received from the server
    # ident or "id" is a constant 1, but can be overridden when calling.  E.g. getAmountReceived(address, ident = 23)
    def getInfo(self, ident = 1):
        self.connect()
        params = simplejson.dumps({"method": "getinfo", "params": ], "id": ident})
        self.connection.request("POST", "/", params, self.httpHeader)
        response = self.connection.getresponse()
        #print response.status, response.reason    # Use for troubleshooting
        dictionary = simplejson.loads(response.read())
        self.disconnect()
        return dictionary

    def getAmountReceived(self, address, ident = 1):
        self.connect()
        params = simplejson.dumps({"method": "getamountreceived", "params": [address], "id": ident})
        self.connection.request("POST", "/", params, self.httpHeader)
        response = self.connection.getresponse()
        #print response.status, response.reason    # Use for troubleshooting
        dictionary = simplejson.loads(response.read())
        self.disconnect()
        return dictionary

    def sendToAddress(self, address, amount, ident = 1):
        self.connect()
        params = simplejson.dumps({"method": "sendtoaddress", "params": [address, amount], "id": ident})
        self.connection.request("POST", "/", params, self.httpHeader)
        response = self.connection.getresponse()
        #print response.status, response.reason    # Use for troubleshooting
        dictionary = simplejson.loads(response.read())
        self.disconnect()
        return dictionary