GithubHelp home page GithubHelp logo

pyrebase4's People

Contributors

acevedog avatar aleksanb avatar arham-sayyed avatar blackorder avatar codekuu avatar craigloftus avatar el-vishal avatar ender-always-wins avatar jonathanbaby avatar laurentsenta avatar lukewoodward avatar m-charchit avatar maneesh-pradeep avatar mar664 avatar ndesamuelmbah avatar nhorvath avatar padmanabhan100 avatar postsdesert avatar rasgo-cc avatar reidsy avatar shamrin avatar sherifzain avatar steliosrammos avatar tenzer avatar thisbejim avatar zoek1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyrebase4's Issues

stream() is very slow with large messages

In current HEAD, with Python 3.6.5, I found that stream() is extremely slow. It takes many seconds on a Raspberry Pi 3 to parse a few tens of kilobytes, and it gets progressively slower.

It looks like pyre_sseclient._event_complete() searches the message from the start for every character read, which makes detecting the end of a message quadratic in the length of the message.

Ordde

Make sure these boxes are checked before submitting your issue:

[] Check that your version of Python is 3.4+
[] Check that you are on the newest version of Pyrebase
[] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Firebase.init() throws error when JSON config has no `databaseURL` key

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

At least on my current Firebase project, the JSON configuration got from the Firebase console has no "databaseURL" key.

Instead, the keys are:

{
 "apiKey": ...,
 "authDomain": ...,
 "projectId": ...,
 "storageBucket": .,
 "messagingSenderId": ...,
 "appId": ...,
 "measurementId": ...
}

That means that the following line of pyrebase.Firebase.__init__ throws an exception:

self.database_url = config["databaseURL"]

The fix seems to be to replace that line with the following code

        if "databaseURL" in config:
          self.database_url = config["databaseURL"]

but I don't know if that has knock-on consequences elsewhere in the codebase.

Creating custom token fails

Hey,
First, thanks for pyrebase.

I was getting the following error/logtrace :

    return jwt.generate_jwt(payload, private_key, "RS256", exp)
  File "/Users/guyma/development/firebase-poc/venv/lib/python3.10/site-packages/python_jwt/__init__.py", line 91, in generate_jwt
    token.add_signature(priv_key, protected=header)
  File "/Users/guyma/development/firebase-poc/venv/lib/python3.10/site-packages/jwcrypto/jws.py", line 540, in add_signature
    sig = c.sign()
  File "/Users/guyma/development/firebase-poc/venv/lib/python3.10/site-packages/jwcrypto/jws.py", line 149, in sign
    raise ValueError('key is not a JWK object')
