(Flask API), make firebase uploaded images have unique names - python

I'm building an API that uploads images to Firebase storage, everything works as expected in that regard, the problem is that the syntax makes me specify the file name in each upload, and in production mode the API will receive upload requests from multiple devices, so I need to make to code so it checks for an available id, set it for the "blob()" object, and then do a normal upload, but I have no idea how to do that. or a random name I don't care as long as it doesn't overwrite another picture
Here is my current code:
from flask_pymongo import PyMongo
import firebase_admin
from firebase_admin import credentials, auth, storage, firestore
import os
import io
cred = credentials.Certificate('service_account_key.json')
firebase_admin.initialize_app(cred, {'storageBucket': 'MY-DATABASE-NAME.appspot.com'})
bucket = storage.bucket()
blob = bucket.blob("images/newimage.png") #here is where im guessing i #should put the next available name
# "apple.png" is a sample image #for testing in my directory
with open("apple.png", "rb") as f:
blob.upload_from_file(f)

As "Klaus D."'s comment said the solution was to implement the "uuid" module
import uuid
.....
.....
blob = bucket.blob("images/" + str(uuid.uuid4()))

Related

How do I download image from firebase storage folder with python?

I want to download image from firebase storage which the resouce folder
can anyone teach me how to do?
my english is not good forgive me
This code will help you download any image in Firebase, you will find in your local folder as "img.png"
The credentials.json should be in the same folder you run this code in and you can retrieve it from Firebase, its particular to your account
In my case my storage bucket is called 'aisparkdev-tinder.appspot.com'
When generating the blob variable, the string is just the path to your image.
import urllib
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
cred = credentials.Certificate("credentials.json")
# Initialize the app with a service account, granting admin privileges
appF = firebase_admin.initialize_app(cred,
{'storageBucket': 'aisparkdev-tinder.appspot.com',},
name='storage')
bucket = storage.bucket(app=appF)
blob = bucket.blob("profileImages/"+profilePic+".jpg")
urllib.request.urlretrieve(blob.generate_signed_url(datetime.timedelta(seconds=300), method='GET'), ".\\img.png")

GCP Python Compute Engine - list VM's

I have the following Python3 script:
import os, json
import googleapiclient.discovery
from google.oauth2 import service_account
from google.cloud import storage
storage_client = storage.Client.from_service_account_json('gcp-sa.json')
buckets = list(storage_client.list_buckets())
print(buckets)
compute = googleapiclient.discovery.build('compute', 'v1')
def list_instances(compute, project, zone):
result = compute.instances().list(project=project, zone=zone).execute()
return result['items'] if 'items' in result else None
list_instances(compute, "my-project", "my-zone")
Only listing buckets without the rest works fine, that tells me that my service account (with has read access to the whole project) should work. How can I now list VM's? Using the code above, I get
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
So that tells me that I somehow have to pass the service account json. How is that possible?
Thanks!!

Why doesn't the Firebase Storage UI ever display the thumbnail of my uploaded image?

So I am trying to upload my data to firebase using python. Although my data is being pushed to the cloud and it's an image file of .png format. When I view my data in the cloud, it keeps on loading but never actually shows up. Although the size is identical to the size of the local image file. But I don't understand why It never displays the image. This wait bar keeps rotating.
Here's my code from the server-side (Python Code).
import firebase
from google.cloud import storage
from google.cloud.storage import client
import cv2
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
cred = credentials.Certificate('certificate.json')
firebase_admin.initialize_app(cred, {
'storageBucket': 'test-cd462.appspot.com'
})
bucket = storage.bucket()
image_data=cv2.imread('1.png')
imageBlob = bucket.blob('Images.png')
blob.upload_from_string(
image_data,
content_type='image/png'
)
print(imageBlob)
Here's the screenshot of what I am getting in my firebase window:
Please help me and let me know where have I gone wrong. Thanks in advance!

Are there timestamps on each Cloud Firestore document that are accessible from Python via the Admin API?

I'm trying to write a Python script that iterates a collection in Firebase and takes external actions using data from each document matching the where() criteria.
My thinking is that I can run this script periodically (for instance, every 15 minutes or every hour), select only those documents that have been created or modified in the preceding period, and have the script create static HTML documents containing Open Graph and Twitter Card tags, so links into my existing Angular app show relevant information from dynamically-generated pages.
Here's the code I've written so far:
from __future__ import print_function
import pprint
import datetime
import requests
import codecs
import json
import sys
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
#
# The purpose of this script is to generate static document pages for
# Facebook OpenGraph and Twitter meta tag exposure.
#
# We run this code at /home/app-name/utilities on the third-party app server at our inexpensive hosting provider.
#
# Use a service account
cred = credentials.Certificate('./App-Data-Mover-Key.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
pp = pprint.PrettyPrinter(indent=4)
pp.pprint({u'sys.argv': sys.argv})
try:
docs = [snapshot.reference for snapshot in db.collection(u'documents').where(u'what goes here?').get()]
for docref in docs:
doc = docref.get().to_dict()
pp.pprint(doc)
# Create the file and write out HTML stub here.
finally:
print("Done!\n")
My question is, are there timestamps representing creation and last modification of each Cloud Firestore document that I can reference in the where clause when I'm building up the snapshot?

Connecting aws backend to firebase database

I'm currently running python code in my aws server and trying to connect to my friend's firebase database. I read the documentation provided by firebase to connect to aws server.
https://firebase.google.com/docs/admin/setup
I have followed every step but I'm getting an error when I try to connect to my server. I have added google-service.json for credential.
Error that I get :
ValueError: Invalid service account certificate. Certificate must
contain a "type" field set to "service_account".
Do I need to modify the google-services.json ?
My code:
import firebase_admin
from firebase_admin import credentials
cred = credentials.Certificate('/home/ec2-user/google-services.json')
#default_app = firebase_admin.initialize_app(cred)
other_app = firebase_admin.initialize_app(cred, name='other')
ault_app = firebase_admin.initialize_app()
google-services.json is typically the name of an Android app configuration file. That's not the same as a service account. To get a hold of the credentials for a service account for your project, you'll need to generate one from the Firebase console from Project Settings -> Service Accounts. The documentation is here. Once you have this file, you can initialize the Admin SDK with it to begin accessing the data in your project.
Better way would be to store credentials on s3 (encrypted) with a IAM role attached to lambda function.
import os
import firebase_admin
from firebase_admin import credentials
import boto3
from settings.local_settings import AWS_REGION, ENVIRONMENT
import json
firebase_config_file = 'app-admin-config-{}.json'.format(ENVIRONMENT)
firebase_admin_creds_file = 'app-admin-sdk-{}.json'.format(ENVIRONMENT)
current_dir = os.path.abspath(os.path.dirname(__file__))
files = [f for f in os.listdir(current_dir) if os.path.isfile(f)]
if firebase_config_file not in files and firebase_admin_creds_file not in files:
s3 = boto3.resource('s3', region_name=AWS_REGION)
bucket = s3.Bucket('app-s3-secrets')
firebase_config = json.loads(
bucket.Object('app-admin-config-{}.json'.format(ENVIRONMENT)).get()['Body'].read())
firebase_admin_creds = json.loads(
bucket.Object('app-admin-sdk-{}.json'.format(ENVIRONMENT)).get()['Body'].read().decode())
class Firebase:
#staticmethod
def get_connection():
cred = credentials.Certificate(firebase_admin_creds)
return firebase_admin.initialize_app(cred, firebase_config)
app = Firebase.get_connection()

Categories