【问题标题】:Importing an image from Python (raspberry pi) to Firebase将图像从 Python (raspberry pi) 导入 Firebase
【发布时间】:2018-11-04 12:01:16
【问题描述】:

对于一个项目,我们创建了一个记录全天某些分数的应用程序,我们还在 R 中创建了一些图表,我们将其保存为 Raspberry 上的 jpeg。

我们想通过 Python 将 jpg 文件上传到 Firebase(我们将一个变量上传到 Firebase 并且它可以工作)

我们首先尝试了这段代码:

from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket('teddy-aztech-ehealth.appspot.com') 
graphicBlob = bucket.get_blob('graph.jpeg')
graphBlob.upload_from_filename(filename='/home/pi/graph.jpeg')

但是我们从客户端存储桶部分得到一个很长的错误,告诉我们存储桶名称必须以数字开头和结尾。

我们也试过这段代码:

import sys
import requests
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
sys.argv = "/home/pi/graph.jpeg"
image_url = sys.argv

cred = credentials.Certificate('teddy-aztech-ehealth-firebase-adminsdk-t0iz1-61f49237f4.json')
firebase_admin.initialize_app(cred, {
   'storageBucket': 'https://teddy-aztech-ehealth.appspot.com'
})
bucket = storage.bucket()

image_data = requests.get(image_url).content
blob = bucket.blob('graph.jpg')
blob.upload_from_string(
    image_data,
    content_type='image/jpg'
)
print(blob.public_url)

但是在使用 initializeapp 的部分出现错误(同样,因为存储桶......) 我们是否必须从 Firebase 激活/授予访问权限?

【问题讨论】:

    标签: python image firebase upload firebase-storage


    【解决方案1】:

    您的初始尝试已接近您的需要。

    import io
    from google.cloud import storage
    
    # Google Cloud Project ID. This can be found on the 'Overview' page at
    # https://console.developers.google.com
    PROJECT_ID = 'your-project-id'
    CLOUD_STORAGE_BUCKET = 'your-bucket-name'
    
    filename = "graph-filename.jpeg"
    
    # Create unique filename to avoid name collisions in Google Cloud Storage
    date = datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%M%S")
    basename, extension = filename.rsplit('.', 1)
    unique_filename = "{0}-{1}.{2}".format(basename, date, extension)
    
    # Instantiate a client on behalf of the project
    client = storage.Client(project=PROJECT_ID)
    # Instantiate a bucket
    bucket = client.bucket(CLOUD_STORAGE_BUCKET)
    # Instantiate a blob
    blob = bucket.blob(unique_filename)
    
    # Upload the file
    with open(filename, "rb") as fp:
        blob.upload_from_file(fp)
    
    # The public URL for this blob
    url = blob.public_url
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2015-04-24
      • 2018-01-29
      • 2018-03-25
      相关资源
      最近更新 更多