如何使用GAE的Python API将原始字节写入Google云存储 [英] How to write raw bytes to Google cloud storage with GAE's Python API

查看:80
本文介绍了如何使用GAE的Python API将原始字节写入Google云存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图修改用户表单提交的一些二进制数据,并将其写入Google Cloud Storage。我试图遵循 Google文档的示例,但写完后我收到了诸如此类的错误作为:
$ b

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.

我的代码简单如下

My code is simply as below

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开发团队的建议是使用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云存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