【问题标题】:Send json with autobahn python使用高速公路 python 发送 json
【发布时间】:2013-10-08 14:26:59
【问题描述】:

我正在尝试将 json 内容从 url widh sendMessage 发送到客户端。

def broadcast(self):
  response = urllib2.urlopen('http://localhost:8001/json?as_text=1')
  data = json.load(response)

  for c in self.clients:
     c.sendMessage(data)

我得到了错误

File "myServer.py", line 63, in broadcast
c.sendMessage(data)
File "/Library/Python/2.7/site-packages/autobahn-0.6.3-py2.7.egg/autobahn    /websocket.py",     line 2605, in sendMessage
self.sendMessageHybi(payload, binary, payload_frag_size, sync, doNotCompress)
  File "/Library/Python/2.7/site-packages/autobahn-0.6.3-py2.7.egg/autobahn    /websocket.py", line 2671, in sendMessageHybi
    self.sendFrame(opcode = opcode, payload = payload, sync = sync, rsv = 4 if     sendCompressed else 0)
  File "/Library/Python/2.7/site-packages/autobahn-0.6.3-py2.7.egg/autobahn/websocket.py", line 2161, in sendFrame
raw = ''.join([chr(b0), chr(b1), el, mv, plm])
exceptions.TypeError: sequence item 4: expected string, dict found

【问题讨论】:

    标签: javascript python json twisted autobahn


    【解决方案1】:

    sendMessage 接受字节字符串或 unicode 字符串 - 而不是字典。这是因为 WebSockets 是二进制数据和文本数据的传输。它不是结构化对象的传输方式。

    您可以发送字典的 JSON 编码形式,但不能发送字典本身:

    def broadcast(self):
        response = urllib2.urlopen('http://localhost:8001/json?as_text=1')
    
        for c in self.clients:
            c.sendMessage(response)
    

    请注意,您实际上会想要使用twisted.web.client - 而不是阻塞urllib2

    from twisted.internet import reactor
    from twisted.web.client import Agent, readBody
    
    agent = Agent(reactor)
    
    def broadcast(self):
        getting = agent.request(
            b"GET", b"http://localhost:8001/json?as_text=1")
        getting.addCallback(readBody)
    
        def got(body):
            for c in self.clients:
                c.sendMessage(body)
        getting.addCallback(got)
        return getting
    

    【讨论】:

    • 没错。听从 Jean-Paul 的建议 .. 特别是使用 Twisted 的异步 Web 客户端而不是(阻塞)Python 内置的东西。
    • 我从 twisted.web.client import readBody ImportError: cannot import name readBody 中得到错误
    • readBody 在 Twisted 13.1.0 中引入。您可能使用的是旧版本的 Twisted。升级,如果可以的话。否则,您可能想改用(不太好)twisted.web.client.getPage
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多