简体   繁体   中英

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.

We want to upload the jpg to Firebase via Python (we uploaded a variable to Firebase and it worked)

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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