Root
Root

Reputation: 1005

Tornado write_message not sending dict/json

I am trying to send the file over the tornado websocket like this

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)

as per tornado documentation.

The message may be either a string or a dict (which will be encoded as json). If the binary argument is false, the message will be sent as utf8; in binary mode any byte string is allowed.

But I am getting this exception.

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'>

Upvotes: 0

Views: 1397

Answers (1)

xyres
xyres

Reputation: 21834

The documentation which you're citing is for WebSocketHandler which is meant for serving a websocket connection.

Whereas you're using a websocket client. You'll have to manually convert your dictionary to json.

from tornado.escape import json_encode

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

Upvotes: 1

Related Questions