firebase / firebase-admin-python Goto Github PK
View Code? Open in Web Editor NEWFirebase Admin Python SDK
Home Page: https://firebase.google.com/docs/admin/setup
License: Apache License 2.0
Firebase Admin Python SDK
Home Page: https://firebase.google.com/docs/admin/setup
License: Apache License 2.0
Currently firebase_admin.App
has a set of private methods for generating OAuth2 tokens. It also handles token caching. But the google.auth.credentials
package we use underneath already takes care of these, and we can directly use it if necessary. Use this package where needed, and get rid of the private _get_token()
method from App
.
Updating a key with the value null is a valid way to delete data in Node, Java SDK.
However currently you cannot do this in Python as it breaks the validation mechanism. (Dictionary must not contain None keys or values.
)
This is problematic when you are doing multi-path delete as it doesn't work right now in Python.
Is it possible to add a flag to the .update method to make it skip the validation?
update_statement = prepare_multipath_update(args)
db.reference().update(update_statement)
Traceback (most recent call last):
File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "", line 60, in <module>
db.reference().update(update_statement)
File "../lib/python3.5/site-packages/firebase_admin/db.py", line 273, in update
raise ValueError('Dictionary must not contain None keys or values.')
ValueError: Dictionary must not contain None keys or values.
I managed to get over the validation by using the internal methods of db.Reference
db_ref = db.reference()
db_ref._client.request('patch', db_ref._add_suffix(), json=update_statement)
It would be nice if there is a flag that can be provided to the update statement that skips the None validation.
E.g: db.reference().update(update_statement, skip_none_validation=True)
Yes
Verify token fails with an incorrect audience claim error, for token generated with firebase_admin
Traceback (most recent call last):
File "create_token.py", line 28, in <module>
d = auth.verify_id_token(custom_token)
File "/usr/local/lib/python3.6/site-packages/firebase_admin/auth.py", line 98, in verify_id_token
return token_generator.verify_id_token(id_token)
File "/usr/local/lib/python3.6/site-packages/firebase_admin/auth.py", line 272, in verify_id_token
raise ValueError(error_message)
ValueError: Firebase ID token has incorrect "aud" (audience) claim. Expected "[redacted]" but got "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit". Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
#!/usr/bin/env python3
import firebase_admin
from firebase_admin import credentials
from firebase_admin import auth
from os.path import expanduser
import sys
def usage():
'''Print usage'''
print("Usage: create_token.py <UID>")
sys.exit(1)
def init():
cred = credentials.Certificate(expanduser('~/.mq/serviceAccountKey.json'))
return firebase_admin.initialize_app(cred)
if __name__ == "__main__":
if(len(sys.argv) < 2):
usage()
uid = sys.argv[1]
default_app = init()
custom_token = auth.create_custom_token(uid).decode('utf-8')
print(custom_token)
d = auth.verify_id_token(custom_token)
print(d)
Currently this module returns a small number of custom error codes. It would be better to flesh this out a bit more, and reuse the same error codes documented at https://firebase.google.com/docs/auth/admin/errors (at least for the backend server errors).
For example:
def _handle_http_error(self, error):
error_code = 'auth/internal-error'
if error.response is not None:
error_code = _extract_error_code(error)
msg = _lookup_error_msg(error_code)
six.raise_from(ApiCallError(error_code, msg), error)
I use Python 2.7, virtualenv, google app engine standard and firebase-admin.
When I run app on Google app engine dev and production environment, i have met error console "ImportError: No module named firebase_admin". Even firebase-admin be installed.
Console output:
Traceback (most recent call last):
File "/Users/mac/store/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Users/mac/store/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Users/mac/store/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/Users/mac/store/source/gae/main.py", line 3, in <module>
import firebase_admin
ImportError: No module named firebase_admin
Issue only meets with GAE. If i run normally: python main.py, it still works.
Please help me to give suggestion!
Please add support for the shallow option when retrieving data from the realtime db.
def create_custom_token(uid, developer_claims=None, app=None):
"""Builds and signs a Firebase custom auth token.
Args:
uid: ID of the user for whom the token is created.
developer_claims: A dictionary of claims to be included in the token
(optional).
app: An App instance (optional).
Returns:
string: A token minted from the input parameters.
Raises:
ValueError: If input parameters are invalid.
"""
token_generator = _get_auth_service(app).token_generator
return token_generator.create_custom_token(uid, developer_claims)
The docstring says it returns a string, but in python 3, this actually returns a bytes
type. https://github.com/firebase/firebase-admin-python/blob/master/firebase_admin/auth.py#L745 returns bytes from jwt.encode
Right now there does not seem to be an easy solution to the transaction operation if I have a previous value for an ETag, and I want to update the corresponding part of the database only if the ETag is the same (note that set_if_unchanged is not sufficient because this is an update operation). Should we perhaps add an "update_if_unchanged" operation or something else?
I downloaded the default google-services.json file from my project's Firebase console.
Then I have the following error:
ValueError: Invalid service account certificate. Certificate must contain a "type" field set to "service_account".
import firebase_admin
from firebase_admin import db
from firebase_admin import credentials
cred = credentials.Certificate('google-services.json')
firebase_admin.initialize_app(cred)
Operating System version: macOS 10.13.3
Firebase SDK version: firebase_admin 2.9.1
Firebase Product: messaging
Python version: 3.6.2
!('TopicA' in topics)
condition does not work.
https://firebase.google.com/docs/cloud-messaging/ios/topic-messaging#build_send_requests
'TopicA' in topics
worked.
I tried nodejs https://github.com/firebase/firebase-admin-node
. worked.
try:
data = {
"title" : "test",
"body" : "great match"
}
notification = messaging.Notification(title="test", body=None)
condition = "!('TopicA' in topics)"
message = messaging.Message(data=data, notification=notification, condition=condition)
res = messaging.send(message)
print(res)
except Exception as e:
print(e)
print(traceback.print_exc())
Request contains an invalid argument.
Traceback (most recent call last):
File "/Users/x/.anyenv/envs/pyenv/versions/3.6.2/lib/python3.6/site-packages/firebase_admin/messaging.py", line 764, in send
resp = self._client.body('post', url=self._fcm_url, json=data, timeout=self._timeout)
File "/Users/x/.anyenv/envs/pyenv/versions/3.6.2/lib/python3.6/site-packages/firebase_admin/_http_client.py", line 93, in body
resp = self.request(method, url, **kwargs)
File "/Users/x/.anyenv/envs/pyenv/versions/3.6.2/lib/python3.6/site-packages/firebase_admin/_http_client.py", line 85, in request
resp.raise_for_status()
File "/Users/x/.anyenv/envs/pyenv/versions/3.6.2/lib/python3.6/site-packages/requests/models.py", line 935, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://fcm.googleapis.com/v1/projects/dev-leahi-gcp/messages:send
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "firebase.py", line 47, in a
res = messaging.send(message, app=app)
File "/Users/x/.anyenv/envs/pyenv/versions/3.6.2/lib/python3.6/site-packages/firebase_admin/messaging.py", line 54, in send
return _get_messaging_service(app).send(message, dry_run)
File "/Users/x/.anyenv/envs/pyenv/versions/3.6.2/lib/python3.6/site-packages/firebase_admin/messaging.py", line 767, in send
self._handle_fcm_error(error)
File "/Users/x/.anyenv/envs/pyenv/versions/3.6.2/lib/python3.6/site-packages/firebase_admin/messaging.py", line 826, in _handle_fcm_error
raise ApiCallError(code, msg, error)
firebase_admin.messaging.ApiCallError: Request contains an invalid argument.
#54 implements transaction support where the ref.transaction()
method accepts an update_function()
. Following changes are proposed to this API:
update_function()
may signal abort by raising an exception. This is probably how this API works today. Verify and fix if needed.transaction()
method returns the updated value when it commits. If retry attempts are exhausted it should raise an error.dev_appserver.py app.yaml
)Running a trivial DB write results in this error message:
Traceback (most recent call last):
File "/Users/rajvir/Dev/SR-backend/scraper.py", line 289, in firebase_test
'test': 'value'
File "/Users/rajvir/Dev/SR-backend/lib/firebase_admin/db.py", line 152, in set
self._client.request_oneway('put', self._add_suffix(), json=value, params='print=silent')
File "/Users/rajvir/Dev/SR-backend/lib/firebase_admin/db.py", line 603, in request_oneway
self._do_request(method, urlpath, **kwargs)
File "/Users/rajvir/Dev/SR-backend/lib/firebase_admin/db.py", line 631, in _do_request
resp = self._session.request(method, self._url + urlpath, auth=self._auth, **kwargs)
File "/Users/rajvir/Dev/SR-backend/lib/requests/sessions.py", line 488, in request
prep = self.prepare_request(req)
File "/Users/rajvir/Dev/SR-backend/lib/requests/sessions.py", line 431, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/Users/rajvir/Dev/SR-backend/lib/requests/models.py", line 309, in prepare
self.prepare_auth(auth, url)
File "/Users/rajvir/Dev/SR-backend/lib/requests/models.py", line 540, in prepare_auth
r = auth(self)
File "/Users/rajvir/Dev/SR-backend/lib/firebase_admin/db.py", line 674, in __call__
req.headers['Authorization'] = 'Bearer {0}'.format(self._app._get_token())
File "/Users/rajvir/Dev/SR-backend/lib/firebase_admin/__init__.py", line 211, in _get_token
self._token = self._credential.get_access_token()
File "/Users/rajvir/Dev/SR-backend/lib/firebase_admin/credentials.py", line 97, in get_access_token
self._g_credential.refresh(_request)
File "/Users/rajvir/Dev/SR-backend/env/lib/python2.7/site-packages/google/oauth2/service_account.py", line 310, in refresh
request, self._token_uri, assertion)
File "/Users/rajvir/Dev/SR-backend/env/lib/python2.7/site-packages/google/oauth2/_client.py", line 143, in jwt_grant
response_data = _token_endpoint_request(request, token_uri, body)
File "/Users/rajvir/Dev/SR-backend/env/lib/python2.7/site-packages/google/oauth2/_client.py", line 104, in _token_endpoint_request
method='POST', url=token_uri, headers=headers, body=body)
File "/Users/rajvir/Dev/SR-backend/env/lib/python2.7/site-packages/google/auth/transport/requests.py", line 115, in __call__
raise exceptions.TransportError(exc)
TransportError: ('Connection aborted.', error(13, 'Permission denied'))
Running this same code outside of the App Engine environment works normally as expected.
cred = credentials.Certificate('service_account_file.json')
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://APP_ID.firebaseio.com'
})
ref = db.reference()
def firebase_test():
try:
ref.set({
'test': 'value'
})
except:
traceback.print_exc()
Environment
firebase-tools -V
shows 3.18.4Hey all, I would like my server to be able to trigger/send those various email authentication links.
See related: firebase/firebase-admin-node#46
I'm trying to create a user with firebase_admin.auth.create_user(email=email, app=app)
in a dev environment on my local machine. I initialize app
with
app = firebase_admin.initialize_app(options={'projectId': 'DEVPROJECT'})
Output:
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\firebase_admin\_user_mgt.py", line 289, in create_user
response = self._request('post', 'signupNewUser', json=payload)
File "C:\Python36\lib\site-packages\firebase_admin\_user_mgt.py", line 384, in _request
resp.raise_for_status()
File "C:\Python36\lib\site-packages\requests\models.py", line 935, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\firebase_admin\auth.py", line 249, in create_user
uid = user_manager.create_user(**kwargs)
File "C:\Python36\lib\site-packages\firebase_admin\_user_mgt.py", line 291, in create_user
self._handle_http_error(USER_CREATE_ERROR, 'Failed to create new user.', error)
File "C:\Python36\lib\site-packages\firebase_admin\_user_mgt.py", line 348, in _handle_http_error
raise ApiCallError(code, msg, error)
firebase_admin._user_mgt.ApiCallError: Failed to create new user.
Server response: {
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. Google Identity Toolkit API has not been used in project 764086051850 before or it is disabled. Enable it by visiting https://conso
le.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=764086051850 then retry. If you enabled this API recently, wait a few minutes for the ac
tion to propagate to our systems and retry.",
"extendedHelp": "https://console.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=764086051850"
}
],
"code": 403,
"message": "Access Not Configured. Google Identity Toolkit API has not been used in project 764086051850 before or it is disabled. Enable it by visiting https://console
.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=764086051850 then retry. If you enabled this API recently, wait a few minutes for the acti
on to propagate to our systems and retry."
}
}
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Scott\workspace\onechart-gae\app\tests\dev\patients_test.py", line 12, in setUpClass
super(PatientTests, cls).setUpClass()
File "C:\Users\Scott\workspace\onechart-gae\app\tests\dev\__init__.py", line 20, in setUpClass
cls.u1 = db.Users.get_or_create('[email protected]')
File "C:\Users\Scott\workspace\onechart-gae\app\db\users.py", line 44, in get_or_create
u = firebase.get_or_create_user(email, create_password)
File "C:\Users\Scott\workspace\onechart-gae\app\firebase.py", line 45, in get_or_create_user
return firebase_admin.auth.create_user(email=email, app=app)
File "C:\Python36\lib\site-packages\firebase_admin\auth.py", line 252, in create_user
raise AuthError(error.code, str(error), error.detail)
firebase_admin.auth.AuthError: Failed to create new user.
Server response: {
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. Google Identity Toolkit API has not been used in project 764086051850 before or it is disabled. Enable it by visiting https://conso
le.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=764086051850 then retry. If you enabled this API recently, wait a few minutes for the ac
tion to propagate to our systems and retry.",
"extendedHelp": "https://console.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=764086051850"
}
],
"code": 403,
"message": "Access Not Configured. Google Identity Toolkit API has not been used in project 764086051850 before or it is disabled. Enable it by visiting https://console
.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=764086051850 then retry. If you enabled this API recently, wait a few minutes for the acti
on to propagate to our systems and retry."
}
}
# First, init your application default creds with `gcloud auth application-default login`
import firebase_admin
import firebase_admin.auth
PROJECTID = 'YOURPROJECT'
def main():
app = firebase_admin.initialize_app(options={'projectId': PROJECTID})
u = firebase_admin.auth.create_user(email='[email protected]', app=app)
print(u)
if __name__ == '__main__':
main()
There are at least some Python >= 3 invalid syntax used in this project (see print statements added in #130).
This suggests there is currently no such validation in place or the snippets are not validated to be compatible with Python >= 3.
Need an feature to send notification for specified channel_id.
For example:
message = messaging.Message(
android=messaging.AndroidConfig(
ttl=datetime.timedelta(seconds=3600*6),
priority="high",
notification=messaging.AndroidNotification(
title="SUPER TITLE",
body="COLORED MESSAGE"
),
channel_id="timetable"
),
topic="timetable"
)
Lack of support for Realtime Database API now in firebase-admin.
Would be great if the auth API provided:
in the current version I don't find the examples to auth with providers(Google, Facebook, GitHub, etc..). Can create a examples/ in this repo with authentication examples? I can contribute with this ?
My plan is create some examples using firebase-admin library to Python+Flask API. Today don't have these examples with Firebase.
URL:
https://us-central1-ossbot-f0cad.cloudfunctions.net/githubWebhook
Content type:
application/json
Secret:
N/A
Select individual events:
{
"jobs": {
"count": 0
}
}
root.child('jobs/count').transaction(lambda x: x + 1 if x else 1)
Raised error: ValueError: Value argument must be a non-empty dictionary.
firebase-admin-python/firebase_admin/db.py
Lines 204 to 207 in 99c48ef
We currently check if project_id is a string in each of the service modules. This can be done in one place -- namely when the project_id is first read in the App.__init__()
method.
Hi, I was wondering if/when this API will support writing files to storage, and transaction support. Either of these things would be very useful for the work I am doing. Thanks.
Integration tests for DB updates rules for a specific child node in the database (_adminsdk). But if there are any top-level rules already defined in the environment they are going to take precedence over what the test suite sets, which may cause tests to fail.
To fix this, the test suite should overwrite the entire rules configuration at test set up (not just the child rules).
This function no longer raises AppIdentityErrors (not since the library was migrated to google-auth package #19). We now raise ValueError
for all error conditions. Update the Reference docs to reflect this change.
@hiranya911 do you have any plan to add realtime update listener ? I have django api service.I want to change my current authentication and authorization system to firebase authentication.Realtime data update listener is not available so I have to call firebase server for authorization every time.It will make my api slower.What to do now for django in this situation?
I'm using firebase-admin v2.3.0 in a Google AppEngine app (Standard Environment, Python 2.7).
Unfortunately I'm getting a DeadlineExceededError once in a while when accessing my Firebase DB.
On Appengine the request timeout is 5 seconds, but it is possible to increase it up to 60 seconds, as described here:
https://cloud.google.com/appengine/articles/deadlineexceedederrors
I already tried to follow the official solution proposed by Google for Requests, but it doesn't seem to work:
https://cloud.google.com/appengine/docs/standard/python/issue-requests
I've seen that the google-auth library provides a timeout option in her Requests transport:
https://google-auth.readthedocs.io/en/latest/reference/google.auth.transport.requests.html#module-google.auth.transport.requests
It would be great to have a "timeout" option on Firebase App initialization, in order to avoid the DeadlineExceededError on AppEngine.
have a nice day!
Mauro
Integration test suite uses some Python 2.x specific syntax. This needs to be corrected so that it can run on Python 3.x
I'm trying to install firebase-admin-python from github URL (I actually want to install my fork), but the setup.py file imports project before dependencies instalations, and this causes an import error.
$ pip install -e git+https://github.com/firebase/firebase-admin-python.git#egg=firebase-admin-python
Obtaining firebase-admin-python from git+https://github.com/firebase/firebase-admin-python.git#egg=firebase-admin-python
Updating /tmp/.venv/src/firebase-admin-python clone
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/.venv/src/firebase-admin-python/setup.py", line 24, in <module>
import firebase_admin
File "/tmp/.venv/src/firebase-admin-python/firebase_admin/__init__.py", line 20, in <module>
import six
ImportError: No module named 'six'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/.venv/src/firebase-admin-python/
On my local I removed the import firebase_admin
(link) and replaces __version__
value with the version string. It works.
I'm not sure how this can work in pypi but not in local.
I installed GAE standard (python), firebase-admin.
When use function of firebase-admin, it doesn't work.
Console output:
logMessage: "TransportError: ('Connection broken: IncompleteRead(38 bytes read)', IncompleteRead(38 bytes read))"
app.yaml
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.app
libraries:
- name: flask
version: 0.12
- name: ssl
version: latest
env_variables:
GAE_USE_SOCKETS_HTTPLIB: 'true'
appengine_config.py
from google.appengine.ext import vendor
# Add any libraries install in the "lib" folder.
vendor.add('lib')
Code
import firebase_admin
from firebase_admin import credentials, auth
cred = credentials.Certificate("key/asgsagahaha.json")
default_app = firebase_admin.initialize_app(cred)
class Test():
def __init__(self):
pass
def create_user(self):
usr = auth.create_user() // Error at here
print usr.uid
With this SDK we are able to interact with the Realtime Database, but not with the Firestore.
Is the Firestore something that is on the roadmap for this SDK?
I try
message = messaging.Message( notification = messaging.Notification( title='my app', body='my message', sound='default' ), data=data, topic='all', )
it has an exception got an unexpected keyword argument 'sound'
how to add sound to notification?
I am using firebase-admin
on an asyncio
project and when there are a lot of requests it slows down the whole API.
Surprisingly, I didn't see any other issues about this, I hope I am not duplicating.
ref = yield from db.reference
result = yield from ref.get()
Thanks
As discussed in #54, I think it would be a good idea of exposing API functions that can explicitly access the value of the ETag of the firebase db.
We could have the following API for the Reference class:
get(self, etag=False) # When etag is True, behaves like _get_with_etag()
set(self, value, etag=None) # When etag is not None, behaves like _update_with_etag()
get_etag(self) # Retrieves the etag without the corresponding data
check_etag(self, etag) # Returns a boolean indicating whether or not the etag is correct
These API functions could come in handy for low level operations that the user may want to perform that the proposed transaction functionality may not be able to handle. An example would be if the user keeps a cache of some of the firebase data, the user will likely want to keep track of the ETag for each part of the database, so he can check whether the data in some part of the cache is up to date.
Does a quite old version of Requests library matter?
The problem is described here
user = firebase_decode_handler(key)
File "/home/gis/development/python/apps/gee-bridge/rest_auth_firebase/firebase_sdkadm.py", line 15, in firebase_decode_handler
decoded_token = auth.verify_id_token(id_token, check_revoked=True)
File "/home/gis/.local/share/virtualenvs/gee-bridge-u7zdh93C/lib/python2.7/site-packages/firebase_admin/auth.py", line 104, in verify_id_token
verified_claims = token_generator.verify_id_token(id_token)
File "/home/gis/.local/share/virtualenvs/gee-bridge-u7zdh93C/lib/python2.7/site-packages/firebase_admin/auth.py", line 838, in verify_id_token
audience=project_id)
File "/home/gis/.local/share/virtualenvs/gee-bridge-u7zdh93C/lib/python2.7/site-packages/google/oauth2/id_token.py", line 159, in verify_firebase_token
id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL)
File "/home/gis/.local/share/virtualenvs/gee-bridge-u7zdh93C/lib/python2.7/site-packages/google/oauth2/id_token.py", line 120, in verify_token
certs = _fetch_certs(request, certs_url)
File "/home/gis/.local/share/virtualenvs/gee-bridge-u7zdh93C/lib/python2.7/site-packages/google/oauth2/id_token.py", line 94, in _fetch_certs
response = request(certs_url, method='GET')
File "/home/gis/.local/share/virtualenvs/gee-bridge-u7zdh93C/lib/python2.7/site-packages/google/auth/transport/requests.py", line 124, in __call__
six.raise_from(new_exc, caught_exc)
File "/home/gis/.local/share/virtualenvs/gee-bridge-u7zdh93C/lib/python2.7/site-packages/six.py", line 737, in raise_from
raise value
TransportError: HTTPSConnectionPool(host='www.googleapis.com', port=443): Max retries exceeded with url: /robot/v1/metadata/x509/[email protected] (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fd35de70650>: Failed to establish a new connection: [Errno 11] Resource temporarily unavailable',))
def firebase_decode_handler(id_token):
decoded_token = auth.verify_id_token(id_token, check_revoked=True)
uid = decoded_token['uid']
logger.debug("User={0}".format(uid))
return uid
For the record, this is a traceback from using firebase_adm pyhon sdk on appengine standard with 3rd party libraries google-oauth, and custom oauth2client, amongst others:
Environment:
Request Method: GET
Request URL: <redacted>
Django Version: 1.11.3
Python Version: 2.7.12
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
[...])
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'corsheaders.middleware.CorsMiddleware',
'house.middleware.OAuth2TokenMiddleware')
Traceback:
[...]
File "/base/data/home/apps/[...]/models.py" in user_created_callback
82. uid = create_firebase_user_from_google_signin(google_user)
File "/base/data/home/apps/s~[...]/models.py" in create_firebase_user_from_google_signin
53. disabled=False)
File "/base/data/home/apps/[...]/v1.404130886528581043/lib/firebase_admin/auth.py" in create_user
194. uid = user_manager.create_user(**kwargs)
File "/base/data/home/apps/[...]/v1.404130886528581043/lib/firebase_admin/_user_mgt.py" in create_user
215. response = self._request('post', 'signupNewUser', json=payload)
File "/base/data/home/apps/s~[...]/v1.404130886528581043/lib/firebase_admin/_user_mgt.py" in _request
306. resp = self._session.request(method, ID_TOOLKIT_URL + urlpath, **kwargs)
File "/base/data/home/apps/[...]/v1.404130886528581043/lib/google/auth/transport/requests.py" in request
176. self._auth_request, method, url, request_headers)
File "/base/data/home/apps/[...]/v1.404130886528581043/lib/google/auth/credentials.py" in before_request
121. self.refresh(request)
File "/base/data/home/apps/[...]/v1.404130886528581043/lib/google/oauth2/service_account.py" in refresh
322. request, self._token_uri, assertion)
File "/base/data/home/apps/[...]/v1.404130886528581043/lib/google/oauth2/_client.py" in jwt_grant
143. response_data = _token_endpoint_request(request, token_uri, body)
File "/base/data/home/apps/s[...]/v1.404130886528581043/lib/google/oauth2/_client.py" in _token_endpoint_request
104. method='POST', url=token_uri, headers=headers, body=body)
File "/base/data/home/apps/[...]/v1.404130886528581043/lib/google/auth/transport/requests.py" in __call__
115. raise exceptions.TransportError(exc)
Exception Type: TransportError at /oauth2/oauth2callback/
Exception Value: ('Connection broken: IncompleteRead(93 bytes read)', IncompleteRead(93 bytes read))
This issue is quickly resolved by following the google-oauth app engine standard-specific installation instructions, notably the addition of the environment variable GAE_USE_SOCKETS_HTTPLIB
in app.yaml as follows:
GAE_USE_SOCKETS_HTTPLIB: 'true'
as per https://google-auth.readthedocs.io/en/latest/user-guide.html#the-app-engine-standard-environment.
Since this library is a dependency of firebase-admin-python, would it be appropriate to add a note as to this required configuration in README.md? The reason I am asking is because the traceback is not very descriptive as to what might be causing this and it is currently hard to find the information necessary to make this work.
@salqadri now that I read the library is tested on app engine it makes me think this could be due to something specific to my environment--where can we see how the library is tested on app engine (README.md), if not is this a known quirk?
Describe your environment
Hi,
I have been looking to manage the firebase database from my on backend. My backend is in google app engine, and is running on python 2.7 with Flask.
Till now I am able to generate a JWT and retrieve it to my app successfully. My next step is to try to push somenthing to the db. For that i am just using your code example in this article:
https://firebase.googleblog.com/2017/07/accessing-database-from-python-admin-sdk.html
but when it reaches the line:
new_user = root.child('users').push({
'name' : 'Mary Anning',
'since' : 1700
})
it breakes.
Am I doing anything wrong?
pd: Is there any code example in which i can see the correct way of handling errors using the ApiCallError?
Regards,
Guillermo Barrena
Rules:
// These rules require authentication
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
# This is pointing to the correct place in my aplication
cred = credentials.Cert('path/to/serviceKey.json')
# I have the correct URL in my aplication
firebase_admin.initialize_app(cred, {
'databaseURL' : 'https://my-db.firebaseio.com'
})
root = db.reference()
# Add a new user under /users.
new_user = root.child('users').push({
'name' : 'Mary Anning',
'since' : 1700
})
If you don't already have python six installed, you can't install firebase
pip install .
setup.py has: import firebase_admin
and firebase_admin.__init__.py
has import six
so if it isn't installed before installing the installation fails with:
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/rh/fs2krkgj1hz_2ftgxgl20d980000gn/T/pip-mpnc1wob-build/setup.py", line 24, in <module>
import firebase_admin
File "/private/var/folders/rh/fs2krkgj1hz_2ftgxgl20d980000gn/T/pip-mpnc1wob-build/firebase_admin/__init__.py", line 21, in <module>
import six
ModuleNotFoundError: No module named 'six'
Add a source map to the doc generation process so that reference docs can link directly into source files for each function/constant/etc.
When using the SDK within an App Engine environment, the docs require you do some extra configuration. Within that configuration you have to add the following variables to your app.yaml
libraries:
- name: ssl
version: latest
env_variables:
GAE_USE_SOCKETS_HTTPLIB: 'true'
However, this introduces an error within app engine that breaks any requests that have to do with the google api python client library. Through some research I found this question that explains my issue.
Is there a workaround that permits the use GAE_USE_SOCKETS_HTTPLIB in order for firebase to function properly as well as being able to use google api client library within app engine such as:
from apiclient.discovery import build
service = build('calendar', 'v3')
# etc...
I am fairly new to python, I apologize if this questions seems out of place.
Thank you in advance for you feedback.
What is the correct way to handle this error? I've created two stack questions and both answers no longer work. Here is my code:
from firebase_admin import auth as admin_auth
try:
uid = 'testUID'
email = '[email protected]' # [email protected] already exists
admin_auth.update_user(uid, email=email)
except Exception as e:
print(e)
I get the following response:
Failed to update user: testUID. Server response: { "error": { "errors": [ { "domain": "global", "reason": "invalid", "message": "EMAIL_EXISTS" } ], "code": 400, "message": "EMAIL_EXISTS" } }
Am I creating the exception correctly? If I use:
except ValueError as e:
I get the response in a string. What I want is to get the status and message.
Add an optional max_retries
argument to the db.Reference.transaction()
method. Currently it uses a fixed retry count (25).
check_revoked
needs to be code formatted in a couple of places in the auth doc strings:
https://github.com/firebase/firebase-admin-python/blob/master/firebase_admin/auth.py#L93
https://github.com/firebase/firebase-admin-python/blob/master/firebase_admin/auth.py#L146
In firebase-admin-python/firebase_admin/db.py , it's unable to use equal_to(), start_at(), and end_at() with a boolean False value. It throws ValueError: Equal to value must not be empty or None.
Suggest the condition of False boolean value to be catered.
@hiranya911 I just realized that the collections I'm working on firestore-watch for python was copied from firestore-admin-java. I'm working on the python versions now, but just in case there is similar python code that I'm not aware of from here.
Otherwise maybe I'll make a PR here when I'm done with them.
Thanks.
Firebase Product: auth
Payload may contain padding(=) when creating custom token.
Padding was not included in the node version even if the token was created using the same key.
It was possible to decode tokens containing padding created in python version with node version.
However, Json web token, which is one of the node's decoders, produces an error.
(https://github.com/auth0/node-jsonwebtoken)
Because it is defined as follows.
var JWS_REGEX = /^[a-zA-Z0-9-]+?.[a-zA-Z0-9-]+?.([a-zA-Z0-9-_]+)?$/;
(https://github.com/brianloveswords/node-jws/blob/master/lib/verify-stream.js)
Will this problem be fixed?
Should I look for another decoder?
This sentence translated Japanese into English using Google Translate.
initialize_app has an options= argument, and I found this documented for Java here, but cannot get it working in Python.
This is what I have tried for the DataBaseAuthVariableOverride option:
current_app.firebase_app = initialize_app(cred, options={'DatabaseAuthVariableOverride': {'uid': 'my-uid'}})
Python 3 incompatible code was introduced in #130 and is causing test execution to fail in this environment:
$ python setup.py test
running test
running egg_info
writing firebase_admin.egg-info/PKG-INFO
writing dependency_links to firebase_admin.egg-info/dependency_links.txt
writing requirements to firebase_admin.egg-info/requires.txt
writing top-level names to firebase_admin.egg-info/top_level.txt
reading manifest file 'firebase_admin.egg-info/SOURCES.txt'
writing manifest file 'firebase_admin.egg-info/SOURCES.txt'
running build_ext
Traceback (most recent call last):
File "setup.py", line 73, in <module>
'License :: OSI Approved :: Apache Software License',
File "/home/user/.local/share/virtualenvs/utils-iX9zXjhl/lib/python3.7/site-packages/setuptools/__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "/usr/local/lib/python3.7/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/local/lib/python3.7/distutils/dist.py", line 966, in run_commands
self.run_command(cmd)
File "/usr/local/lib/python3.7/distutils/dist.py", line 985, in run_command
cmd_obj.run()
File "/home/user/.local/share/virtualenvs/utils-iX9zXjhl/lib/python3.7/site-packages/setuptools/command/test.py", line 226, in run
self.run_tests()
File "/home/user/.local/share/virtualenvs/utils-iX9zXjhl/lib/python3.7/site-packages/setuptools/command/test.py", line 248, in run_tests
exit=False,
File "/usr/local/lib/python3.7/unittest/main.py", line 100, in __init__
self.parseArgs(argv)
File "/usr/local/lib/python3.7/unittest/main.py", line 124, in parseArgs
self._do_discovery(argv[2:])
File "/usr/local/lib/python3.7/unittest/main.py", line 244, in _do_discovery
self.createTests(from_discovery=True, Loader=Loader)
File "/usr/local/lib/python3.7/unittest/main.py", line 154, in createTests
self.test = loader.discover(self.start, self.pattern, self.top)
File "/usr/local/lib/python3.7/unittest/loader.py", line 347, in discover
tests = list(self._find_tests(start_dir, pattern))
File "/usr/local/lib/python3.7/unittest/loader.py", line 404, in _find_tests
full_path, pattern, namespace)
File "/usr/local/lib/python3.7/unittest/loader.py", line 481, in _find_test_path
tests = self.loadTestsFromModule(package, pattern=pattern)
File "/home/user/.local/share/virtualenvs/utils-iX9zXjhl/lib/python3.7/site-packages/setuptools/command/test.py", line 52, in loadTestsFromModule
tests.append(self.loadTestsFromName(submodule))
File "/usr/local/lib/python3.7/unittest/loader.py", line 191, in loadTestsFromName
return self.loadTestsFromModule(obj)
File "/home/user/.local/share/virtualenvs/utils-iX9zXjhl/lib/python3.7/site-packages/setuptools/command/test.py", line 52, in loadTestsFromModule
tests.append(self.loadTestsFromName(submodule))
File "/usr/local/lib/python3.7/unittest/loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "/home/user/firebase-admin-python/snippets/database/index.py", line 35
print ref.get()
^
SyntaxError: invalid syntaex
This is a namedtuple
type, and hence requires a bit of work to document it properly. Namely it has to be wrapped in a simple class, where the docstring can be provided.
I just try to install the python package and it give me an error.
1- pip install firebase-admin
What happened? How can we make the problem occur?
This could be a description, log/console output, etc.
Collecting google-cloud-core<0.28dev,>=0.27.0 (from google-cloud-storage>=1.2.0->firebase-admin)
Using cached google_cloud_core-0.27.1-py2.py3-none-any.whl
Collecting googleapis-common-protos>=1.3.4 (from google-cloud-core<0.28dev,>=0.27.0->google-cloud-storage>=1.2.0->firebase-admin)
Using cached googleapis-common-protos-1.5.3.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\setuptools\__init__.py", line 10, in <module>
from setuptools.extern.six.moves import filter, filterfalse, map
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\setuptools\extern\__init__.py", line 1, in <module>
from pkg_resources.extern import VendorImporter
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 3017, in <module>
@_call_aside
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 3003, in _call_aside
f(*args, **kwargs)
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 3045, in _initialize_master_working_set
dist.activate(replace=False)
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2577, in activate
declare_namespace(pkg)
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2151, in declare_namespace
_handle_ns(packageName, path_item)
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2091, in _handle_ns
_rebuild_mod_path(path, packageName, module)
File "c:\users\clust\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources\__init__.py", line 2120, in _rebuild_mod_path
orig_path.sort(key=position_in_sys_path)
AttributeError: '_NamespacePath' object has no attribute 'sort'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\clust\AppData\Local\Temp\pip-build-2qs9dsol\googleapis-common-protos\
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.