简体   繁体   English

将图像从Python(Raspberry Pi)导入到Firebase

[英]Importing an image from Python (raspberry pi) to Firebase

For a project in which we created an app that records certain scores throughout the day, we also created some graphs in R which we saved as jpegs on the Raspberry. 对于一个我们创建了一个全天记录某些分数的应用程序的项目,我们还在R中创建了一些图形,并将其另存为jpegs在Raspberry上。

We want to upload the jpg to Firebase via Python (we uploaded a variable to Firebase and it worked) 我们想通过Python将jpg上传到Firebase(我们将变量上传到Firebase并成功了)

We first tried this code: 我们首先尝试了以下代码:

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

But we get a long error from the client bucket part , telling us the bucket name must start and end with a number. 但是我们从客户端存储桶部分得到了一个很长的错误,告诉我们存储桶名称必须以数字开头和结尾。

We also tried this code: 我们还尝试了以下代码:

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)

But get an error at the part with initializeapp (again, because of the bucket...) Do we have to activate/give access from Firebase? 但是initializeapp的部分出现错误(再次由于存储桶...)我们是否必须激活/提供来自Firebase的访问权限?

Your initial attempt is close to what you need. 您最初的尝试接近您的需求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM