问题描述
我正在尝试修改用户表单提交的一些二进制数据,并将其写入谷歌云存储.我尝试遵循 Google 文档的示例,但在编写时出现了诸如如:
I am trying to modify some binary data submitted by user form, and write it to Google Cloud Storage. I tried to follow Google document's example, but upon writing I got errors such as:
UnicodeDecodeError:ascii"编解码器无法解码位置 34 中的字节 0xe5:序数不在范围内.
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 34: ordinal not in range.
我的代码如下
gcs_file = gcs.open(filename,'w',content_type='audio/mp3')
gcs_file.write(buf)
gcs_file.close()
我尝试使用wb"模式打开文件,但得到无效模式 wb".错误.
I tried to open file with 'wb' mode but got a "Invalid mode wb." error.
我在 GCS 的邮件列表 发现了一个类似的问题在 Java 上.GCS 开发团队的建议是使用 writeChannel.write() 而不是 PrintWriter.有人可以建议如何让它在 Python 中工作吗?
I found a similar question at GCS's maillist which was on Java. There the GCS develop team's suggest was to use writeChannel.write() instead of PrintWriter. Could anybody suggest how to make it work in Python?
推荐答案
我想问题是 gcs_file.write() 方法需要str"类型的数据.由于您的 buf 类型是unicode"并且显然包含一些 Unicode 字符(可能在 ID3 标签中),因此您会得到 UnicodeDecodeError.所以你只需要将 buf 编码为 UTF-8:
I suppose the problem is that gcs_file.write() method expects data of type "str". Since type of your buf is "unicode" and apparently contains some Unicode chars (maybe in ID3 tags), you get UnicodeDecodeError. So you just need to encode buf to UTF-8:
gcs_file = gcs.open(filename,'w',content_type='audio/mp3')
gcs_file.write(buf.encode('utf-8'))
gcs_file.close()
这篇关于如何使用 GAE 的 Python API 将原始字节写入 Google 云存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!