ValueError: key is not a JWK object```

**I managed to solve it locally by replacing line 104~ in pyrebase.py**
from:         `private_key = RSA.importKey(self.credentials._private_key_pkcs8_pem)`
to:             `private_key = jwk.JWK.from_pem(str.encode(self.credentials._private_key_pkcs8_pem))`


Thank you!
---
Make sure these boxes are checked before submitting your issue:

[V] Check that your version of Python is 3.4+
[V] Check that you are on the newest version of Pyrebase
[V] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Another Authentication Method

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Hello, I'm using pyrebase for my website to handle authentication but it can only sign in using email and password. Can pyrebase support using phone auth or another oauth like twitter or github auth ?

unable to get list of all files in firebase storage

i have a directory (wallpaper_app/Best_Wallpapers) in storage of firebase and it have some files iwant URL's of them all

but when i try to get list_files by
image = storage.child('wallpaper_app/Best_Wallpapers/').list_files()

it is working with serviceAccount adid to conig bu idont want to add

#-------------------------------iam facing error-----------------------------------#

File "d:\Project\wallpaper-app-kivy\temp.py", line 33, in
imageUrl = storage.list_files()
File "D:\Project\wallpaper-app-kivy\wallpaper-app\lib\site-packages\pyrebase\pyrebase.py", line 507, in list_files
return self.bucket.list_blobs()
AttributeError: 'Storage' object has no attribute 'bucket'
#----------------------------------------------------------------------------------#
Make sure these boxes are checked before submitting your issue:

[/] Check that your version of Python is 3.4+
[/] Check that you are on the newest version of Pyrebase
[/] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Order by not working on pythonanywhere

Make sure these boxes are checked before submitting your issue:

[X] Check that your version of Python is 3.4+
[X] Check that you are on the newest version of Pyrebase
[X] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

My django app's order_by_child filter has stopped working since I deployed it on pythonanywhere, I've tested it locally and it works fine but once deployed it throws an error "[Errno 400 Client Error: Bad Request for url: .......] { "error" : "orderBy must be a valid JSON encoded path" }" when ever it encounters order_by_child. Any solutions?

pyrebase Error after pyinstaller to exe ImportError: attempted relative import with no known parent package

I dont understand why pyrebase4 will not work after making exe with pyinstaller i give the path to the module but it give strange error i have been looking for 4 day's for solution but i dont seem to finde it.

i'm on windows 10 virtual machine 64bit

Is there sombody ho can help me to figure this out?

Thanks.

import schedule
import time
import os
import runpy

try:
import pyrebase
except ImportError:
import pyrebase

config = {

}

def do_somthing():

dir_name = 'download/'
if os.path.exists(dir_name) and os.path.isdir(dir_name):
    if not os.listdir(dir_name):
        print("Directory is empty")
        firebase = pyrebase.initialize_app(config)
        storage = firebase.storage()


        path_in_firebase = "test.py"
        path_local = r"C:\Users\win10\PycharmProjects\winlog\download\File.py"
        storage.child(path_in_firebase).download('',path_local)
        print('Downloading...')
        time.sleep(2)
        print('Complete')
    else:

        print('Downloading completed')


        schedule.every(5).seconds.do(moveUpdate)

        while 1:
            schedule.run_pending()
            time.sleep(1)

else:
    print("Given Directory don't exists")
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)

def moveUpdate():
runpy.run_path(path_name='moveUpdate.py')
print('is running...')

do_somthing()

def compare_file():
print('program running...')

schedule.every(5).seconds.do(compare_file)

while 1:
schedule.run_pending()
time.sleep(1)

schedule.every().day.at('18:00').do(subprocess.call("python3 main.py", shell=True))

My .spec file

-- mode: python ; coding: utf-8 --

block_cipher = None

a = Analysis(['update.py'],
pathex=['C:\Users\win10\PycharmProjects\winlog', 'C:\Users\win10\PycharmProjects\winlog\venv\Lib\site-packages\schedule','C:\Users\win10\PycharmProjects\winlog\venv\Lib\site-packages\pyrebase'],
binaries=[],
datas=[],
hiddenimports=['schedule','pyrebase'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='update',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True )

My error after running exe

Traceback (most recent call last):
File "update.py", line 7, in
File "c:\users\win10\pycharmprojects\log\venv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
exec(bytecode, module.dict)
File "venv\Lib\site-packages\pyrebase\pyrebase.py", line 14, in
ImportError: attempted relative import with no known parent package

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "update.py", line 9, in
File "c:\users\win10\pycharmprojects\log\venv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
exec(bytecode, module.dict)
File "venv\Lib\site-packages\pyrebase\pyrebase.py", line 14, in
ImportError: attempted relative import with no known parent package
[2112] Failed to execute script update

Make sure these boxes are checked before submitting your issue:
[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Push with rtdb rules

Please note that I am not using the service account.

I am using the following rules to my rtdb:
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid",
".read": "$user_id === auth.uid"
}
}
}
}

And using the following code:
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
user = auth.sign_in_with_email_and_password('[email protected]', '*******')

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").child(user['localId']).push(data, user['idToken'])

I can write to the db, but it creates an additional node with the token:
image

Is it possible to write to the db without the token?

Feature Request

add google, facebook, twitter, github...... etc auth to this project. It would be really nice and helpful. Thanks

Unable to dynamically assign db collections path

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!


I tried to get the existing values from the firebase db using this following code, which works fine.

existing_data = db.child('account_group').child(new_member).get().val()

However, if i change it to dynamically assign the path of db it doesn't work.

member_path = db.child('account_group')
existing_data = member_path.child(new_member).get().val()

Is there a way to fix?

unable to get list of all files in firebase storage

i have a directory (wallpaper_app/Best_Wallpapers) in storage of firebase and it have some files iwant URL's of them all

but when i try to get list_files by
image = storage.child('wallpaper_app/Best_Wallpapers/').list_files()

iam facing error

File "d:\Project\wallpaper-app-kivy\temp.py", line 33, in <module>
  imageUrl = storage.list_files()
File "D:\Project\wallpaper-app-kivy\wallpaper-app\lib\site-packages\pyrebase\pyrebase.py", line 507, in list_files
  return self.bucket.list_blobs()
AttributeError: 'Storage' object has no attribute 'bucket'

Make sure these boxes are checked before submitting your issue:

[/] Check that your version of Python is 3.4+
[/] Check that you are on the newest version of Pyrebase
[/] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Closing connection

The truth is that Pyrebase has solved many problems for me, but I've been stuck in one for a few days, and I don't know what to do anymore. Maybe it is a silly question and its answer is very simple, but I am already short of ideas and I am looking for someone to enlighten me.

How can I close a connection that I have created with pyrebase without waiting for the system to determine that it needs to be closed?

Thanks

stream(), Passing "request" in stream_handler() function

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+ (my ver 3.7)
[x] Check that you are on the newest version of Pyrebase ( my Pyrebase4)
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.
Hi all,
i'm using Django and pyrebase
with rule of firebase like:
"rules": {
".read": "auth != null",
".write": "auth != null",
So we need to get idToken when to do something.
In my case, i save idToken in session, so i need request argument function to get idToken just like:

def postComment(request):
     idToken = request.session['uid']

But when i use stream(): how can i use request to get idToken in stream_handler function to retrieve data?? Something like:

stream_handler(request, message):
    idToken = request.session['uid']  #Stream_handler get dict first, and i can't use request argument.

Could we edit the pyrebase4 code? How to resolve this?
Hope somebody can resolve this. Thank you.

Problems with running on local emulators.

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Pyrebase does not work with emulators.

Emulators have a query parameter in the database url, this gets treated like part of the host in the current implementation (i.e. the path get's appended after).

Package installed but import fails.

I am trying to use this package but unfortunately when I run my code it just says that the module is not found, even thought pip says that the install requirment is already satisfied. I 've tried it on two Windows systems with a fresh install of Python.
(No I don't have any other versions of python installed)
please help.

Pyrebase4 and Security Rules

Hi, i have a question..
Does Pyrebase4 has a method to use for security rules?

by set "auth.uid != null" in rules,
i cant read / write to the database

seems like Pyrebase not capture/ detecting/ sending logged in user in Firebase server to apply with the rules
that has been set

import error

Make sure these boxes are checked before submitting your issue:

[] Check that your version of Python is 3.4+
[] Check that you are on the newest version of Pyrebase
[] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

import pyrebase gives error
from Crypto.PublicKey import RSA
ModuleNotFoundError: No module named 'Crypto'
Crypto is installed already.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

put method for storage throws error after authenticating server as service account

hello ,
First of thanks for maintaining this project, this is my first time using pyrebase and it has been immensely helpful.
I came across an error when i tried to upload files into my storage bucket after authenticating my server as admin by providing path to my ServiceAccount credentials in my config object. This was supposed to make firebase ignore security rules and that checked out but i got this error.
ERROR:
total bytes could not be determined. Please pass an explicit size, or supply a chunk size for a streaming transfer.

I looked into the error and found some discussions on github and stackoverflow that kinda gave me an idea of what was going on. looked at the put method in the storage class in the source code and then realized there was a upload_from_file method being called on the blob instance.

blob = self.bucket.blob(path)
  if isinstance(file, str):
           return blob.upload_from_filename(filename=file)
   else:
        nn return blob.upload_from_file(file_obj=file)

I traced that method into another file and saw it was a method implementation under the blob class in the google storage blob source code . The blob object instantiated in the put method has a chunk_size attribute that is checked for presence in the the object when the upload_from_file is called on it , if that fails, it then checks if the file size was provided also (and it that fails we get the error )

...

if self.chunk_size is not None:
            upload.chunksize = self.chunk_size

            if total_bytes is None:
                upload.strategy = RESUMABLE_UPLOAD
elif total_bytes is None:
            raise ValueError('total bytes could not be determined. Please '
                             'pass an explicit size, or supply a chunk size '
                             'for a streaming transfer.')

...

After the instantiation of the the blob object above with the path argument , there was not chunk_size argument specified . (my guess is this is needed to provide a directive on how the file is uploaded in chunks of the size you specify ). The value provided must be a multiple of 256 KB per the API specification.
These are links to some of the discussions and answers i found on stack overflow and github around this problem https://stackoverflow.com/questions/59210646/uploading-image-file-to-google-bucket-in-python

googleapis/google-cloud-python#3429

solution 1
A fix to this problem is simply providing a chunk_size argument to the blob object instance . If you look into the upload_from_file method source code i believe you’ll find out why this works.
code will now look like this

blob = self.bucket.blob(path, chunk_size="put chunk size here eg 262144")
  if isinstance(file, str):
           return blob.upload_from_filename(filename=file)
   else:
        return blob.upload_from_file(file_obj=file)

solution 2
Providing a size argument to the upload_from_file method will also solve the error as the error is produced when a conditional statement fails after checking if size was provided after it fails to find the chunk_size too. I suspect this solution causes the file to be uploaded in a single chunk other than in small chunks.

return blob.upload_from_file(file_obj=file, size="size of file here")

Please update the docs with proper snippets and templates. I'm just struggling with token and sending email verification

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!


I know it is absurd request but still. Why not make it so that using library is quick and easy. Try to do it in your free time.
Do it so that noobs like me can benefit from it.

Adding data to firebase

Make sure these boxes are checked before submitting your issue:

[] Check that your version of Python is 3.4+
[] Check that you are on the newest version of Pyrebase
[] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Cannot store database reference in variable

To make the code cleaner, I save the database references in a variable. However, this may lead to my entire database being deleted.

If I do NOT query the value from the database before "set ('test')", everything works as expected. If the value is loaded from the database beforehand, the complete database is deleted after "set". If only the value is queried from the database, nothing is deleted either.

Python version: 3.7.4
Pyrebase4 version: 4.5.0

This code deletes the database:

import pyrebase

firebase_config = {
    "apiKey": "..",
    "authDomain": "...",
    "databaseURL": "...",
    "projectId": "...",
    "storageBucket": "...",
    "messagingSenderId": "...",
    "appId": "...",
    "serviceAccount": '...'
}

firebase = pyrebase.initialize_app(firebase_config)
db = firebase.database()


queue_id = db.child('queue_id').child('4IYNzoZ63Am2XYkxMFXsN7').get().val()
status_ref = db.child('queue').child(queue_id).child('status')

status = status_ref.get().val()

status_ref.set('test')

And this works fine:

queue_id = db.child('queue_id').child('4IYNzoZ63Am2XYkxMFXsN7').get().val()
status_ref = db.child('queue').child(queue_id).child('status')

# status = status_ref.get().val()

status_ref.set('test')

After the "deletion" my database looks like this:
database_empty

Ordd

Make sure these boxes are checked before submitting your issue:

[] Check that your version of Python is 3.4+
[] Check that you are on the newest version of Pyrebase
[] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

equal_to() method gets the whole document instead of the parent only

I have this structure:

-User:
     -user1:
              -name : cycy
              -email: [email protected]

What I intend to do is know what parent does the input email contains. for example if my input email is [email protected], I should be able to output "user1". Here is my code:

hey = db.child("User").order_by_child("email").equal_to("[email protected]").get()
print(hey.val())

My problem with this code is that it outputs everything and not the parent "user1" only
OrderedDict([('user1', {'name: cycy, email: [email protected]})])

How can i modify this so that it only gives the parent "user1"

Thank you!

Issue with downloading files: File does not download and no errors

I am just trying to download all files in a folder, this worked on pyrebase on my main PC but somehow pyrebase can't be installed on my work PC so I googled and had to install pyrebase4.

apart from having to change this syntax: from storage.child(file.name).download(os.path.basename(file.name)) to storage.child(file.name).download(path, os.path.basename(file.name))

I was able to run the script without issues... until I realize that none of my files are getting downloaded. Maybe my path is incorrect? this is my script:

I know that my script able to access firebase because it worked on pyrebase on my PC and this is the print I get from path and file respectively.

path: https://firebasestorage.googleapis.com/v0/b/asdasdadasdad.appspot.com/o/records%2F000000000000053-777-cotizacion.pdf?alt=media
os.path.basename(file.name): 000000000000053-777-cotizacion.pdf

import pyrebase
import os
import time

project_root = os.path.dirname(os.path.dirname(__file__))
keys_path = os.path.join(project_root, 'keys')
hylKeyPath = os.path.join(keys_path, 'ServiceAccountKey.json')


firebase = pyrebase.initialize_app({
    "apiKey": "asdadasdasddadsa",
    "authDomain": "asdadsada.firebaseapp.com",
    "databaseURL": "https://asdasdaddasda.firebaseio.com",
    "storageBucket": "asdasdadasd.appspot.com",
    "serviceAccount": asdKeyPath
})

storage = firebase.storage()


def sleepCountDown(t):
    while t > 0:
        print(f"sleeping for {t} seconds...")
        t -= 1
        time.sleep(1)


while True:
    print('fetching data')
    files = storage.child('/').list_files()

    for file in files:
        if 'records/' in file.name:
            # get the file url path
            print(storage.child(file.name).get_url(None))

            path = storage.child(file.name).get_url(None)

            print(os.path.basename(file.name))

            # downloads file
            storage.child(file.name).download(path, os.path.basename(file.name))
            # deletes file? kinda deletes the entire folder
            storage.delete(file.name)
    sleepCountDown(10)

btw thanks for forking pyrebase.

Documentation on returned error messages

Hi there,

I've been using pyrebase4 for some time and was digging through the pyrebase documentation and the docs on the firebase website but haven't been able to find a list of possible error messages that could be returned.

Take this example for instance:

try:
      result = self.auth.sign_in_with_email_and_password(email, password)
except requests.HTTPError as e:
      error_json = e.args[1]
      error = json.loads(error_json)['error']['message']
      if error == "INVALID_PASSWORD":
          print("Password is invalid")
      if error == "EMAIL_NOT_VALID":
          print("No account found with this e-mail")

I had to find out by entering a wrong password that the error message "INVALID_PASSWORD" is returned and did another request with a non existing e-mail address to receive "EMAIL_NOT_VALID".
If anyone could steer me in the direction of a list of these returned values per auth function then it would save me a lot of time trying out all kinds of requests to see what exact error message gets returned to write exceptions for them. Putting these in the Pyrebase docs would be massively helpful as well! 😄

Thanks in advance.

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Service Account gets 401 Client Error after 1+ hours

Make sure these boxes are checked before submitting your issue:

[x] Check that your version of Python is 3.4+
[x] Check that you are on the newest version of Pyrebase
[x] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Hi,
I'm using Pyrebase4 for a project that, at its core, does nothing but waits for and reacts to changes to two Firebase database variables.
I've created a Service Account for this, per the readme, and the configuration seems to work. The Service Account has the Editor role per the GCP IAM console for this project.

After 1+ hours, I get a 401 error:

Exception` in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.5/dist-packages/pyrebase/pyrebase.py", line 619, in start_stream
for msg in self.sse:
File "/usr/local/lib/python3.5/dist-packages/pyrebase/pyre_sseclient.py", line 85, in next
self._connect()
File "/usr/local/lib/python3.5/dist-packages/pyrebase/pyrebase.py", line 584, in _connect
super(ClosableSSEClient, self)._connect()
File "/usr/local/lib/python3.5/dist-packages/pyrebase/pyre_sseclient.py", line 54, in _connect
self.resp.raise_for_status()
File "/usr/local/lib/python3.5/dist-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://powerswitch-4d391.firebaseio.com/shouldTakeAndUploadGaragePicture.json

