pyrebase

A simple python wrapper for the Firebase API.

https://github.com/thisbejim/pyrebase

Science Score: 13.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (10.7%) to scientific vocabulary

Keywords

firebase python
Last synced: 6 months ago · JSON representation

Repository

A simple python wrapper for the Firebase API.

Basic Info
  • Host: GitHub
  • Owner: thisbejim
  • Language: Python
  • Default Branch: master
  • Homepage:
  • Size: 158 KB
Statistics
  • Stars: 2,084
  • Watchers: 46
  • Forks: 533
  • Open Issues: 239
  • Releases: 0
Topics
firebase python
Created over 10 years ago · Last pushed almost 2 years ago
Metadata Files
Readme

README.md

Pyrebase

A simple python wrapper for the Firebase API.

Support

Does your business or project depend on Pyrebase? Reach out to pibals@protonmail.com

Installation

python pip install pyrebase

Getting Started

Python Version

Pyrebase was written for python 3 and will not work correctly with python 2.

Add Pyrebase to your application

For use with only user based authentication we can create the following configuration:

```python import pyrebase

config = { "apiKey": "apiKey", "authDomain": "projectId.firebaseapp.com", "databaseURL": "https://databaseName.firebaseio.com", "storageBucket": "projectId.appspot.com" }

firebase = pyrebase.initialize_app(config) ```

We can optionally add a service account credential to our configuration that will allow our server to authenticate with Firebase as an admin and disregard any security rules.

```python import pyrebase

config = { "apiKey": "apiKey", "authDomain": "projectId.firebaseapp.com", "databaseURL": "https://databaseName.firebaseio.com", "storageBucket": "projectId.appspot.com", "serviceAccount": "path/to/serviceAccountCredentials.json" }

firebase = pyrebase.initialize_app(config) ```

Adding a service account will authenticate as an admin by default for all database queries, check out the Authentication documentation for how to authenticate users.

Use Services

A Pyrebase app can use multiple Firebase services.

firebase.auth() - Authentication

firebase.database() - Database

firebase.storage() - Storage

Check out the documentation for each service for further details.

Authentication

The sign_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() and stream().

```python

Get a reference to the auth service

auth = firebase.auth()

Log the user in

user = auth.signinwithemailand_password(email, password)

Get a reference to the database service

db = firebase.database()

data to save

data = { "name": "Mortimer 'Morty' Smith" }

Pass the user's idToken to the push method

results = db.child("users").push(data, user['idToken']) ```

Token expiry

A user's idToken expires after 1 hour, so be sure to use the user's refreshToken to avoid stale tokens. ``` user = auth.signinwithemailand_password(email, password)

before the 1 hour expiry:

user = auth.refresh(user['refreshToken'])

now we have a fresh token

user['idToken'] ```

Custom tokens

You can also create users using custom tokens, for example: token = auth.create_custom_token("your_custom_id") You can also pass in additional claims. token_with_additional_claims = auth.create_custom_token("your_custom_id", {"premium_account": True}) You can then send these tokens to the client to sign in, or sign in as the user on the server. user = auth.sign_in_with_custom_token(token)

Manage Users

Creating users

python auth.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 emails

python auth.send_email_verification(user['idToken'])

Sending password reset emails

python auth.send_password_reset_email("email")

Get account information

python auth.get_account_info(user['idToken'])

Refreshing tokens

python user = auth.refresh(user['refreshToken'])

Database

You can build paths to your data by using the child() method.

python db = firebase.database() db.child("users").child("Morty")

Save Data

push

To save data with a unique, auto-generated, timestamp-based key, use the push() method.

python data = {"name": "Mortimer 'Morty' Smith"} db.child("users").push(data)

set

To create your own keys use the set() method. The key in the example below is "Morty".

python data = {"name": "Mortimer 'Morty' Smith"} db.child("users").child("Morty").set(data)

update

To update data for an existing entry use the update() method.

python db.child("users").child("Morty").update({"name": "Mortiest Morty"})

remove

To delete data for an existing entry use the remove() method.

python db.child("users").child("Morty").remove()

multi-location updates

You can also perform multi-location updates with the update() method.

