Check out what’s new from Firebase at Google I/O 2022. Learn more

Python 3.0.0 的 Admin SDK 迁移指南

适用于 Python 的 Firebase Admin SDK 3.0.0 版在 API 中引入了一些重要更改。此版本中的 API 更改主要是对 Auth、FCM 和其他 Firebase 功能的错误处理进行了添加和改进。

一般错误处理更改

已删除以下异常类型:

  • auth.AuthError
  • db.ApiCallError
  • instance_id.ApiCallError
  • messaging.ApiCallError
  • project_management.ApiCallError

相反,引入了一个新的firebase_admin.exceptions模块。 authdbinstance_idmessagingproject_management模块中的公共 API 现在会引发exceptions.FirebaseError类型的实例。

# Before
from firebase_admin import messaging

try:
    messaging.send(build_message())
except messaging.ApiCallError as ex:
    print('Error message:', ex)

# v3
from firebase_admin import exceptions
from firebase_admin import messaging

try:
    messaging.send(build_message())
except exceptions.FirebaseError as ex:
    print('Error message:', ex)
    print('Error code:', ex.code) # Platform-wide error code
    print('HTTP response:', ex.http_response) # requests HTTP response object

exceptions.FirebaseError类型有许多子类型。 Admin SDK 中的公共 API 只能引发这些子类型。因此,您可以编写捕获特定子类型并更精细地处理错误的代码。例如:

try:
    messaging.send(build_message())
except exceptions.InvalidArgumentError as ex:
    print(ex) # One or more arguments were invalid
except exceptions.UnavailableError as ex:
    print(ex) # FCM service is temporarily down
except exceptions.FirebaseError as ex:
    print(ex) # All other errors

除了捕获特定的错误类型,还可以捕获父FirebaseError类型并比较错误代码。

try:
    messaging.send(build_message())
except exceptions.FirebaseError as ex:
    if ex.code == exceptions.INVALID_ARGUMENT:
        print(ex) # One or more arguments were invalid
    elif ex.code == exceptions.UNAVAILABLE:
        print(ex) # FCM service is temporarily down
    else:
        print(ex) # All other errors

每个模块都可以声明从exceptions.FirebaseError父类型扩展的其他子类型(见下文)。

错误处理的一般准则:当您不需要区分错误条件时捕获exceptions.FirebaseError 。当您需要区分错误情况时,请查找更具体的错误子类或错误代码。

身份验证错误处理更改

智威汤逊验证

auth.verify_id_token()方法不再引发ValueError来指示令牌验证错误。相反,您将获得以下错误类型之一:

  • InvalidIdTokenError
  • ExpiredIdTokenError
  • RevokedIdTokenError

InvalidIdTokenError类型扩展了exceptions.InvalidArgumentError类型,而后者又扩展了exceptions.FirebaseError类型。 ExpiredIdTokenErrorRevokedIdTokenError扩展InvalidIdTokenError

# Before
from firebase_admin import auth

try:
    auth.verify_id_token(id_token, check_revoked=True)
except ValueError as ex:
    print('Error message:', ex)

 # v3
from firebase_admin import auth

# Coarse-grained error handling
try:
    auth.verify_id_token(id_token, check_revoked=True)
except auth.InvalidIdTokenError as ex:
    print('ID token is invalid, expired or revoked')

# Fine-grained error handling
try:
    auth.verify_id_token(id_token, check_revoked=True)
except auth.RevokedIdTokenError as ex:
    print('ID token has been revoked')
except auth.ExpiredIdTokenError as ex:
    print('ID token is expired')
except auth.InvalidIdTokenError as ex:
    print('ID token is invalid')

同样, auth.verify_session_cookie()方法引发以下异常类型:

  • InvalidSessionCookieError
  • ExpiredSessionCookieError
  • RevokedSessionCookieError

类层次结构和语义类似于verify_id_token() API。

自定义令牌

create_custom_token() API 引发auth.TokenSignError而不是ValueError来指示失败。

# Before
from firebase_admin import auth

try:
    auth.create_custom_token(uid)
except ValueError as ex:
    print('Error message:', ex)

 # v3
from firebase_admin import auth

try:
    auth.create_custom_token(uid)
except auth.TokenSignError as ex:
    print('Error message:', ex)

用户管理

auth模块中引入了以下新的错误类型:

  • EmailAlreadyExistsError
  • InvalidDynamicLinkDomainError
  • PhoneNumberAlreadyExistsError
  • UidAlreadyExistsError
  • UnexpectedResponseError
  • UserNotFoundError
# Before
from firebase_admin import auth

try:
    auth.get_user(uid)
except auth.AuthError as ex:
    if ex.code == auth.USER_NOT_FOUND_ERROR:
        print('Specified user does not exist')
    else:
        print('Something else went wrong')

 # v3
from firebase_admin import auth
from firebase_admin import exceptions

try:
    auth.get_user(uid)
except auth.UserNotFoundError as ex:
    print('Specified user does not exist')
except exceptions.FirebaseError as ex:
    print('Something else went wrong')

FCM 错误处理更改

messaging模块中引入了以下新错误类型。

  • QuotaExceededError
  • SenderIdMismatchError
  • ThirdPartyAuthError
  • UnregisteredError
# Before
from firebase_admin import messaging

try:
    messaging.send(msg)
except messaging.ApiCallError as ex:
    if ex.code == 'registration-token-not-registered':
        print('Registration token has been unregistered')
    elif ex.code == 'invalid-argument':
        print('One or more arguments invalid')
    else:
        print('Something else went wrong')

# v3
from firebase_admin import exceptions
from firebase_admin import messaging

try:
    messaging.send(msg)
except messaging.UnregisteredError as ex:
    print('Registration token has been unregistered')
except exceptions.InvalidArgumentError as ex:
    print('One or more arguments invalid')
except exceptions.FirebaseError as ex:
    print('Something else went wrong')

用户属性删除

不再可以通过将属性display_namephoto_urlphone_numbercustom_claims设置为None来删除它们。将这些设置为None会使这些属性保持不变。必须将它们显式设置为auth.DELETE_ATTRIBUTE才能删除它们。

# Before
from firebase_admin import auth

auth.update_user(uid, display_name=None, photo_url=None)

 # v3
from firebase_admin import auth

auth.update_user(
  uid, display_name=auth.DELETE_ATTRIBUTE, photo_url=auth.DELETE_ATTRIBUTE)