Try using FireBase Cloud Firestore in Python for the time being

Introduction

"I want to use FireBase's Cloud Firestore with Python for the time being!" While following the [Official document] of FireBase (https://firebase.google.com/docs/firestore/quickstart?authuser=0), write the procedure when trying the basic "data input / output". I will.

First ... let's create a "project"

A "project" is a "group" for using services such as Firestore, Cloud Functions, Authentication, and Hosting. Projects created with FireBase are also common to GCP.

Now let's create a project.

First, go to the FireBase Console (https://console.firebase.google.com). image.png Click "Create Project" in the middle. image.png Enter a name for your project and click Continue.

Step 2/3 will explain "Google Analytics (for Firebase projects)", so you can enable it or not. (Turn it off this time.) image.png

Finally, click "Create Project" to start the creation process automatically.

After a short while, the message "New project is ready" will be displayed as shown below. Click "Continue". image.png

Then, the screen will change to the console. image.png

This completes the project creation.

Create a Cloud Firestore database

In Cloud Firestore, "Document" to write "Data", There is a "collection" (like a folder) for keeping documents together. A "database" is a "box" that holds a collection.

.... it's difficult. If you're not sure, take a look at other people's very easy-to-understand articles!

Let's create a database first.

Click Database from the menu on the left. image.png Then click "Create Database".

A dialog will appear, so select "Start in test mode" and then "Next". image.png Leave the location selection and click Finish. image.png

After provisioning and security settings are complete, the screen below automatically appears.

image.png

This completes the database creation.

Create collections and documents

Now let's get ready to stream the data.

Click "Start Collection" in the middle. A dialog will appear, so enter an arbitrary character string (collection name) in "Collection ID". image.png

The "Document ID" can be any character string, and if you click "Automatic ID", it will be assigned appropriately. You can set the "field", but if you enter the data, it will be generated without permission. image.png

This will create a collection and documents all at once, so you're ready to populate your data.

Bring your API key

Finally, generate and download the API key for playing with FireBase from Python.

Click the gear mark on the upper left → "Project settings". image.png

Then select "Service Account". image.png

As it is, click "Generate New Private Key" and then click "Generate Key". The Json file will be downloaded, so keep it in a suitable location.

Then it's Python!

From here, I will leave FireBase and start working on the Python side. The code written here is taken from the Official Document and partially modified.

Let's put the library

We already have a library for playing with FireBase from Python.

pip install firebase-admin

To install the FireBase library.

Let's initialize first

Initialize your Cloud Firestore SDK instance.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate('Write the private key path.json')
firebase_admin.initialize_app(cred)

db = firestore.client()

With this alone, the SDK is initialized and data can be input and output.

Let's add some data

Now let's add the data to the database created in the previous step. Use the sample from the Official Documentation (https://firebase.google.com/docs/firestore/quickstart) as is. Please add the code below below the initialization code above!

doc_ref = db.collection(u'users').document(u'alovelace')
doc_ref.set({
    u'first': u'Ada',
    u'last': u'Lovelace',
    u'born': 1815
})

A little commentary db.collection (u'users') ... Which collection in the database to specify .document (u'alovelace') ... Which document in the previously specified collection to specify ʻU'first': u'Ada',` ... Add the value "Ada" to the "first" field

Let's do it!

If executed correctly, you should see something like this on the FireBase Console side. image.png

Let's read the data this time

Now, let's read the added data. Here, the character string is output as it is in the Python output window.

Under the initialization code

users_ref = db.collection(u'users')
docs = users_ref.stream()

for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))

If all goes well, you should see something like this: image.png

Let's delete the added data

Finally, let's delete the data.

I think the structure before deleting is as follows image.png

To delete only the added field

city_ref = db.collection(u'users').document(u'alovelace')
city_ref.update({
    u'born': firestore.DELETE_FIELD
})

This code removes the "born" field.

To delete the entire document

db.collection(u'users').document(u'alovelace').delete()

To delete the collection as well

def delete_collection(coll_ref, batch_size):
    docs = coll_ref.limit(batch_size).get()
    deleted = 0

    for doc in docs:
        print(u'Deleting doc {} => {}'.format(doc.id, doc.to_dict()))
        doc.reference.delete()
        deleted = deleted + 1

    if deleted >= batch_size:
        return delete_collection(coll_ref, batch_size)

(When you delete a collection, you need to get all the documents and delete them.)

This is the end of the basic operation.

in conclusion

I think it was a difficult article to read, but thank you for reading this far. Have a good FireBase life!

Recommended Posts

Try using FireBase Cloud Firestore in Python for the time being
Try using LINE Notify for the time being
Try using the Kraken API in Python
Python Master RTA for the time being
MongoDB for the first time in Python
Try using the BitFlyer Ligntning API in Python
Use logger with Python for the time being
Try using the DropBox Core API in Python
A useful note when using Python for the first time in a while
Run with CentOS7 + Apache2.4 + Python3.6 for the time being
Try adding an external module to pepper. For the time being, in requests.
Try a similar search for Image Search using the Python SDK [Search]
[Understand in the shortest time] Python basics for data analysis
[Introduction to Reinforcement Learning] Reinforcement learning to try moving for the time being
Try using LevelDB in Python (plyvel)
See python for the first time
Try using the Python Cmd module
Try using Leap Motion in Python
Understanding the python class Struggle (1) Let's move it for the time being
Let's touch Google's Vision API from Python for the time being
Try using the services that support serverless development that appeared in 2020 (CDK Pipelines / CodeArtifact / CodeGuru for Python)
Try using the HL band in order
Tweet using the Twitter API in Python
Try using Python with Google Cloud Functions
Let's try Linux for the first time
Notes for using python (pydev) in eclipse
CERTIFICATE_VERIFY_FAILED in Python 3.6, the official installer for macOS
I tried using scrapy for the first time
vprof --I tried using the profiler for Python
Firebase: Use Cloud Firestore and Cloud Storage from Python
[Cloudian # 7] Try deleting the bucket in Python (boto3)
For the time being, import them into jupyter
Python: Try using the UI on Pythonista 3 on iPad
Run yolov4 "for the time being" on windows
I played with Floydhub for the time being
Try using the Python web framework Tornado Part 1
Tips for hitting the ATND API in Python
Try to calculate RPN in Python (for beginners)
Try using the collections module (ChainMap) of python3
Try using the Python web framework Tornado Part 2
Try implementing the Monte Carlo method in Python
Hit the Firebase Dynamic Links API in Python
virtualenv For the time being, this is all!
Try using ChatWork API and Qiita API in Python
Try posting to Qiita for the first time
Prepare the development environment for Python on AWS Cloud9 (pip install & time change)
Turn multiple lists with a for statement at the same time in Python
I tried Python on Mac for the first time.
I will try to summarize the links that seem to be useful for the time being
[Unity (C #), Python] Try running Python code in Unity using IronPython
Directory structure for test-driven development using pytest in python
[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK
Flow memo to move LOCUST for the time being
[Python] Measures and displays the time required for processing
Collectively register data in Firestore using csv file in Python
Initial settings when using the foursquare API in python
Determine the threshold using the P tile method in python
Try searching for a million character profile in Python
I tried python on heroku for the first time
Explore Alibaba Cloud Function Compute for DevOps using Python 3.0
How to unit test a function containing the current time using freezegun in python