简体   繁体   English

如何提供来自龙卷风的二进制数据?

[英]How do I serve a binary data from Tornado?

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. 我有一个numpy数组,我想使用Tornado服务,但是当我尝试使用self.write(my_np_array)编写它时,我只会得到一个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)

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 如果要将numpy数组用作python对象,以便在其他客户端上使用它,则需要先对对象进行腌制

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. 如果要传输numpy数组并在javascript中使用它,则不需要二进制表示形式。

Just convert the numpy array to a list 只需将numpy数组转换为列表

your_numpy_list = your_numpy_object.tolist()

and convert it to json 并将其转换为json

import json
self.write(json.dumps(your_numpy_list))

at the javascript side you just parse the result string 在javascript端,您只需解析结果字符串

var result = JSON.parse(resultString)

and create the typed array from it 并从中创建类型化数组

var typedResult = new Float32Array(result)

voila! 瞧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM