我试图将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大神给出的解决方案
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
Javascript + Python:将数组发送到Python脚本,将结果返回给Javascript - javascript我想建立一个网页,该网页通过Javascript API进行许多Facebook状态更新,并将它们分类到一个数组中。然后,我想将此数组发送到Python脚本,该脚本可以专门使用NLTK.进行语言分析。在Python中获得合适的结果后,我想将结果从该脚本返回到Javascript,以显示给用户等。听起来可能吗? javascript大神给出的解决方案 是的,完…
Javascript和Python JSON-未定义变量 - javascript例如,如果您具有以下JSON对象(删除python的分号):values = { a: 1, b: { c: 2, d: { e: 3 } }, f: 4, g: 5 }; 如果您尝试在JS中打印values,它将正常工作。但是在Python中,它将返回错误NameError: name 'a' is not defined,这意味着未定…
Python:可以使用JSON将消息发送到包含加密部分的Python Server吗? - javascript我对JSON的了解不多,我刚刚开始学习本教程,所以请多多包涵:http://pymotw.com/2/json/我的问题是我可以使用JSON发送包含已加密的部分的消息到Python服务器,以便它可以将其转发到另一台服务器吗?该消息将来自通过SSL的Javascript客户端,其中包含有关Python Server的一些信息,以及将被加密的消息转发到另一个Py…
从Chrome WebDriver访问getEventListeners(Python) - javascript目标:从Selenium WebDriver获取附加到节点的所有事件我正在使用selenium-python,我想执行一个javascript脚本(通过driver.execute_script('my js script')。该脚本使用getEventListeners,仅在Chrome上可用。我成功使用了driver = webdri…
跨python套接字将JSON传递给Javascript - javascript我正在使用python套接字与JavaScript客户端进行通信。http://docs.python.org/2/library/socket.html然后遵循JavaScript代码的一部分,ws = new WebSocket("ws://localhost:7777/"); ws.onopen = function(){ aler…