This locks up the application and it cannot continue.

I looked into trying to refresh the Service Account token, but I don't see a way to do that.

Any suggestions on how to proceed?
Thanks!

Requirement is pinned for Pyrebase4 4.4.1: oauth2client==4.1.2

Description

Thanks for your support of Home Assistant!

(home-assistant) x$ pip install -r requirements_all.txt
...
(home-assistant) x$ pipdeptree -w silence -r -p oauth2client
oauth2client==4.0.0
...
  - gcloud==0.18.3 [requires: oauth2client>=2.0.1]
    - Pyrebase4==4.4.1 [requires: gcloud==0.18.3]
      - thermoworks-smoke==0.1.8 [requires: pyrebase4>=4.3.0]
  - Pyrebase4==4.4.1 [requires: oauth2client==4.1.2]
    - thermoworks-smoke==0.1.8 [requires: pyrebase4>=4.3.0]

Make sure these boxes are checked before submitting your issue:

  • Check that your version of Python is 3.4+
  • Check that you are on the newest version of Pyrebase
  • Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

can we use google authetication using pyrebase??

Make sure these boxes are checked before submitting your issue:

[] Check that your version of Python is 3.4+
[] Check that you are on the newest version of Pyrebase
[] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!

Can I work in pyrebase4 docs?

Can I work in pyrebase4 docs and make it more beginner friendly? Easy to use for beginners and noobs
Since I couldn't find your email I decided to reach out here. Sorry for that

AttributeError: module 'collections' has no attribute 'MutableMapping'

i get error while adding data

my code

import pyrebase

# Konfigurasi database Firebase
config = {
  	 "apiKey": "AIzaSyBxwerEkMk0IzRT_xN17HXhT-Qw743c-wg",
  "authDomain": "testdoang-e8396.firebaseapp.com",
  "projectId": "testdoang-e8396",
  "storageBucket": "testdoang-e8396.appspot.com",
  "messagingSenderId": "969724166255",
  "appId": "1:969724166255:web:03f0aa356ea1c8b30d4d9a",
  "measurementId": "G-LDLHNY5NN1"
}

# Inisialisasi koneksi ke Firebase
firebase = pyrebase.initialize_app(config)

# Inisialisasi instance database Firebase
db = firebase.database()

# CREATE (menambahkan data ke Firebase)
def tambah_data(nama, email, umur):
    data = {
        "nama": nama,
        "email": email,
        "umur": umur
    }
    db.child("pengguna").push(data)
    print("Data berhasil ditambahkan")

# READ (mengambil data dari Firebase)
def baca_data():
    data = db.child("pengguna").get()
    if data.val() == None:
        print("Belum ada data yang ditambahkan")
    else:
        print("Data yang tersimpan di Firebase:")
        for pengguna in data.each():
            print(pengguna.val())

# UPDATE (mengubah data di Firebase)
def ubah_data(key, nama, email, umur):
    data = {
        "nama": nama,
        "email": email,
        "umur": umur
    }
    db.child("pengguna").child(key).update(data)
    print("Data berhasil diubah")

# DELETE (menghapus data di Firebase)
def hapus_data(key):
    db.child("pengguna").child(key).remove()
    print("Data berhasil dihapus")

# Menambahkan data ke Firebase
tambah_data("Andi", "[email protected]", 27)

# Membaca data dari Firebase
baca_data()

# # Mengubah data di Firebase
# ubah_data("-MaWsb9eRp1A0A3fzj5M", "Budi", "[email protected]", 30)

# # Menghapus data di Firebase
# hapus_data("-MaWsb9eRp1A0A3fzj5M")

my python version

root@minx-Lenovo-V145-14AST:/home/minx/belajar/fletApp/flerebase# python3 --version
Python 3.10.6

get error like this

root@minx-Lenovo-V145-14AST:/home/minx/belajar/fletApp/flerebase# python3 main.py 
Traceback (most recent call last):
  File "/home/minx/belajar/fletApp/flerebase/main.py", line 1, in <module>
    import pyrebase
  File "/usr/local/lib/python3.10/dist-packages/pyrebase/__init__.py", line 1, in <module>
    from .pyrebase import initialize_app
  File "/usr/local/lib/python3.10/dist-packages/pyrebase/pyrebase.py", line 1, in <module>
    import requests
  File "/usr/local/lib/python3.10/dist-packages/requests/__init__.py", line 63, in <module>
    from . import utils
  File "/usr/local/lib/python3.10/dist-packages/requests/utils.py", line 28, in <module>
    from .structures import CaseInsensitiveDict
  File "/usr/local/lib/python3.10/dist-packages/requests/structures.py", line 15, in <module>
    class CaseInsensitiveDict(collections.MutableMapping):
AttributeError: module 'collections' has no attribute 'MutableMapping'

Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Hello, i'm trying to install pyrebase via pip, but I keep getting the same error:

C:\Users\admin>python3 -m pip install Pyrebase4
Collecting Pyrebase4
Using cached Pyrebase4-4.3.0-py3-none-any.whl (8.8 kB)
Requirement already satisfied: gcloud==0.18.3 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from Pyrebase4) (0.18.3)
Requirement already satisfied: python-jwt==2.0.1 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages\python_jwt-2.0.1-py3.8.egg (from Pyrebase4) (2.0.1)
Collecting requests-toolbelt>=0.7.1
Using cached requests_toolbelt-0.9.1-py2.py3-none-any.whl (54 kB)
Requirement already satisfied: requests>=2.19.1 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from Pyrebase4) (2.23.0)
Collecting oauth2client==4.1.2
Using cached oauth2client-4.1.2-py2.py3-none-any.whl (99 kB)
Collecting pycryptodome>=3.6.4
Using cached pycryptodome-3.9.7-cp38-cp38-win_amd64.whl (14.1 MB)
Requirement already satisfied: six in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud==0.18.3->Pyrebase4) (1.14.0)
Requirement already satisfied: googleapis-common-protos in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud==0.18.3->Pyrebase4) (1.52.0)
Requirement already satisfied: httplib2>=0.9.1 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud==0.18.3->Pyrebase4) (0.18.1)
Requirement already satisfied: protobuf!=3.0.0.b2.post1,>=3.0.0b2 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud==0.18.3->Pyrebase4) (3.11.3)
Collecting jws>=0.1.3
Using cached jws-0.1.3.tar.gz (8.1 kB)
ERROR: Command errored out with exit status 1:
command: 'C:\Users\admin\AppData\Local\Programs\Python\Python38\python3.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\admin\AppData\Local\Temp\pip-install-zn8e9kyp\jws\setup.py'"'"'; file='"'"'C:\Users\admin\AppData\Local\Temp\pip-install-zn8e9kyp\jws\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\admin\AppData\Local\Temp\pip-pip-egg-info-bmfgi4yr'
cwd: C:\Users\admin\AppData\Local\Temp\pip-install-zn8e9kyp\jws
Complete output (7 lines):
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\admin\AppData\Local\Temp\pip-install-zn8e9kyp\jws\setup.py", line 17, in
long_description=read('README.md'),
File "C:\Users\admin\AppData\Local\Temp\pip-install-zn8e9kyp\jws\setup.py", line 5, in read
return open(os.path.join(os.path.dirname(file), fname)).read()
UnicodeDecodeError: 'cp932' codec can't decode byte 0x93 in position 502: illegal multibyte sequence
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Python version:
C:\Users\admin>python3 --version
Python 3.8.3rc1

