Giter VIP home page Giter VIP logo

python-firebase's Introduction

Python Firebase

Python interface to the Firebase's REST API

Firebase

Installation

Build Status

python-firebase highly makes use of the requests library so before you begin, you need to have that package installed.

$ sudo pip install requests
$ sudo pip install python-firebase

Getting Started

You can fetch any of your data in JSON format by appending '.json' to the end of the URL in which your data resides and, then send an HTTPS request through your browser. Like all other REST specific APIs, Firebase offers a client to update(PATCH, PUT), create(POST), or remove(DELETE) his stored data along with just to fetch it.

The library provides all the correspoding methods for those actions in both synchoronous and asynchronous manner. You can just start an asynchronous GET request with your callback function, and the method

To fetch all the users in your storage simply do the following:

from firebase import firebase
fb_app = firebase.FirebaseApplication('https://your_storage.firebaseio.com', None)
result = fb_app.get('/users', None)
print result
{'1': 'John Doe', '2': 'Jane Doe'}

The second argument of get method is the name of the snapshot. Thus, if you leave it NULL, you get the data in the URL /users.json. Besides, if you set it to 1, you get the data in the url /users/1.json. In other words, you get the user whose ID equals to 1.

from firebase import firebase
fb_app = firebase.FirebaseApplication('https://your_storage.firebaseio.com', None)
result = fb_app.get('/users', '1')
print result
{'1': 'John Doe'}

You can also provide extra query parameters that will be appended to the url or extra key-value pairs sent in the HTTP header.

from firebase import firebase
fb_app = firebase.FirebaseApplication('https://your_storage.firebaseio.com', None)
result = fb_app.get('/users/2', None, {'print': 'pretty'}, {'X_FANCY_HEADER': 'VERY FANCY'})
print result
{'2': 'Jane Doe'}

Creating new data requires a POST or PUT request. Assuming you don't append print=silent to the url, if you use POST the returning value becomes the name of the snapshot, if PUT you get the data you just sent. If print=silent is provided, you get just NULL because the backend never sends an output.

from firebase import firebase
fb_app = firebase.FirebaseApplication('https://your_storage.firebaseio.com', None)
new_user = 'Ozgur Vatansever'

result = fb_app.post('/users', new_user, {'print': 'pretty'}, {'X_FANCY_HEADER': 'VERY FANCY'})
print result
{u'name': u'-Io26123nDHkfybDIGl7'}

result = fb_app.post('/users', new_user, {'print': 'silent'}, {'X_FANCY_HEADER': 'VERY FANCY'})
print result == None
True

Deleting data is relatively easy compared to other actions. You just set the url and that's all. Backend sends no output as a result of a delete operation.

from firebase import firebase
fb_app = firebase.FirebaseApplication('https://your_storage.firebaseio.com', None)
fb_app.delete('/users', '1')
# John Doe goes away.

Authentication

Authentication in Firebase is nothing but to simply creating a token that conforms to the JWT standards and, putting it into the querystring with the name auth. The library creates that token for you so you never end up struggling with constructing a valid token on your own. If the data has been protected against write/read operations with some security rules, the backend sends an appropriate error message back to the client with the status code 403 Forbidden.

from firebase import firebase
fb_app = firebase.FirebaseApplication('https://your_storage.firebaseio.com', authentication=None)
result = fb_app.get('/users', None, {'print': 'pretty'})
print result
{'error': 'Permission denied.'}

authentication = firebase.FirebaseAuthentication('THIS_IS_MY_SECRET', '[email protected]', extra={'id': 123})
fb_app.authentication = authentication
print authentication.extra
{'admin': False, 'debug': False, 'email': '[email protected]', 'id': 123, 'provider': 'password'}

