Package: micropython-firebase-firestore
micropython-firebase-firestoreFirebase Firestore implementation for Micropython.Firebase implementationbased onREST API, based onmicropython-firebase-realtime-databasefrom ckoever.InstallationYou can useuPipto install library fromPyPiimportupipupip.install("micropython-firebase-firestore")or you can just uploadufirestore/ufirestore.pyto your microcontroller:pythonpyboard.py-dPORT-fcpufirestore.py:Commands that are implemented- set_project_id
- set_access_token
- patch
- create
- get
- getfile
- delete
- list
- list_collection_ids
- run_queryRequired modulesujson, urequests, _threadConnect to Wifiimporttimeimportnetworkwlan=network.WLAN(network.STA_IF)wlan.active(True)ifnotwlan.isconnected():wlan.connect("ssid","pass")print("Waiting for Wi-Fi connection",end="...")whilenotwlan.isconnected():print(".",end="")time.sleep(1)print()Example UsageReads a field from a stored documentimportufirestoreufirestore.set_project_id("INSERT_PROJECT_ID")ufirestore.set_access_token("INSERT_ACCESS_TOKEN")raw_doc=ufirestore.get("DOCUMENT_PATH")doc=FirebaseJson.from_raw(raw_doc)ifdoc["fields"].exists("FIELD"):print("The field value is:%s"%doc["fields"].get("FIELD"))The project ID is required, read about ithereor you can find it atProject Settings > Generalin your project'sconsoleThe access token is obtained from the Firebase Auth API, which can be harnessed with myauth library, or reading can be donehereFunctionsset_project_idufirestore.set_project_id("INSERT_PROJECT_ID")Set the ID of your Firebase projectset_access_tokenufirestore.set_access_token("INSERT_ACCESS_TOKEN")Sets the access token to use for authenticationpatchufirestore.patch(PATH,DOC,update_mask=[],bg=True,cb=None)Updates or inserts a documentDOCat the locationPATHSet the fields to update withupdate_maskOptional run in the background withbgSet a callback function after getting data withcbExampledoc=FirebaseJson()doc.set("age/integerValue",21)response=ufirestore.patch("users/234",doc,["age"],False)print(response)createufirestore.create(PATH,DOC,document_id=None,bg=True,cb=None)Creates a new documentDOCat the collection at locationPATHdocument_id- The document ID to use for the document. If not specified, an ID will be generatedOptional run in the background withbgSet a callback function after getting data withcbExampledoc=FirebaseJson()doc.set("name/stringValue","Jane Doe")doc.set("age/integerValue",25)doc.set("height/integerValue",165)response=ufirestore.create("users",doc,bg=False)print(response)getufirestore.get(PATH,mask=None,bg=True,cb=None)Gets a single document at locationPATHdocument_id- The document ID to use for the document. If not specified, an ID will be generatedmask- The fields to returnOptional run in the background withbgSet a callback function after getting data withcbExampleresponse=ufirestore.get("users/129",bg=False)doc=FirebaseJson.from_raw(response)ifdoc.exists("fields/name"):print("Hello,%s"%doc.get("fields/name"))getfileufirestore.getfile(PATH,FILENAME,mask=None,bg=True,cb=None)Gets a single document at locationPATHand writes it to fileFILENAMEdocument_id- The document ID to use for the document. If not specified, an ID will be generatedmask- The fields to returnOptional run in the background withbgSet a callback function after getting data withcbExampleufirestore.getfile("users/129","user.json")deleteufirestore.delete(PATH,bg=True,cb=None)Deletes a document at locationPATHOptional run in the background withbgSet a callback function after getting data withcbExamplesuccess=ufirestore.delete("users/129")ifsuccess:print("User data successfully deleted.")listufirestore.list(PATH,page_size=None,page_token=None,order_by=None,mask=None,show_missing=None,bg=True,cb=None)Lists documents at locationPATHpage_size- The number of documents to returnpage_token- Thenext_page_tokenreturned from a previouslistoptionorder_by- The order to sort results by. For example:priority desc, namemask- The fields to return. If not set, return all fieldsshow_missing- If the list should show missing documentsOptional run in the background withbgSet a callback function after getting data withcbExampledocuments,next_page_token=ufirestore.list("users",bg=False)fordocumentindocuments:doc=FirebaseJson.from_raw(document)ifdoc.exists("fields/age"):print("Age:%s"%doc.get("fields/age"))list_collection_idsufirestore.list_collection_ids(PATH,page_size=None,page_token=None,bg=True,cb=None)Lists all the collection IDs underneath a document atPATHpage_size- The maximum number of results to returnpage_token- A page tokenOptional run in the background withbgSet a callback function after getting data withcbExamplecollection_ids,next_page_token=ufirestore.list_collection_ids("rooms/28",bg=False)forcollection_idincollection_ids:print("ID:%s"%collection_id)run_queryufirestore.run_query(PATH,query,bg=True,cb=None)Runs a query at locationPATHOptional run in the background withbgSet a callback function after getting data withcbExamplefromufirestore.jsonimportFirebaseJson,Queryquery=Query().from_("users").where("age",">=",18)raw_doc=ufirestore.run_query("",query,bg=False)doc=FirebaseJson.from_raw(raw_doc)ifdoc.exists("fields/name"):print("Resulted with user named%s"%doc.get("fields/name"))FirebaseJsonA simple helper class for Firebase document JSON datasetdoc.set(path,value,with_type=False)Edit, overwrite or create new node at the specified pathwith_type- If set toTrue, the value's type will be inferred and applied accordingly, as per a Firestore DocumentValuegetdoc.get(path,default=None)Get the node value at a given path, returningdefaultif the path does not existadddoc.add(path,name,value)Add a new node at the path, with namenameand contentsvalueadd_itemdoc.add_item(path,value)Adds an array item to the node at the pathremovedoc.remove(path)Removes the node at the pathexistsdoc.exists(path)Checks whether a node exists at the pathprocessdoc.process(resource_name)Processes json instance into adictfor usage with Firestore APINOTE: All the functions in this library that require a document actually require theFirebaseJoninstance and runsprocessbehind the scenesFirebaseJson.from_rawFirebaseJson.from_raw(raw_doc)Parses a raw document object from the Firestore API into aFirebaseJsoninstanceExtra methodsFirebaseJson.to_value_typeFirebaseJson.to_value_type(value)Infers the type ofvalueand returns adictin the format of a Firestore DocumentValueExamplevalue=35data=FirebaseJson.to_value_type(value)print(data)# Returns {"integerValue": "35"}FirebaseJson.from_value_typeFirebaseJson.from_value_type(value)Takes a Firestore DocumentValueobject and returns its value, casted to the correct typeExample# Example data from APIdata={"arrayValue":{"values":[{"stringValue":"a"},{"stringValue":"b"},{"integerValue":"3"}]}}print(value)# Returns ["a", "b", 3]QueryWrapper overFirebaseJsonto easily create document queriesExtends allFirebaseJsonmethodsfrom_query.from_(collection_id,all_descendants=False)collection_id- When set, selects only collections with this IDall_descendants- WhenTrue, selects all descendant collections, whenFalse, selects collections that are immediate children of theparentthe query will be run onselectquery.select(field)Adds a document field to returnorder_byquery.order_by(field,direction="DESCENDING")field- The field to order bydirection- The direction to order by (ASCENDINGorDESCENDING)limitquery.limit(value)The maximum number of results to return,valuemust be >= 0wherequery.where(field,op,value)Applies a filter on a specific field.field- The field to filter byop- The operation to filter by, is one of<,<=,>,>=,==,!=,array-contains,in,array-contains-any,not-invalue- The value to compare to, type is inferred withFirebaseJson.to_value_typeprocessquery.process()Returnsdictdata of query for use with Firestore APINOTE: This function is already used in therun_queryfunction