Pip version:
C:\Users\admin>python3 -m pip --version
pip 20.1.1 from C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\pip (python 3.8)

I found this question on StackOverflow https://stackoverflow.com/questions/50027201/installation-of-pyrebase-returns-an-error/50103097

I updated both setuptools and cloud, but i keep meeting the same error.

C:\Users\admin>python3 -m pip install --upgrade setuptools
Requirement already up-to-date: setuptools in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (47.1.1)

C:\Users\admin>python3 -m pip install --upgrade gcloud
Requirement already up-to-date: gcloud in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (0.18.3)
Requirement already satisfied, skipping upgrade: googleapis-common-protos in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud) (1.52.0)
Requirement already satisfied, skipping upgrade: six in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud) (1.14.0)
Requirement already satisfied, skipping upgrade: protobuf!=3.0.0.b2.post1,>=3.0.0b2 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud) (3.11.3)
Requirement already satisfied, skipping upgrade: oauth2client>=2.0.1 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages\oauth2client-3.0.0-py3.8.egg (from gcloud) (3.0.0)
Requirement already satisfied, skipping upgrade: httplib2>=0.9.1 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from gcloud) (0.18.1)
Requirement already satisfied, skipping upgrade: setuptools in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from protobuf!=3.0.0.b2.post1,>=3.0.0b2->gcloud) (47.1.1)
Requirement already satisfied, skipping upgrade: pyasn1>=0.1.7 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from oauth2client>=2.0.1->gcloud) (0.4.8)
Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.0.5 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from oauth2client>=2.0.1->gcloud) (0.2.8)
Requirement already satisfied, skipping upgrade: rsa>=3.1.4 in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (from oauth2client>=2.0.1->gcloud) (4.0)

