Reputation: 2609
I have a numpy array, that I want to serve using Tornado, but when I try to write it using self.write(my_np_array)
I just get an AssertionErrror.
What am I doing wrong?
File "server.py", line 28, in get
self.write(values)
File "/usr/lib/python2.7/site-packages/tornado/web.py", line 468, in write
chunk = utf8(chunk)
File "/usr/lib/python2.7/site-packages/tornado/escape.py", line 160, in utf8
assert isinstance(value, unicode)
Upvotes: 1
Views: 2027
Reputation: 2793
Not exactly sure what your goal is, but if you want to get a string representation of the object you can do
self.write(str(your_object))
If you want to serve the numpy array as a python object in order to use it on a different client you need to pickle the object first
import pickle
self.write(pickle.dumps(your_object))
the object can then be retrieved with
your_object = pickle.loads(sent_object)
Keep in mind that it is dangerous to unpickle objects from an untrusted source as it can lead to malicious code execution.
Edit:
If you want to transfer a numpy array and use it within javascript you don't need a binary representation.
Just convert the numpy array to a list
your_numpy_list = your_numpy_object.tolist()
and convert it to json
import json
self.write(json.dumps(your_numpy_list))
at the javascript side you just parse the result string
var result = JSON.parse(resultString)
and create the typed array from it
var typedResult = new Float32Array(result)
voila!
Upvotes: 1