如何使用 GAE 的 Python API 将原始字节写入 Google 云存储

2023-11-07Python开发问题
1

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

问题描述

我正在尝试修改用户表单提交的一些二进制数据,并将其写入谷歌云存储.我尝试遵循 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 云存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11