user = authentication.get_user()
print user.firebase_auth_token
"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJhZG1pbiI6IGZhbHNlLCAiZGVidWciOiBmYWxzZSwgIml
hdCI6IDEzNjE5NTAxNzQsICJkIjogeyJkZWJ1ZyI6IGZhbHNlLCAiYWRtaW4iOiBmYWxzZSwgInByb3ZpZGVyIjog
InBhc3N3b3JkIiwgImlkIjogNSwgImVtYWlsIjogIm96Z3VydnRAZ21haWwuY29tIn0sICJ2IjogMH0.lq4IRVfvE
GQklslOlS4uIBLSSJj88YNrloWXvisRgfQ"

result = fb_app.get('/users', None, {'print': 'pretty'})
print result
{'1': 'John Doe', '2': 'Jane Doe'}

Concurrency

The interface heavily depends on the standart multiprocessing library when concurrency comes in. While creating an asynchronous call, an on-demand process pool is created and, the async method is executed by one of the idle process inside the pool. The pool remains alive until the main process dies. So every time you trigger an async call, you always use the same pool. When the method returns, the pool process ships the returning value back to the main process within the callback function provided.

import json

from firebase import firebase
from firebase import jsonutil

fb_app = firebase.FirebaseApplication('https://your_storage.firebaseio.com', authentication=None)

def log_user(response):
    with open('/tmp/users/%s.json' % response.keys()[0], 'w') as users_file:
        users_file.write(json.dumps(response, cls=jsonutil.JSONEncoder))

fb_app.get_async('/users', None, {'print': 'pretty'}, callback=log_user)

TODO

  • Async calls must deliver exceptions raised back to the main process.
  • More regression/stress tests on asynchronous calls.
  • Docs must be generated.

python-firebase's People

Contributors

14ngiestas avatar adeshatole avatar anonymousdouble avatar b4oshany avatar bahattincinic avatar darrelfrancis avatar emrcftci avatar gholadr avatar heartpunk avatar hobthross avatar jayd3e avatar kmader avatar mjbrisebois avatar nyc432 avatar ozgur 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-firebase's Issues

process pooling does not play well with django runserver

In development mode, I often have to restart the runserver.

The atexit method, which cleans up the process pool, causes unpredictable behavior on runserver shutdown. I believe that this is because the lazyloader first instantiates the process pool during the atexit callback, during your attempt to terminate that same process pool.

Why is a new token generated for each request?

    def _authenticate(self, params, headers):
        """
        Method that simply adjusts authentication credentials for the
        request.
        `params` is the querystring of the request.
        `headers` is the header of the request.
        If auth instance is not provided to this class, this method simply
        returns without doing anything.
        """
        if self.authentication:
            user = self.authentication.get_user()
            params.update({'auth': user.firebase_auth_token})
            headers.update(self.authentication.authenticator.HEADERS)

The _authenticate method is invoked for each request. Each time self.authentication.get_user() is invoked, a new JWT token is built:

    def get_user(self):
        """
        Method that gets the authenticated user. The returning user has
        the token, email and the provider data.
        """
        token = self.authenticator.create_token(self.extra)  # creates new JWT
        user_id = self.extra.get('id')
        return FirebaseUser(self.email, token, self.provider, user_id)

Why is a new token built for each request? It seems to me like the sensible thing to do would be to build a token in the constructor of FirebaseAuthentication, and stash it in the authenticator object? The caller should be able to specify when this token expires.

post() got multiple values for keyword argument 'connection'

This was a closed bug but I think still there is a problem when I post like this :
result = firebase.post('/users', new_user, {'print': 'pretty'}, {'X_FANCY_HEADER': 'VERY FANCY'})

I get the following error :
post() got multiple values for keyword argument 'connection'

patch() does not have param 'name'

The params for the patch() method do not match the other verbs, like those for GET, DELETE and PUT, which accept 'name' and then use build_endpoint_url().

This forces the caller to compose the path himself, ie partially re-implement build_endpoint_url().

At this point, it would be understandably difficult to insert a param at position 2. Therefore, I am not sure what the ideal solution for you may be.

Storing data with period

How would I ever go about storing any data with a period?

