65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Python 连接到 Spokes 的 REST API

2013 年 1 月 28 日

CPOL

2分钟阅读

viewsIcon

15885

使用 Python 连接 Spokes REST API。

 

Spokes 提供了多种使用其 API 的方式,并且有一些有趣的事情可以用来了解您的设备。 

当我“探查”API,看看基于不同的输入它可以生成什么时,Python 是我首选的语言。这有助于我快速上手并开始利用其全部潜力。

对于 Spokes 也是如此。您也可以使用提供交互式方法的语言来玩转其 API。

在下面的示例中,我通过使用 Python 2.7.3 中的 httplib 和 json 模块,通过其 REST API 连接到 Spokes

import httplib
import json
class PLTDevice:
    def __init__(self, spokes, uid):
        self.DeviceInfoURL = '/Spokes/DeviceServices/'+uid+'/Info'
        self.AttachURL =  '/Spokes/DeviceServices/'+uid+'/Attach'
        self.ReleaseURL =  '/Spokes/DeviceServices/'+uid+'/Release'
        
        self.attached = False
        self.session = None
        
        self.uid = uid
        self.spokes = spokes
        self.spokes.conn.request('GET', self.DeviceInfoURL);
        r = self.spokes.conn.getresponse()
        
        if r.status == 200:
            response = r.read()
            
            response = json.loads(response)
            self.device = response['Result']
    def __getattr__(self, name):
        if name in self.device.keys():
            return self.device[name]
    
    def attach(self):
        self.spokes.conn.request('GET', self.AttachURL);
        r = self.spokes.conn.getresponse()
        if r.status == 200:
            response = r.read()
            
            response = json.loads(response)
            if response['Err']==None:
                self.attached = True
                self.session = response['Result']
        
    def release(self):
        self.spokes.conn.request('GET', self.ReleaseURL);
        r = self.spokes.conn.getresponse()
        if r.status == 200:
            response = r.read()
            
            response = json.loads(response)
            if response['Err']==None:
                self.attached = False
                self.session = None
    def get_events(self, queue=127):
        eventsURL = '/Spokes/DeviceServices/'+self.session+'/Events?queue='+str(queue)
        self.spokes.conn.request('GET', eventsURL);
        r = self.spokes.conn.getresponse()
        if r.status == 200:
            response = r.read()
            
            response = json.loads(response)
            print response
        
class Spokes:
    def __init__(self):
        self.host = '127.0.0.1'
        self.port = '32001'
        self.conn = httplib.HTTPConnection(self.host+":"+self.port)
        self.DevicesListURL = '/Spokes/DeviceServices/DeviceList'
        self.devices=[]
        
    def get_device_list(self):
        self.conn.request('GET', self.DevicesListURL);
        r = self.conn.getresponse()
        if r.status == 200:
            response = r.read()
            
            response = json.loads(response)
            if response['Err']==None:
                for d in response['Result']:
                    self.devices.append(PLTDevice(self, d['Uid']))
        return self.devices

这绝不是一个完整的解决方案,它只是一个快速而简陋的方法来调用 REST 接口中最基本的 API(我几乎没有添加任何错误检查)。它展示了如何以交互方式与 Spokes 交互,以了解设备事件以及如何使用它们。

现在,加载上面的代码并切换到交互模式后

>>> s=Spokes()
>>> print s
<__main__.Spokes instance at 0x029FDFD0>
>>> print s.devices
[]
>>> dl = s.get_device_list()
>>> print len(dl)
1
>>> d = dl[0]
>>> print d.attached
False
>>> d.attach()
>>> print d.attached
True
>>> d.get_events()
{u'Description': u'', u'Err': None, u'Type_Name': u'DeviceEventArray', u'Result': [{u'Event_Log_Type_Name': u'HeadsetStateChange', u'Event_Id': 14, u'Timestamp': 634939487913969843L, u'Age': 10853, u'Event_Name': u'Doff', u'Event_Log_Type_Id': 2}, {u'Event_Log_Type_Name': u'HeadsetStateChange', u'Event_Id': 13, u'Timestamp': 634939487969032861L, u'Age': 5347, u'Event_Name': u'Don', u'Event_Log_Type_Id': 2}], u'Type': 6, u'isError': False}

请注意,由于我没有继续实现事件和其他 API 的代码,因此事件列表会按其返回的方式显示。我只是解析 JSON 结果并在 get_events() 中打印它。

我特别喜欢 Python,因为它具有访问其数据结构的灵活性的优势,如上文在 PLTDevice.__getattr__ 中所示。ProductName 并非作为类的成员定义,但仍然可以像一个成员一样访问。它的内容来自我们从 Spokes 接收到的响应。

>>> print d.ProductName
Plantronics BT300

从这里,您可以开始构建您的应用程序来实际监控事件队列并对其采取行动,或者继续在交互模式下探索,看看您还可以用设备和 API 做些什么。

这种方法通常对解决 REST API 问题对我很有帮助,希望对您也有帮助。

只是另一种方法。 

本文由 Ricardo de Andrade 撰写。Ricardo 是 Plantronics 的系统架构师和推广者,致力于帮助开发社区、客户和合作伙伴使用 Spokes SDK 以及构建围绕当前和未来产品解决方案。Ricardo 在软件和云分布式架构方面拥有丰富的经验,尤其是在电信领域。Ricardo 之前曾在微软工作,帮助客户和合作伙伴开发基于云的语音识别应用程序,并将他们的 Web 服务集成到 Microsoft Tellme 服务中。

© . All rights reserved.