Package: pyrebase4lite
Pyrebase4LiteA simple python wrapper for theFirebase API.This is a fork ofPyrebase4with the heavy dependecies and the admin priveledge removedInstallationpipinstallpyrebase4liteGetting StartedPython VersionPyrebase was written for python 3 and will not work correctly with python 2.Add Pyrebase to your applicationFor use with only user based authentication we can create the following configuration:importpyrebaseliteconfig={"apiKey":"apiKey","authDomain":"projectId.firebaseapp.com","databaseURL":"https://databaseName.firebaseio.com","storageBucket":"projectId.appspot.com"}firebase=pyrebaselite.initialize_app(config)Use ServicesA Pyrebase app can use multiple Firebase services.firebase.auth()-Authenticationfirebase.database()-Databasefirebase.storage()-StorageCheck out the documentation for each service for further details.AuthenticationThesign_in_with_email_and_password()method will return user data including a token you can use to adhere to security rules.Each of the following methods accepts a user token:get(),push(),set(),update(),remove()andstream().# Get a reference to the auth serviceauth=firebase.auth()# Log the user inuser=auth.sign_in_with_email_and_password(email,password)# Log the user in anonymouslyuser=auth.sign_in_anonymous()# Add user infouser=auth.update_profile(display_name,photo_url,delete_attribute)# Get user infouser=auth.get_account_info()# Get a reference to the database servicedb=firebase.database()# data to savedata={"name":"Mortimer 'Morty' Smith"}# Pass the user's idToken to the push methodresults=db.child("users").push(data,user['idToken'])Token expiryA user's idToken expires after 1 hour, so be sure to use the user's refreshToken to avoid stale tokens.user = auth.sign_in_with_email_and_password(email, password)
# before the 1 hour expiry:
user = auth.refresh(user['refreshToken'])
# now we have a fresh token
user['idToken']Manage UsersCreating usersauth.create_user_with_email_and_password(email,password)Note: Make sure you have the Email/password provider enabled in your Firebase dashboard under Auth -> Sign In Method.Verifying emailsauth.send_email_verification(user['idToken'])Sending password reset emailsauth.send_password_reset_email("email")Get account informationauth.get_account_info(user['idToken'])Refreshing tokensuser=auth.refresh(user['refreshToken'])Delete accountauth.delete_user_account(user['idToken'])DatabaseYou can build paths to your data by using thechild()method.db=firebase.database()db.child("users").child("Morty")Save DatapushTo save data with a unique, auto-generated, timestamp-based key, use thepush()method.data={"name":"Mortimer 'Morty' Smith"}db.child("users").push(data)setTo create your own keys use theset()method. The key in the example below is "Morty".data={"name":"Mortimer 'Morty' Smith"}db.child("users").child("Morty").set(data)updateTo update data for an existing entry use theupdate()method.db.child("users").child("Morty").update({"name":"Mortiest Morty"})removeTo delete data for an existing entry use theremove()method.db.child("users").child("Morty").remove()multi-location updatesYou can also performmulti-location updateswith theupdate()method.data={"users/Morty/":{"name":"Mortimer 'Morty' Smith"},"users/Rick/":{"name":"Rick Sanchez"}}db.update(data)To perform multi-location writes to new locations we can use thegenerate_key()method.data={"users/"+ref.generate_key():{"name":"Mortimer 'Morty' Smith"},"users/"+ref.generate_key():{"name":"Rick Sanchez"}}db.update(data)Conditional RequestsIt's possible to do conditional sets and removes by using theconditional_set()andconitional_remove()methods respectively. You can read more about conditional requests in Firebasehere.To use these methods, you first get the ETag of a particular path by using theget_etag()method. You can then use that tag in your conditional request.etag=db.child("users").child("Morty").get_etag()data={"name":"Mortimer 'Morty' Smith"}db.child("users").child("Morty").conditional_set(data,etag["ETag"])If the passed ETag does not match the ETag of the path in the database, the data will not be written, and both conditional request methods will return a single key-value pair with the new ETag to use of the following form:{"ETag":"8KnE63B6HiKp67Wf3HQrXanujSM=","value":"<current value>"}Here's an example of checking whether or not a conditional removal was successful:etag=db.child("users").child("Morty").get_etag()response=db.child("users").child("Morty").conditional_remove(etag["ETag"])iftype(response)isdictand"ETag"inresponse:etag=response["ETag"]# our ETag was out-of-dateelse:print("We removed the data successfully!")Here's an example of looping to increase age by 1:etag=db.child("users").child("Morty").child("age").get_etag()whiletype(etag)isdictand"ETag"inetag:new_age=etag["value"]+1etag=db.child("users").child("Morty").child("age").conditional_set(new_age,etag["ETag"])Retrieve DatavalQueries return a PyreResponse object. Callingval()on these objects returns the query data.users = db.child("users").get()
print(users.val()) # {"Morty": {"name": "Mortimer 'Morty' Smith"}, "Rick": {"name": "Rick Sanchez"}}keyCallingkey()returns the key for the query data.user = db.child("users").get()
print(user.key()) # userseachReturns a list of objects on each of which you can callval()andkey().all_users = db.child("users").get()
for user in all_users.each():
    print(user.key()) # Morty
    print(user.val()) # {name": "Mortimer 'Morty' Smith"}getTo return data from a path simply call theget()method.all_users=db.child("users").get()Conditional RequestsIt's possible to do conditional sets and removes by using theconditional_set()andconitional_remove()methods respectively. You can read more about conditional requests in Firebasehere.To use these methods, you first get the ETag of a particular path by using theget_etag()method. You can then use that tag in your conditional request.etag=db.child("users").child("Morty").get_etag()data={"name":"Mortimer 'Morty' Smith"}db.child("users").child("Morty").conditional_set(data,etag)If the passed ETag does not match the ETag of the path in the database, the data will not be written, and both conditional request methods will return a single key-value pair with the new ETag to use of the following form:{"ETag":"8KnE63B6HiKp67Wf3HQrXanujSM="}Here's an example of checking whether or not a conditional removal was successful:etag=db.child("users").child("Morty").get_etag()response=db.child("users").child("Morty").conditional_remove(etag)if"ETag"inresponse:etag=response["ETag"]# our ETag was out-of-dateelse:print("We removed the data successfully!")shallowTo return just the keys at a particular path use theshallow()method.all_user_ids=db.child("users").shallow().get()Note:shallow()can not be used in conjunction with any complex queries.streamingYou can listen to live changes to your data with thestream()method.defstream_handler(message):print(message["event"])# putprint(message["path"])# /-K7yGTTEp7O549EzTYtIprint(message["data"])# {'title': 'Pyrebase', "body": "etc..."}my_stream=db.child("posts").stream(stream_handler)You should at least handleputandpatchevents. Refer to"Streaming from the REST API"for details.You can also add astream_idto help you identify a stream if you have multiple running:my_stream = db.child("posts").stream(stream_handler, stream_id="new_posts")close the streammy_stream.close()Complex QueriesQueries can be built by chaining multiple query parameters together.users_by_name=db.child("users").order_by_child("name").limit_to_first(3).get()This query will return the first three users ordered by name.order_by_childWe begin any complex query withorder_by_child().users_by_name=db.child("users").order_by_child("name").get()This query will return users ordered by name.equal_toReturn data with a specific value.users_by_score=db.child("users").order_by_child("score").equal_to(10).get()This query will return users with a score of 10.start_at and end_atSpecify a range in your data.users_by_score=db.child("users").order_by_child("score").start_at(3).end_at(10).get()This query returns users ordered by score and with a score between 3 and 10.limit_to_first and limit_to_lastLimits data returned.users_by_score=db.child("users").order_by_child("score").limit_to_first(5).get()This query returns the first five users ordered by score.order_by_keyWhen usingorder_by_key()to sort your data, data is returned in ascending order by key.users_by_key=db.child("users").order_by_key().get()order_by_valueWhen usingorder_by_value(), children are ordered by their value.users_by_value=db.child("users").order_by_value().get()StorageThe storage service allows you to upload images to Firebase.childJust like with the Database service, you can build paths to your data with the Storage service.storage.child("images/example.jpg")putThe put method takes the path to the local file and an optional user token.storage=firebase.storage()# as adminstorage.child("images/example.jpg").put("example2.jpg")# as userstorage.child("images/example.jpg").put("example2.jpg",user['idToken'])downloadThe download method takes the path to the saved database file and the name you want the downloaded file to have.storage.child("images/example.jpg").download("downloaded.jpg")get_urlThe get_url method takes the path to the saved database file and user token which returns the storage url.storage.child("images/example.jpg").get_url(user["idToken"])
# https://firebasestorage.googleapis.com/v0/b/storage-url.appspot.com/o/images%2Fexample.jpg?alt=mediadeleteThe delete method takes the path to the saved database file and user token.storage.delete("images/example.jpg",user["idToken"])Helper Methodsgenerate_keydb.generate_key()is an implementation of Firebase'skey generation algorithm.See multi-location updates for a potential use case.sortSometimes we might want to sort our data multiple times. For example, we might want to retrieve all articles written between a
certain date then sort those articles based on the number of likes.Currently the REST API only allows us to sort our data once, so thesort()method bridges this gap.articles=db.child("articles").order_by_child("date").start_at(startDate).end_at(endDate).get()articles_by_likes=db.sort(articles,"likes")Common ErrorsIndex not defined+Indexing isnot enabledfor the database reference.