Firebase存储上传文件-Python

9

我需要帮助。我正在使用Python 3.6上传文件到Firebase存储中,但是我无法得到合理的结果。

import firebase_admin
from firebase_admin import credentials, firestore, storage

cred=credentials.Certificate('C:\\Users\\blackturtle\\Envs\\tube\\ps.json')
firebase_admin.initialize_app(cred, {
    'storageBucket': 'gs://dene-2ac17.appspot.com'
})
db = firestore.client()
bucket = storage.bucket()
blob = bucket.blob('hello.txt')
outfile='C:\\Users\\blackturtle\\Envs\\tube\\hello.txt'
blob.upload_from_filename(outfile)

那段代码会产生以下错误:
Exception has occurred: google.api_core.exceptions.NotFound
404 POST https://www.googleapis.com/upload/storage/v1/b/gs://dene-2ac17.appspot.com/o?uploadType=multipart: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>)
  File "C:\Users\blackturtle\Envs\tube\drive.py", line 27, in <module>
    blob.upload_from_filename(outfile)

当我使用下面的代码来上传文件时:
import firebase_admin
from firebase_admin import credentials, firestore, storage

cred=credentials.Certificate('C:\\Users\\blackturtle\\Envs\\tube\\ps.json')
firebase_admin.initialize_app(cred, {
    'storageBucket': 'gs://dene-2ac17.appspot.com'
})
db = firestore.client()
bucket = storage.bucket()
blob = bucket.blob('hello.txt')
outfile='C:\\Users\\blackturtle\\Envs\\tube\\hello.txt'
with open(outfile, 'rb') as my_file:
    blob.upload_from_file(my_file)

出现了以下错误

Exception has occurred: google.api_core.exceptions.NotFound
404 POST https://www.googleapis.com/upload/storage/v1/b/gs://dene-2ac17.appspot.com/o?uploadType=resumable: ('Response headers must contain header', 'location')
  File "C:\Users\blackturtle\Envs\tube\drive.py", line 29, in <module>
    blob.upload_from_file(my_file)

有什么想法是怎么回事? 提前感谢。
1个回答

9

请按照此处的说明,将'gs://dene-2ac17.appspot.com'更改为'dene-2ac17.appspot.com'

使用默认存储桶

初始化Admin SDK时,您可以指定默认存储桶名称,然后检索对此存储桶的身份验证引用。存储桶名称不得包含gs://或任何其他协议前缀。例如,如果Firebase控制台中显示的存储桶URL为gs://bucket-name.appspot.com,则将字符串bucket-name.appspot.com传递给Admin SDK。


感谢您的建议。我刚刚尝试了您建议的方法,但是出现了相同的错误(“响应头必须包含标头”位置“)。如果您有任何建议,将不胜感激 @Cheche - digging
哎呀!我以为它会工作。那个错误是在你的第一段代码还是第二段? - Cheche
我按照你建议的方式再次单独尝试了这两个代码块,结果它们给出的错误与上面相同。@Cheche - digging
好的,抱歉@digging - 最后两个尝试:a)尝试去除“db = firestore.client()”来分离您的问题; b) 检查您的凭据是否正确。 - Cheche
1
感谢您抽出时间解决问题@Cheche,这一切都是关于凭据的问题。我从Firebase复制了凭据并粘贴,然后它就像魔法般地运行了。再次感谢您。 - digging
太棒了!很高兴知道。 - Cheche

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接