```python 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 the generate_key() method.

```python data = { "users/"+ref.generatekey(): { "name": "Mortimer 'Morty' Smith" }, "users/"+ref.generatekey(): { "name": "Rick Sanchez" } }

db.update(data) ```

Retrieve Data

val

Queries return a PyreResponse object. Calling val() on these objects returns the query data.

users = db.child("users").get() print(users.val()) # {"Morty": {"name": "Mortimer 'Morty' Smith"}, "Rick": {"name": "Rick Sanchez"}}

key

Calling key() returns the key for the query data.

user = db.child("users").get() print(user.key()) # users

each

Returns a list of objects on each of which you can call val() and key().

all_users = db.child("users").get() for user in all_users.each(): print(user.key()) # Morty print(user.val()) # {name": "Mortimer 'Morty' Smith"}

get

To return data from a path simply call the get() method.

python all_users = db.child("users").get()

shallow

To return just the keys at a particular path use the shallow() method.

python all_user_ids = db.child("users").shallow().get()

Note: shallow() can not be used in conjunction with any complex queries.

streaming

You can listen to live changes to your data with the stream() method.

```python def stream_handler(message): print(message["event"]) # put print(message["path"]) # /-K7yGTTEp7O549EzTYtI print(message["data"]) # {'title': 'Pyrebase', "body": "etc..."}

mystream = db.child("posts").stream(streamhandler) ```

You should at least handle put and patch events. Refer to "Streaming from the REST API" for details.

You can also add a stream_id to help you identify a stream if you have multiple running:

my_stream = db.child("posts").stream(stream_handler, stream_id="new_posts")

close the stream

python my_stream.close()

Complex Queries

Queries can be built by chaining multiple query parameters together.

python 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.

orderbychild

We begin any complex query with order_by_child().

python users_by_name = db.child("users").order_by_child("name").get() This query will return users ordered by name.

equal_to

Return data with a specific value.

python users_by_score = db.child("users").order_by_child("score").equal_to(10).get() This query will return users with a score of 10.

startat and endat

Specify a range in your data.

python 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.

limittofirst and limittolast

Limits data returned.

python 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.

orderbykey

When using order_by_key() to sort your data, data is returned in ascending order by key.

python users_by_key = db.child("users").order_by_key().get()

orderbyvalue

When using order_by_value(), children are ordered by their value.

python users_by_value = db.child("users").order_by_value().get()

Storage

The storage service allows you to upload images to Firebase.

child

Just like with the Database service, you can build paths to your data with the Storage service.

python storage.child("images/example.jpg")

put

The put method takes the path to the local file and an optional user token.

```python storage = firebase.storage()

as admin

storage.child("images/example.jpg").put("example2.jpg")

as user

storage.child("images/example.jpg").put("example2.jpg", user['idToken']) ```

download

The 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_url

The get_url method takes the path to the saved database file and returns the storage url.

``` storage.child("images/example.jpg").get_url()

https://firebasestorage.googleapis.com/v0/b/storage-url.appspot.com/o/images%2Fexample.jpg?alt=media

```

Helper Methods

generate_key

db.generate_key() is an implementation of Firebase's key generation algorithm.

See multi-location updates for a potential use case.

sort

Sometimes 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 the sort() method bridges this gap.

python articles = db.child("articles").order_by_child("date").start_at(startDate).end_at(endDate).get() articles_by_likes = db.sort(articles, "likes")

Common Errors

Index not defined

Indexing is not enabled for the database reference.

Owner

  • Name: James Childs-Maidment
  • Login: thisbejim
  • Kind: user

GitHub Events

Total
  • Issues event: 1
  • Watch event: 37
  • Issue comment event: 9
  • Pull request event: 2
  • Fork event: 3
Last Year
  • Issues event: 1
  • Watch event: 37
  • Issue comment event: 9
  • Pull request event: 2
  • Fork event: 3

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 190
  • Total Committers: 15
  • Avg Commits per committer: 12.667
  • Development Distribution Score (DDS): 0.153
Past Year
  • Commits: 0
  • Committers: 0
  • Avg Commits per committer: 0.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
thisbejim j****3@h****m 161
Jeppe Toustrup j****e@t****k 12
lsenta l****a@g****m 2
Jonathan Baby b****n@g****m 2
Roy Kolak r****k@g****m 2
Jeremie Poutrin j****e@d****m 2
cidadao m****s@g****m 1
Sherif Zain s****f@f****m 1
Miguel Angel Gordian o****a@g****m 1
Matthew Ruse m****e@g****m 1
Craig Loftus c****g@r****m 1
Alexey Shamrin s****n@g****m 1
Aleksander Vognild Burkow a****w@g****m 1
jluismari j****o@a****m 1
Teodor Garzdin t****g@h****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 95
  • Total pull requests: 25
  • Average time to close issues: 10 months
  • Average time to close pull requests: almost 3 years
  • Total issue authors: 88
  • Total pull request authors: 23
  • Average comments per issue: 3.68
  • Average comments per pull request: 1.48
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 2
Past Year
  • Issues: 1
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 1
  • Pull request authors: 0
  • Average comments per issue: 0.0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • IGN-Styly (4)
  • CoutinhoElias (3)
  • lohriialo (2)
  • paxsipornax (2)
  • kleysonr (1)
  • mansidak (1)
  • MrPieler (1)
  • AlejandroPG10 (1)
  • ericjsalazar (1)
  • showierdata9978 (1)
  • writeblankspace (1)
  • MehalaKeller (1)
  • robertkstarr (1)
  • nosec2 (1)
  • itfat (1)
Pull Request Authors
  • alexpirine (2)
  • rudranshagrawal (2)
  • dependabot[bot] (2)
  • tfuji384 (2)
  • IGN-Styly (1)
  • Harishwarrior (1)
  • tejasvi (1)
  • septian-fs (1)
  • heston (1)
  • digitake (1)
  • slavaatsig (1)
  • jlowin (1)
  • lpreimesberger (1)
  • DamenTheDev (1)
  • sharmanirudh (1)
Top Labels
Issue Labels
Pull Request Labels
dependencies (2)

Packages

  • Total packages: 4
  • Total downloads:
    • pypi 15,969 last-month
  • Total docker downloads: 29
  • Total dependent packages: 7
    (may contain duplicates)
  • Total dependent repositories: 215
    (may contain duplicates)
  • Total versions: 82
  • Total maintainers: 3
pypi.org: pyrebase

A simple python wrapper for the Firebase API

  • Versions: 74
  • Dependent Packages: 7
  • Dependent Repositories: 214
  • Downloads: 15,958 Last month
  • Docker Downloads: 29
Rankings
Dependent repos count: 1.0%
Dependent packages count: 1.3%
Stargazers count: 1.6%
Downloads: 1.7%
Average: 1.9%
Forks count: 2.3%
Docker downloads count: 3.6%
Maintainers (1)
Last synced: 6 months ago
alpine-edge: py3-pyrebase

simple python wrapper for the Firebase API

  • Versions: 4
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent repos count: 0.0%
Forks count: 4.4%
Stargazers count: 5.6%
Average: 6.2%
Dependent packages count: 14.6%
Maintainers (1)
Last synced: 6 months ago
alpine-edge: py3-pyrebase-pyc

Precompiled Python bytecode for py3-pyrebase

  • Versions: 3
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent repos count: 0.0%
Average: 6.7%
Dependent packages count: 13.4%
Maintainers (1)
Last synced: 6 months ago
pypi.org: totally-not-the-official-pyrebase

firebase api wrapper fork from thisbejim but remove module limitation

  • Versions: 1
  • Dependent Packages: 0
  • Dependent Repositories: 1
  • Downloads: 11 Last month
Rankings
Stargazers count: 1.6%
Forks count: 2.3%
Dependent packages count: 10.1%
Average: 19.4%
Dependent repos count: 21.5%
Downloads: 61.2%
Maintainers (1)
Last synced: 6 months ago

Dependencies

requirements.dev.txt pypi
  • pytest *
requirements.txt pypi
  • gcloud ==0.17.0
  • oauth2client ==3.0.0
  • pycrypto ==2.6.1
  • python-jwt ==2.0.1
  • requests ==2.11.1
  • requests-toolbelt ==0.7.0
setup.py pypi
  • gcloud ==0.17.0
  • oauth2client ==3.0.0
  • pycryptodome ==3.4.3
  • python_jwt ==2.0.1
  • requests ==2.11.1
  • requests_toolbelt ==0.7.0