Python Tornado write_消息未发送dict/json

Python Tornado write_消息未发送dict/json,python,websocket,tornado,Python,Websocket,Tornado,我正试图像这样通过tornado websocket发送文件 in_file = open("/home/rootkit/Pictures/test.png", "rb") data = in_file.read() in_file.close() d = {'file': base64.b64encode(data), 'filename': 'test.png'} self.ws.write_message(message=d) 根据龙卷风文件 消息可以是字符串或dict(将被编码为j

我正试图像这样通过tornado websocket发送文件

in_file = open("/home/rootkit/Pictures/test.png", "rb")  
data = in_file.read()
in_file.close()
d = {'file': base64.b64encode(data), 'filename': 'test.png'}
self.ws.write_message(message=d)
根据龙卷风文件

消息可以是字符串或dict(将被编码为json)。如果二进制参数为false,则消息将作为utf8发送;在二进制模式下,允许任何字节字符串

但我得到了这个例外

ERROR:asyncio:Future exception was never retrieved
future: <Future finished exception=TypeError("Expected bytes, unicode, or None; got <class 'dict'>",)>
Traceback (most recent call last):
  File "/home/rootkit/.local/lib/python3.5/site-packages/tornado/gen.py", line 1147, in run
    yielded = self.gen.send(value)
  File "/home/rootkit/PycharmProjects/socketserver/WebSocketClient.py", line 42, in run
    self.ws.write_message(message=d, binary=True)
  File "/home/rootkit/.local/lib/python3.5/site-packages/tornado/websocket.py", line 1213, in write_message
    return self.protocol.write_message(message, binary=binary)
  File "/home/rootkit/.local/lib/python3.5/site-packages/tornado/websocket.py", line 854, in write_message
    message = tornado.escape.utf8(message)
  File "/home/rootkit/.local/lib/python3.5/site-packages/tornado/escape.py", line 197, in utf8
    "Expected bytes, unicode, or None; got %r" % type(value)
TypeError: Expected bytes, unicode, or None; got <class 'dict'>
错误:asyncio:从未检索到未来异常
未来:
回溯(最近一次呼叫最后一次):
文件“/home/rootkit/.local/lib/python3.5/site packages/tornado/gen.py”,第1147行,正在运行
已生成=self.gen.send(值)
文件“/home/rootkit/PycharmProjects/socketserver/WebSocketClient.py”,第42行,运行中
self.ws.write_消息(消息=d,二进制=True)
文件“/home/rootkit/.local/lib/python3.5/site packages/tornado/websocket.py”,第1213行,在write_消息中
返回self.protocol.write_消息(消息,二进制=二进制)
文件“/home/rootkit/.local/lib/python3.5/site packages/tornado/websocket.py”,第854行,在write_消息中
message=tornado.escape.utf8(消息)
文件“/home/rootkit/.local/lib/python3.5/site packages/tornado/escape.py”,第197行,utf8格式
应为字节、unicode或无;获取了%r”%type(值)
TypeError:应为字节、unicode或无;得到了

您引用的文档旨在为websocket连接提供服务

而你用的是一个。您必须手动将字典转换为json

from tornado.escape import json_encode

self.ws.write_message(message=json_encode(d))