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.
1 2 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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 |