Skip to main content
 首页 » 编程设计

python之使用 Django 将文件发送到 GCS 的最佳方式

2025年02月15日25shihaiming

使用 django 将文件发送到 Google 云存储的最佳方式是什么。

此时我正在使用 post 方法获取文件

file = request.FILES['image'] 

但是当我尝试发送到 GCS 时

    from google.cloud import storage 
    client = storage.Client(projectName) 
    bucket = client.get_bucket(bucketName) 
    blob = bucket.blob(fileName) 
    blob.upload_from_filename(file) 

我收到此错误 InMemoryUploadedFile,因此我必须将文件保存在临时文件中,然后发送到 GCS,但速度很慢。

请您参考如下方法:

这就是我通过 djano 上传文件的方式, 下面显示了我的 django(drf) View 中的 View 方法

def upload_gcp(self, request): 
  file = request.data["file"] 
  storage_client = storage.Client.from_service_account_json( 
        'path-to-credentials-file.json' 
    ) 
  bucket = storage_client.get_bucket("sandbox-bucket-001") 
  blob = bucket.blob(file.name) 
  blob.upload_from_string(file.file.read()) 

文件作为 formdata 发送,在这种情况下,上传的文件包含在名为 file 的键中,file python 变量是 InMemoryUploadedFile 对象和 file.name 包含上传文件的实际名称