在Cloud Storage上载Blob时发生400错误

时间:2019-05-29 08:13:36

标签: python-3.x csv google-cloud-platform google-cloud-functions google-cloud-storage

我在Cloud Function中创建了一个csv文件。现在,我需要将其上传到Cloud Storage。我将其存储在/ tmp文件中。从那里,我必须将其上传到Cloud Storage。

使用的代码-

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_file(source_file_name)
    print('File {} uploaded to {}.'.format(source_file_name,destination_blob_name))

final_df.to_csv('/tmp/'+file_name)
with open('/tmp/'+file_name, 'r') as file_obj:
    upload_blob('test-bucket',file_obj,file_name)

但是,我遇到以下错误-

BadRequest: 400 PUT https://www.googleapis.com/upload/storage/v1/b/test-bucket/o?uploadType=resumable&upload_id=ABC: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>, 308)

文件正在存储在/ tmp文件夹中。从那里,它没有被上传。错误到底是什么?

1 个答案:

答案 0 :(得分:1)

400 error Bad request的许多可能原因(不是404)。也许您应该指定完整路径,而您没有打开文件并将其传递到source_file_name中。这就是我尝试成功将对象(与mp3文件进行尝试)上传到GCS的方法

from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))


if __name__ == '__main__':
    upload_blob ("[bucketname]", "/home/[username]/[filename]", "[filename]")