如何将原始字节数组写入谷歌云存储作为二进制文件

时间:2014-06-26 19:03:34

标签: python google-app-engine google-cloud-storage binaryfiles blobstore

我正在制作一个AE应用程序,通过算法生成一个原始二进制文件(大多数是16位字节,带有一些32位头字节),然后由用户下载。我可以使用以下简单代码生成此数组并将其写入普通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)

显然,这不会在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()

这段代码给了我一个TypeError,基本上说write()需要一个字符串而不是别的。请注意,array模块的.tofile()功能不适用于AE / GCS。

我有什么方法可以写这样的文件吗?我的理解是,我不能以某种方式将字符串编码为原始二进制文件,这些字符串将被正确写入(不是ASCII或某些),所以我想要的可能是不可能的? :( Blobstore有什么不同吗?还有类似的( - 响声)问题(here),但它根本不是我想做的事情。

值得一提的是,我并不需要编写文件 - 如果有帮助,我只需要能够将其提供给用户。

1 个答案:

答案 0 :(得分:0)

使用array.tostring功能:

gcs_file.write(testdata.tostring())