使用CoAPthon库将Coson服务器的json有效负载作为返回值发送到GET方法

时间:2017-11-10 13:52:30

标签: python json python-2.7 coap

我正在使用CoAPthon来创建服务器,每当调用get方法时它都会返回一个json有效负载,下面是我的代码片段:

from coapthon.resources.resource import Resource
from coapthon.server.coap import CoAP 
import json

class res(Resource):
   def __init__(self,name="Res",coap_server=None):
      super(res,self).__init__(name,coap_server,visible=True,observable=True,allow_children=True)
      with open("/home/pratik/Iot_datamodels/IoT-openiot-DataModels/oic.r.temperature.json","r") as f:
        value = json.load(f)
      self.payload=value['definitions']
      self.resource_type = "oic.r.temperature"
      self.content_type = "application/json"
      self.interface_type = "oic.if.a"

   def render_GET(self,request):
    print json.dumps({"e":[{ "n": "temperature", "v":23.5,"u":"degC" }]})
    return json.dumps({"e":[{ "n": "temperature", "v":23.5,"u":"degC" }]}))

class CoAPServer(CoAP):
  def __init__(self, host, port, multicast=False):
    CoAP.__init__(self,(host,port),multicast)
    self.add_resource('sens-Me/',res())
    print "CoAP server started on {}:{}".format(str(host),str(port))
    print self.root.dump()

def main():
    ip = "0.0.0.0"
    port = 5683
    multicast=False
    server = CoAPServer(ip,port,multicast)
    try:
        server.listen(10)
    except KeyboardInterrupt:
        server.close()

if __name__=="__main__":
  main()

服务器运行,我可以通过访问铜线的IP地址来查看它。但是当我按下get时,我的浏览器会显示5.00 Internal Server Error(Blockwise)。有人可以建议我怎么做吗?

1 个答案:

答案 0 :(得分:0)

首先导入以下内容

from coapthon import defines

然后在类res中重新定义get函数,如下所示: -

def render_GET(self,request):
   self.payload = (defines.Content_types["application/json"],json.dumps({"e":[{ "n": "temperature", "v":23.5,"u":"degC" }]}))
   return self