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

PyDrive on Google App engine. Can't set the content of a GoogleDrive object from a StringIO object

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

甚至 tempfile 也被禁用,除了 TemporaryFileStringIO 的别名。所以我需要用 StringIO 对象设置驱动文件的内容。

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

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

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

我的代码

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

有什么方法可以从 StringIO 对象设置 GoogleDrive 对象的内容?

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 的 StringIO.StringIO 接受 unicode 或字节串作为输入,这在这种情况下可能会造成混淆。 io.StringIO 将只接受 unicode 作为输入,因此使用 io.StringIO 可能有助于在代码中更清楚地区分 unicode 和字节串。

我在 GitHub 上得到了答案。

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

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