javascript - 使用高速公路 python 发送 json

标签 javascript python json twisted autobahn

我正在尝试将 json 内容从 url 宽度的 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

最佳答案

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

您可以发送字典的 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

关于javascript - 使用高速公路 python 发送 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19250458/

相关文章:

javascript - 在对象中使用 this 内部函数定义不起作用

javascript - 全屏 iframe 的缩放内容

python - swig 将元组列表传递给 C++ 函数

python - 无法使用 python Minds api 进行身份验证

jquery - 将 json 数据转换为选择下拉选项

javascript - 如何为同一个弹出窗口调用 Controller ?

Javascript:检查数组中是否存在循环值

python - 使用 matplotlib 按钮在我创建的绘图之间交替/切换

Python:函数内的全局变量 + Curses

javascript - 如何使用 forEach 循环添加 Json 项?