firebase.put('/',".", {'print':'silent'})
firebase.put('/',"""{"test":"."}""", {'print': 'silent'})
firebase.put('/test',".", {'print': 'silent'})

All of these will result in a 400 Client Error.

Order by (orderBy) filter requires quoted param in get request

Using:
result = firebase_app.get("/", "article", params={"startAt": "100", "orderBy": "msrp"})
Return the error
Bad Request for url: https://pennywise.firebaseio.com/article.json?orderBy=msrp&startAt=10

To get it working, a manual insertion of quotes is required.
result = firebase_app.get("/", "article", params={"startAt": "100", "orderBy": "\"msrp\""})
Returns successfully

My issue, if the orderBy params requires quotes it should be handled in the backend call.

New Firebase

Will the new Firebase still work with your library? If not, are you planning to update it?

Thanks for your good work!

Installing to Heroku fails

Installing to Heroku fails sometimes, b/c simply running any setuptools command requires requests to be installed. This is due to the fact that the version is obtained from here. Here is an example of the error message that you would receive if experiencing this error:

       Obtaining python-firebase from git+git://github.com/jayd3e/python-firebase.git#egg=python_firebase (from -r requirements.txt (line 42))
         Cloning git://github.com/jayd3e/python-firebase.git to ./.heroku/src/python-firebase
         Running setup.py egg_info for package python-firebase
           Traceback (most recent call last):
             File "<string>", line 16, in <module>
             File "/app/.heroku/src/python-firebase/setup.py", line 9, in <module>
               from firebase import __version__
             File "firebase/__init__.py", line 4, in <module>
               from firebase import *
             File "firebase/firebase.py", line 10, in <module>
               from .decorators import http_connection
             File "firebase/decorators.py", line 1, in <module>
               import requests
           ImportError: No module named requests
           Complete output from command python setup.py egg_info:
           Traceback (most recent call last):

         File "<string>", line 16, in <module>

         File "/app/.heroku/src/python-firebase/setup.py", line 9, in <module>

           from firebase import __version__

         File "firebase/__init__.py", line 4, in <module>

           from firebase import *

         File "firebase/firebase.py", line 10, in <module>

           from .decorators import http_connection

         File "firebase/decorators.py", line 1, in <module>

           import requests

       ImportError: No module named requests`

TypeError: get() got multiple values for keyword argument 'connection'

Following the get examples in the documentation, here's my ipython session.
Using python 2.7.3.

In [1]: from firebase import firebase
In [2]: f = firebase.FirebaseApplication('https://.firebaseio.com')
In [3]: result = f.get('/pins/3', None, None, {'print': 'pretty'}, {'X_FANCY_HEADER': 'VERY FANCY'})


TypeError Traceback (most recent call last)
in ()
----> 1 result = f.get('/pins/3', None, None, {'print': 'pretty'}, {'X_FANCY_HEADER': 'VERY FANCY'})

/home/vagrant/venv/cooliyo/local/lib/python2.7/site-packages/firebase/decorators.pyc in wrapped(_args, *_kwargs)
17 connection.timeout = timeout
18 connection.headers.update({'Content-type': 'application/json'})
---> 19 return f(_args, *_kwargs)
20 return wraps(f)(wrapped)
21 return wrapper

TypeError: get() got multiple values for keyword argument 'connection'


i think the decorator is feeding the 'connection' as a keyword arg, when the get function expects the connection as a positional arg (index = 3) and there are other positional args after it.

Has anyone else run into this problem. Fixed this by modifying the decorator (http_connection) to update the positional arg instead of kwarg.

I am sure I am missing something obvious.

Can this run on Google App Engine?

I'm getting this error:

File "/Users/micahbolen/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 84, in LoadObject
obj = __import__(path[0])
  File "/Users/micahbolen/Desktop/institutions-search/helloworld.py", line 4, in <module>
from firebase import firebase
  File "/Users/micahbolen/Desktop/institutions-search/gaenv_lib/firebase/__init__.py", line 3, in <module>
from .async import process_pool
  File "/Users/micahbolen/Desktop/institutions-search/gaenv_lib/firebase/async.py", line 1, in <module>
import multiprocessing
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/__init__.py", line 65, in <module>
from multiprocessing.util import SUBDEBUG, SUBWARNING
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/util.py", line 40, in <module>
from subprocess import _args_from_interpreter_flags
ImportError: cannot import name _args_from_interpreter_flags

exception: Failed to validate Mac

After I set a rule which allow some user to write to Firebase, a exception was thrown.
It is ok with the iOS SDK, but python will crash.

code:

    f = firebase.FirebaseApplication('https://glowing-fire-xxxx.firebaseIO.com', None)
    f.authentication = firebase.FirebaseAuthentication('xxxx', '[email protected]')
    ref = "/v/2/vd"
    f.put(ref,"2016","a:3:5") // throw exception

the rule:

{
    "rules": {
        ".read": true,
        "v":{
           ".read": true,
           ".write": "auth != null&&auth.uid=='xxx-xxx-af2d'"
        }
    }
}

exception:

_content = {str} '{\n  "error" : "Failed to validate MAC."\n}\n'
_content_consumed = {bool} True
apparent_encoding = {str} 'ascii'
connection = {HTTPAdapter} <requests.adapters.HTTPAdapter object at 0x110fc8790>
content = {str} '{\n  "error" : "Failed to validate MAC."\n}\n'
cookies = {RequestsCookieJar} <RequestsCookieJar[]>
elapsed = {timedelta} 0:00:01.277145
encoding = {str} 'utf-8'
headers = {CaseInsensitiveDict} CaseInsensitiveDict({'content-length': '42', 'strict-transport-security': 'max-age=31556926; includeSubDomains; preload', 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache'})
history = {list} []
links = {dict} {}
ok = {bool} False
raw = {HTTPResponse} <requests.packages.urllib3.response.HTTPResponse object at 0x110fdffd0>
reason = {str} 'Bad Request'
request = {PreparedRequest} <PreparedRequest [PUT]>
status_code = {int} 400
text = {unicode} u'{\n  "error" : "Failed to validate MAC."\n}\n'
url = {unicode} u'https://xxx.firebaseIO.com/v/2/vd/2016.json?auth=eyJhbGciOiAiSFMyNTYiLCAidasdfG1pbiI6IGZhbHNlLCAiZGVidWciOiBmYWxzZSwgImlhdCI6IDE0NTcxMzI2MjEsICJkIjogeyJkZWJ1ZyI6IGZhbHNlLCAiYWRtaW4iOiBmYWxzZSwgImVtYWlsIjogImltcW

Traceback

Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 2411, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1802, in run
    launch(file, globals, locals)  # execute the script
  File "/Users/xxx/script/xxxx.py", line 373, in <module>
    f.put(ref,xxx,xxx)
  File "/Library/Python/2.7/site-packages/firebase/decorators.py", line 19, in wrapped
    return f(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/firebase/firebase.py", line 302, in put
    connection=connection)
  File "/Library/Python/2.7/site-packages/firebase/decorators.py", line 19, in wrapped
    return f(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/firebase/firebase.py", line 72, in make_put_request
    response.raise_for_status()
  File "/Library/Python/2.7/site-packages/requests/models.py", line 683, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request
Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 2411, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1802, in run
    launch(file, globals, locals)  # execute the script
  File "/Users/huifengqi/workspace/xxx/script/myFile.py", line 373, in <module>
    f.put(ref,ds2,hp.retVerse)
  File "/Library/Python/2.7/site-packages/firebase/decorators.py", line 19, in wrapped
    return f(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/firebase/firebase.py", line 302, in put
    connection=connection)
  File "/Library/Python/2.7/site-packages/firebase/decorators.py", line 19, in wrapped
    return f(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/firebase/firebase.py", line 72, in make_put_request
    response.raise_for_status()
  File "/Library/Python/2.7/site-packages/requests/models.py", line 683, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request

Error handling for async calls

It doesn't appear that there's a way to tell when one of the _async methods returns an error status code. I don't see how we can catch the HttpError that is raised normally. Maybe I'm just not looking in the right place?

ThreadPool instead of multiprocessing.Pool

Would there be any problems with using ThreadPool instead of multiprocessing.Pool in the library?

I created a patch that performs the switch however I would like to understand whether this change doesn't cause any thread-safety problems. From what I can see requests library is thread-safe. Are there any shared resources between different "jobs" executed inside the pool?

Sending additional parameters not working

I haven't been able to properly pass parameters like the following:

result = firebase.get('/users/2', None, {'print': 'pretty'}, {'X_FANCY_HEADER': 'VERY FANCY'})

I get errors when I try to use print or silent params.

401 Client Error: Unauthorized

I'm running into intermittent errors when sending updates to firebase with this library.

For example, if I send a PUT request to this firebase resource: /test/123 with the data payload of {'test': 123} it will randomly fail with a response of 401 Client Error: Unauthorized.

It seems very random. I sent two requests back-to-back and the first one failed while the second succeeded.

This was the first payload:
eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJ2IjogMCwgImRlYnVnIjogZmFsc2UsICJhZG1pbiI6IHRydWUsICJpYXQiOiAxNDQ4MDM4Njk5LCAiZCI6IHsiZGVidWciOiBmYWxzZSwgInByb3ZpZGVyIjogInBhc3N3b3JkIiwgImFkbWluIjogdHJ1ZSwgImVtYWlsIjogInRlc3RAdGVzdC5jb20ifX0.07P1p5GhKAxbzXv4UK1ggohsOKKM5heJahRM-R8npBs

This was the second:
eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJ2IjogMCwgImRlYnVnIjogZmFsc2UsICJhZG1pbiI6IHRydWUsICJpYXQiOiAxNDQ4MDM4NzAxLCAiZCI6IHsiZGVidWciOiBmYWxzZSwgInByb3ZpZGVyIjogInBhc3N3b3JkIiwgImFkbWluIjogdHJ1ZSwgImVtYWlsIjogInRlc3RAdGVzdC5jb20ifX0.1yJxoP-CLNWjs0305Y4_MUlxGM7GDgt97EGoqtIKJ3k

If you look at these tokens at http://jwt.io/ you'll see the first token had an iat claim of 1448038699 and the next was 1448038701.

Because this issue seems to be rather random, my suspicion leads me to believe it has to do with the timing and the iat claim, but I may be barking up the wrong tree.

It looks like this library uses different logic than the official python library when creating the iat claim, it appears firebase has since updated their logic. I've updated my local codebase to use their new code, but it didn't help.

Btw it seems others may have experienced this issue:

I've shot off an email to firebase support and they think it could be related to the iat claim as well but at this point I am seeking other opinions. Thanks!

python-firebase requires your Firebase Secret to be embedded in code?

If I understand this library correctly, you're using the Secret to dynamically generate a token for use with the REST API.

The firebase-token-generator code, which you've copied into this library, says this:

"IMPORTANT: Because token generation requires your Firebase Secret, you should only generate tokens on trusted servers. Never embed your Firebase Secret directly into your application and never share your Firebase Secret with a connected client."

https://github.com/firebase/firebase-token-generator-python

Doesn't using your library with authentication require that you do indeed 'embed your Firebase Secret directly into your application'?

Alternative to multiprocessing?

Having an issue using this on App Engine

ERROR    2015-03-16 21:37:06,549 wsgi.py:263] 
Traceback (most recent call last):
 File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
   handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
 File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
   handler, path, err = LoadObject(self._handler)
 File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
   obj = __import__(path[0])
 File "/Users/kevinchau/Dev/airfare/main.py", line 9, in <module>
   from firebase import firebase
 File "/Users/kevinchau/Dev/airfare/lib/firebase/__init__.py", line 3, in <module>
   from .async import process_pool
 File "/Users/kevinchau/Dev/airfare/lib/firebase/async.py", line 1, in <module>
   import multiprocessing
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/__init__.py", line 65, in <module>
   from multiprocessing.util import SUBDEBUG, SUBWARNING
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/util.py", line 40, in <module>
   from subprocess import _args_from_interpreter_flags
ImportError: cannot import name _args_from_interpreter_flags
INFO     2015-03-16 21:37:06,557 module.py:737] default: "GET /blast HTTP/1.1" 500 -

Is there an alternative to multiprocessing?

Dict support?

If I do

dt = {'k': 'v'}
put('/', dt)
I would expect that it to work and put a single key value in the root.

Instead I get 400 Client Error

502 Server Error: Bad Gateway

When I post data to firebase sychron from time to time I get the error:

HTTPError: 502 Server Error: Bad Gateway
This seems to be random. I can't identify the reason.

This doesn't seem to happen with async post. Can you give me a hint why this could be?

Windows import of module causes program to loop

So, on Linux it works fine, but I have this problem on 3 completely separate windows machines. The following code:

from firebase import *
print "test"

Causes the following output:
test
test
test
test
test
test

For some reason, simply importing the module causes the main program to loop 6 times, but only in Windows. Hopefully someone has some idea why it's doing this.

rename the unique name at post request on firebase

support I am doing a post request on the firebase.

result = fb.post('/orders/', {'id': 2})

in result I always get the unique name generated at the time of post request. Like
{u'name': u'-KAdbw7DfCuuRhFWZH7j'}

But I need to give it name of my choice.
{u'name': 'aaa'}

Is there any means to do that.

Cause the item created needs to be access and updated using the put request so I need to pass this unique id to make a put request. If I would give the name of my choice I can use that name without passing an extra argument in my request json.

post_async() is not working.

I tried post_async method to send data to firebase, but post_async() is not working.

firebase.post(url='/test/newsfeed', data=data) is working, but
firebase.post_async(url='/test/newsfeed', data=data) is not working.

noob questions

I'm very new to firebase, and I basically want to populate a base from Python,
so I wrote the following code following the tutorial:

import json, multiprocessing
from firebase import firebase

multiprocessing.freeze_support() #prevents crashes in debugger/win

ref = firebase.FirebaseApplication('https://mybasehere.firebaseio.com/', authentication=None)

result = ref.get('/test', None)
print result

result = ref.post('/test', {'test4':'posted'})
print result

which starts by giving the expected result (I entered some data through firebase's dashboard):

{u'test1': 1, u'test3': {u'test32': u'another one', u'test31': u'subtest'}, u'test2': u'test2'}
{u'name': u'-JcxGMqR_yyfWJVLfN8G'}

but then the program pauses a few seconds and outputs 2x5 more lines :

{u'test1': 1, u'test3': {u'test32': u'another one', u'test31': u'subtest'}, u'test2': u'test2', u'-JcxGMqR_yyfWJVLfN8G': {u'test4': u'posted'}}
{u'test1': 1, u'test3': {u'test32': u'another one', u'test31': u'subtest'}, u'test2': u'test2', u'-JcxGMqR_yyfWJVLfN8G': {u'test4': u'posted'}}
{u'test1': 1, u'test3': {u'test32': u'another one', u'test31': u'subtest'}, u'test2': u'test2', u'-JcxGMqR_yyfWJVLfN8G': {u'test4': u'posted'}}
{u'test1': 1, u'test3': {u'test32': u'another one', u'test31': u'subtest'}, u'test2': u'test2', u'-JcxGMqR_yyfWJVLfN8G': {u'test4': u'posted'}}
{u'test1': 1, u'test3': {u'test32': u'another one', u'test31': u'subtest'}, u'test2': u'test2', u'-JcxGMqR_yyfWJVLfN8G': {u'test4': u'posted'}}
{u'name': u'-JcxGPf-zpGnnGZR35iW'}
{u'name': u'-JcxGPfgPhD4XXK302dn'}
{u'name': u'-JcxGPfr_eaeLRhaHyBr'}
{u'name': u'-JcxGPg7vijAUTv1HbxX'}
{u'name': u'-JcxGPgvRqFXM69hM_qT'}

and I see 6 new records in firebase's dashboard instead of a single 'test4' as expected.
What happened ? and how can I write key='test4' with value='posted' simply in 'test' ?

SSL: CERTIFICATE_VERIFY_FAILED error on PUT request

Hi,
I tried running this piece of code: (that used to work a month ago..)

frb = firebase.FirebaseApplication( 'https://myapp.firebaseio.com', authentication=None) result = frb.put('/latestdata/' ,name=somename, data=data)

and i get this SSL error every time!
File "C:\Python27\lib\site-packages\firebase\firebase.py", line 68, in make_put_request timeout=timeout) File "C:\Python27\lib\site-packages\requests\sessions.py", line 521, in put return self.request('PUT', url, data=data, **kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Python27\lib\site-packages\requests\adapters.py", line 447, in send raise SSLError(e, request=request) SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)

Any Idea why it starts happening?
when i open the url with Chrome, there is no problem with the certificate or whatsoever.

post() got multiple values for keyword argument 'connection error

I'm getting the following error with the following sample case:

from firebase import firebase
firebase = firebase.FirebaseApplication('https://ustun-test.firebaseio.com', None)

new_activity = {
    "user": "Ustun",
    "action_type": "asked",
    "text": "a text questions",
    "url": "a url"
}

result = firebase.post('/activities', "x", {'print': 'pretty'}, {'a': 'b'})
print result

A sample traceback:

python firebase_integration.py
> /Users/ustun/scv14/lib/python2.7/site-packages/firebase/decorators.py(21)wrapped()
     20             import ipdb; ipdb.set_trace()
---> 21             return f(*args, **kwargs)
     22         return wraps(f)(wrapped)

ipdb> args
args = (<firebase.firebase.FirebaseApplication object at 0x10f05b910>, '/activities', 'x', {'print': 'pretty'}, {'a': 'b'})
kwargs = {'connection': <requests.sessions.Session object at 0x10f0ff890>}
ipdb> kwargs
{'connection': <requests.sessions.Session object at 0x10f0ff890>}
ipdb> c
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
firebase_integration.py in <module>()
      9 }
     10 
---> 11 result = firebase.post('/activities', "x", {'print': 'pretty'}, {'a': 'b'})
     12 print result

/Users/ustun/scv14/lib/python2.7/site-packages/firebase/decorators.py in wrapped(*args, **kwargs)
     19             connection.headers.update({'Content-type': 'application/json'})
     20             import ipdb; ipdb.set_trace()
---> 21             return f(*args, **kwargs)
     22         return wraps(f)(wrapped)
     23     return wrapper

TypeError: post() got multiple values for keyword argument 'connection'

Here is what args and kwargs are:

ipdb> args
args = (<firebase.firebase.FirebaseApplication object at 0x10b4df910>, '/activities', 'x', {'print': 'pretty'}, {'a': 'b'})
kwargs = {'connection': <requests.sessions.Session object at 0x10b583890>}
ipdb> kwargs
{'connection': <requests.sessions.Session object at 0x10b583890>}

Why not depend on firebase-token-generator-python instead of copying it?

The comment at the top of firebase/firebase_token_generator.py :

##############################################################################
# THE ENTIRE CODE HAS BEEN TAKEN FROM THE OFFICIAL FIREBASE GITHUB           #
# REPOSITORY NAMED `firebase-token-generator-python` WITH SLIGHT             #
# MODIFICATIONS.                                                             #
#                                                                            #
# FOR MORE INFORMATION, PLEASE TAKE A LOOK AT THE ACTUAL REPOSITORY:         #
#  - https://github.com/firebase/firebase-token-generator-python             #
##############################################################################

Why not just depend on it in your setup.py / requirements.txt? Also, for the more paranoid among us, what exactly were the "slight modifications" made to the original code? Unless you have an excellent reason (which are rare), modifying someone else's crypto code doesn't seem like a good idea (easy to mess up, you miss out on future bug fixes, etc.). I would recommend just depending on the original code rather than maintaining a copy of it here.

SSL Error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

I am using Python 2.7.9 with OpenSSL 1.0.1f 6 Jan 2014 .

On building the following code

 from firebase import firebase
 firebase = firebase.FirebaseApplication('https://test.firebaseio.com',None)
 data = {'testVal': '0'}
 result = firebase.post('/user', data)
 print (result)

However I got the following error

    File "/usr/local/lib/python2.7/dist-packages/firebase/decorators.py", line 19, in wrapped
      return f(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/firebase/firebase.py", line 329, in post
      connection=connection)
    File "/usr/local/lib/python2.7/dist-packages/firebase/decorators.py", line 19, in wrapped
      return f(*args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/firebase/firebase.py", line 97, in make_post_request
      timeout=timeout)
    File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 340, in post
      return self.request('POST', url, data=data, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 279, in request
      resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
    File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 374, in send
      r = adapter.send(request, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 213, in send
      raise SSLError(e)
  requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

how to use put?

Sorry but I am to stupid to use the put method. Can you give me an example?

Type error

Hi,

first of all - thanks for this library!

Then - the example in the readme works only partially for me.
This example works:

firebase.get('/users', None)

and this doesn't:

firebase.get('/users', None, {'print': 'pretty'})

This gives me:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print firebase.get('/users', None, {'print': 'pretty'})
  File "/Library/Python/2.7/site-packages/firebase/decorators.py", line 19, in wrapped
    return f(*args, **kwargs)
TypeError: get() got multiple values for keyword argument 'connection'

Also, in the the last example I needed to change this line:

firebase.get_async('/users', None, {'print': 'pretty'}, callback=log_user) 

to

firebase.get_async(url='/users', name=None, params=None, callback=log_user)

to get it working, but - the callback doesn't seem to work.
I tried this on Python 2.7.1 and 2.7.3.
It seems to be related to http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments .

What version are you using?

Best,
Dirk

Take this repo down

Has not been updates for years and provides confusion that are new. This DOES not work. Else provide a warning that this repo is broken

python code running several times when run through command line

I'm running a simple script with just a firebase import and am running into an issue where it runs the code several times over multiple threads.

#! python

from firebase import firebase
import sys

print "Hello"
print (sys.version)

returns the following:

C:\>python test.py
Hello
2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
Bye
Hello
2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
ByeHH
elloello

22.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)].7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]

BByeye

Hello
2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
Bye
Hello
2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
Bye

whereas

#! python

import sys

print "Hello"
print (sys.version)

returns the correct:

Hello
2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]

I'm running python 2.7.10 on Windows 10 in the command line.

orderBy does not return records in order

Actually, the firebase returns the json string in the right order. However, then, make_get_request() from firebase.py returns response.json() as a result. This call breaks the right order.

Python 2.7.9 ImportError: cannot import name firebase

I just installed via pip python-firebase (and requests) into a brand new virtualenv running Python 2.7.9, yet when I try to use from firebase import firebase Python spits out the following error:

ImportError: cannot import name firebase

I know for a fact the module and its prereqs are installed because I can see them in the list of modules generated by help('modules')

I created this virtual environment after running into the same issue developing without a virtual environment (e.g. I was installing everything to the system's typical Python install). I figured I'd messed something up so I started over with a fresh virtual environment and used it exclusively when I was reinstalling my other dependencies.

Am I doing something wrong? Is Python 2 not supported?

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.