PyDrive在Google App引擎上。无法从StringIO对象设置GoogleDrive对象的内容

时间:2017-06-13 13:44:12

标签: python google-app-engine pydrive

Google App Engine标准应用程序禁止创建文件。

即使 tempfile 也被禁用, TemporaryFile 除外,其名称为 StringIO 。所以我需要用StringIO对象设置驱动文件的内容。

我找到的唯一合适的方法是 SetContentString()

但是该方法期望一个utf-8字符串,我得到一个解码异常 -

UnicodeDecodeError:'ascii'编解码器无法解码位置0的字节0x89:序号不在范围内(128)

我的代码

drive = GoogleDrive(get_drive_auth())
drive_file = drive.CreateFile()
drive_file.SetContentString(stringio_object.getvalue())

有没有办法可以从GoogleDrive对象设置StringIO对象的内容?

2 个答案:

答案 0 :(得分:2)

PyDrive' GoogleDriveFile.setContentString方法希望接收一个unicode字符串作为参数和一个可选编码 - 默认为UTF-8。

该方法对unicode字符串进行编码,并使用编码的字符串初始化io.BytesIO实例,如下所示:

content = io.BytesIO(input_string.encode('utf-8'))

您正在使用UTF-8编码的字节字符串初始化StringIO实例,这导致错误:

>>> s = u'ŋđŧ¶eŋŧ¶ß¶ŋŧ¶'.encode('utf-8')                                                                                                              
>>> sio = StringIO(s)                                                                                                                                 
>>> io.BytesIO(sio.getvalue().encode('utf-8'))                                                                                                
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)

为避免错误,请使用unicode字符串初始化StringIO

>>> s = u'ŋđŧ¶eŋŧ¶ß¶ŋŧ¶'.encode('utf-8')
>>> sio = StringIO(s.decode('utf-8'))
>>> io.BytesIO(sio.getvalue().encode('utf-8'))
<_io.BytesIO object at 0x7f36c0dc0bf0>

Python2&#39; s StringIO.StringIO接受unicode或bytestrings作为输入,这可能会导致像这样的情况混淆。 io.StringIO只接受unicode作为输入,因此使用io.StringIO可能有助于在代码中更清楚地区分unicode和bytestrings。

答案 1 :(得分:2)

我在GitHub上得到了答案。

没有记录,但您可以直接设置GoogleDrive对象的内容

drive = GoogleDrive(get_drive_auth())
drive_file = drive.CreateFile()
drive_file.content = stringio_object