analitics

Pages

Showing posts with label google-cloud-firestore. Show all posts
Showing posts with label google-cloud-firestore. Show all posts

Tuesday, April 23, 2019

Python 3.7.3 : Testing firebase with Python 3.7.3 .

The tutorial for today consists of using the Firebase service with python version 3.7.3 .
As you know Firebase offers multiple free and paid services.
In order to use the Python programming language, we need to use the pip utility to enter the required modules.
If your installation requires other python modules then you will need to install them in the same way.
C:\Python373>pip install firebase-admin
C:\Python373\Scripts>pip install google-cloud-firestore
The next step is to log in with a firebase account and create or use a project with a database.
You must use this link to see your project data and create your JSON configuration file for access.
Here's a screenshot of an old project in another programming language that I used for this tutorial.

At point 1, you will find Project Settings - Service accounts and you will need to use the Generate new private key button.
This will generate a JSON file that we will use in the python script.
Be careful to define the path to the python script file.
At point 2, you will find the database or you will need to create it to use it.
The script I'm going to present has commented on the lines for a better understanding of how to use it.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

# the go-test.json from my project settings 
cred = credentials.Certificate("go-test.json")

# start using firebase python modules 
firebase_admin.initialize_app(cred)

# access the database
database = firestore.client()

# access the collection with limit 
my_ref = database.collection("test").limit(2)

# show the values from database
try:
    docs = my_ref.stream()
    for doc in docs:
         print(u'Doc Data:{}'.format(doc.to_dict()))
except:
    print(u'Missing data')

# result running
#Doc Data:{'nrcrt': 1, 'string_value': 'this is a text'}
#Doc Data:{'name': 'test', 'added': 'just now'}

# add data to database
my_ref_add = database.collection("test")
my_ref_add.add({u'nickname': u'catafest', u'friend': u'Last Ocelot'})

# show the new database values
try:
    docs = my_ref_add.stream()
    for doc in docs:
         print(u'Doc Data:{}'.format(doc.to_dict()))
except:
    print(u'Missing data')

# result running
#Doc Data:{'nrcrt': 1, 'string_value': 'this is a text'}
#Doc Data:{'friend': 'Last Ocelot', 'nickname': 'catafest'}
#Doc Data:{'name': 'test', 'added': 'just now'}

# get just one 
doc = database.collection('test').document('doc_id').get()

# show create time 
print(doc.create_time)

# result running
#seconds: 1556014478
#nanos: 460439000