[英]How to write array of raw bytes to google cloud storage as binary file
I'm making an AE app that algorithmically produces a raw binary file (mostly 16-bit bytes with some 32-bit header bytes) which is then downloaded by the user. 我正在制作一个AE应用程序,该应用程序通过算法生成原始二进制文件(大多数为16位字节,有些为32位头字节),然后由用户下载。 I can produce this array and write it to a file in normal python using the following simple code:
我可以使用以下简单代码生成此数组并将其写入普通python文件中:
import numpy as np
import array as arr
toy_data_to_write = arr.array('h', np.zeros(10, dtype=np.int16))
output_file = open('testFile.xyz', 'wb')
toy_data_to_write.tofile(output_file)
Obviously, this won't work in AE because writes are not allowed, so I tried to do something similar in the GCS: 显然,这在AE中不起作用,因为不允许写入,因此我尝试在GCS中执行类似的操作:
import cloudstorage as gcs
self.response.headers['Content-Type'] = 'application/octet-stream'
self.response.headers['Content-Disposition'] = 'attachment; filename=testFile.xyz'
testfilename = '/' + 'xyz-app.appspot.com' + '/testfile'
gcs_file = gcs.open(testfilename,'w',content_type='application/octet-stream')
testdata = arr.array('h', np.zeros(10, dtype=np.int16))
gcs_file.write(testdata)
gcs_file.close()
gcs_file = gcs.open(testfilename)
self.response.write(gcs_file.read())
gcs_file.close()
This code gives me a TypeError
, basically saying that write()
expects a string and nothing else. 这段代码给了我
TypeError
,基本上是说write()
需要一个字符串,而没有别的。 Note that the array
module's .tofile()
function does not work with AE/GCS. 请注意,
array
模块的.tofile()
函数不适用于AE / GCS。
Is there any way for me to write a file like this? 有什么办法可以写这样的文件吗? My understanding is that I can't somehow encode a string to be raw binary that will be written correctly (not ASCII or somesuch), so what I want may be impossible?
我的理解是,我无法以某种方式将字符串编码为可以正确写入的原始二进制文件(而不是ASCII或类似字符),所以我想要的是不可能的吗? :( Is the Blobstore any different? Also there's a similar(-sounding) question ( here ), but it's not at all what I'm trying to do.
:( Blobstore有什么不同吗?还有一个类似的(听起来)问题( 在这里 ),但这根本不是我想要做的。
It's worth mentioning that I don't really need to write the file -- I just need to be able to serve it back to the user, if that helps. 值得一提的是,我真的不需要编写文件,只要有帮助,我只需要能够将其提供给用户即可。
使用array.tostring函数:
gcs_file.write(testdata.tostring())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.