I also tried to run CMD as and admin, still the same problem.
This is not a problem with PIP because it installs all the other packages without errors.
I get this error with Pyrebase4 AND Pyrebase.

Firebase Storage - Download Path

Make sure these boxes are checked before submitting your issue:

storage.child(#firebse-file-path-location).download(filename='#local-path-location', path='#?')

What is "path" do/refer to in download method?

Thank you for helping make Pyrebase better!

'str' object has no attribute 'sign_in_with_email_and_password'

Hi!
I'm trying to login to existing user accounts. I am sure everything is setup correctly (python 3.5, Auth Sign In enabled in my Firebase). However, I keep having the same problem over and over: 'str' object has no attribute 'sign_in_with_email_and_password(email, password)'.

here's the code:

def sign_in():
    global auth
    global user
    email = input("Please, enter your email")
    password = input("Please, enter your password")
    user = auth.sign_in_with_email_and_password(email, password)
    get_user_id(user)

I can't seem to find a solution.
Any help?!

Pyrebase4 auth not working

Make sure these boxes are checked before submitting your issue:

[X] Check that your version of Python is 3.4+ (3.7.10)
[X] Check that you are on the newest version of Pyrebase (4.5.0)
[X] Check that Email/password provider is enabled in your Firebase dashboard under Auth -> Sign In Method.

Please don't be discouraged if you do not get a response to your issue quickly,
I maintain Pyrebase for fun and don't always have as much free time as I'd like.

Thank you for helping make Pyrebase better!


Unfortunately I can't login with pyrebase and get the user info. Firebase is giving 401. On the frontend, the React app does work correctly and using the request simulator from firebase it works ok too, so it's not an issue with the rules. Here is my code:

    email = post_data.get('email')
    password = post_data.get('password')
    user = pb.auth().sign_in_with_email_and_password(email, password)
    # user1 = fb_auth.verify_id_token(user["idToken"])

    # When coming back from sign in uid is localId for some reason...
    # FIXME: this line is raising 401
    user_info = pb.database().child("users").child(user["localId"]).get().val()

This are my testing rules:

{
  "rules": {
    ".read": "auth.uid != null",
    ".write": "auth.uid != null"
  }
}

Pyrebase works if rules are disabled (.write, .read both true)

This issue is already present in the old library. It seems weird that nobody noticed it because it's such a basic function. I'll probably fallback to using a service account, but that's not what I intended in the first place.

thisbejim#341

Thanks

Library needs to be updated. Requests- Toolsbelt was updated today and Pyrebase4 now throws import error

File "/home/appuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
exec(code, module.dict)
File "/app/cleeve-2/main.py", line 35, in
import pyrebase
File "/home/appuser/venv/lib/python3.9/site-packages/pyrebase/init.py", line 1, in
from .pyrebase import initialize_app
File "/home/appuser/venv/lib/python3.9/site-packages/pyrebase/pyrebase.py", line 20, in
from requests_toolbelt.adapters import appengine
File "/home/appuser/venv/lib/python3.9/site-packages/requests_toolbelt/adapters/appengine.py", line 42, in
from .._compat import gaecontrib

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.