Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write raw bytes to Google cloud storage with GAE's Python API

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' 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()

I tried to open file with 'wb' mode but got a "Invalid mode wb." error.

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?

like image 553
user2686101 Avatar asked Aug 17 '13 15:08

user2686101


People also ask

How do I upload files to Google Cloud Python?

In the Google Cloud console, go to the Cloud Storage Buckets page. In the list of buckets, click on the name of the bucket that you want to upload an object to. In the Objects tab for the bucket, either: Drag and drop the desired files from your desktop or file manager to the main pane in the Google Cloud console.

How do I upload a CSV file to Google Cloud?

Select All Settings > Raw Data Export > CSV Upload. Select Google Cloud Storage from the dropdown menu. Upload your Service Account Key credential file. This is the JSON file created in the Google Cloud Console. Enter your Google Cloud Storage bucket name.


1 Answers

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()
like image 162
Denisigo Avatar answered Oct 16 '22 09:10

Denisigo