Ishank Aggarwal
Ishank Aggarwal

Reputation: 43

import JSON file to google firestore using cloud functions

I'm new to GCP and Python. I have got a task to import JSON file into google firestore using google cloud functions via Python.

Kindly assist please.

Upvotes: 1

Views: 2742

Answers (3)

MI Haque
MI Haque

Reputation: 53

Ishank Aggarwal, You can add the above code snippet as a part of cloud function by following steps:

  1. https://console.cloud.google.com/functions/
  2. Create function using function name, yours requirements, choose run time as python and choose trigger as your gcs bucket.

Once you create it, if any change happens in your bucket, the function will trigger and execute your code

Upvotes: 0

Ishank Aggarwal
Ishank Aggarwal

Reputation: 43

I could achieve this system setup using below code. Posting for your reference:-

CLOUD FUNCTIONS CODE

REQUIREMENTS.TXT (Dependencies)

`google-api-python-client==1.7.11
google-auth==1.6.3
google-auth-httplib2==0.0.3
google-cloud-storage==1.19.1
google-cloud-firestore==1.6.2`

MAIN.PY

from google.cloud import storage
from google.cloud import firestore
import json

client = storage.Client()``

def hello_gcs_generic(data, context):

print('Bucket: {}'.format(data['bucket']))
print('File: {}'.format(data['name']))

bucketValue = data['bucket']
filename = data['name']
print('bucketValue : ',bucketValue)
print('filename : ',filename)

testFile = client.get_bucket(data['bucket']).blob(data['name'])
dataValue = json.loads(testFile.download_as_string(client=None))
print(dataValue)

db = firestore.Client()

doc_ref = db.collection(u'collectionName').document(u'documentName')
doc_ref.set(dataValue)

Upvotes: 2

MI Haque
MI Haque

Reputation: 53

Cloud functinos are server less functions provided by google. The beauty of cloud function is it will destroy it will invoke any trigger happens and itself once the execution is complete. Cloud functions are single purpose functions. Not only python, you can also use NodeJS and Go to write cloud functions. You can create a cloud function very easily by visiting quick start of cloud functions (https://cloud.google.com/functions/docs/quickstart-console).

Your task is to import a JSON file into google firestore. This part you can do using Firestore python connector like any normal python program and add into cloud function console or upload via gcloud. Still the trigger part is missing here. As I mentioned cloud function is serverless. It will execute when any event happens in the attached trigger. You haven't mentioned any trigger here (when you want to trigger the function). Once you give information about the trigger I can give more insights on resolution.

Upvotes: 0

Related Questions