Join us for Firebase Summit on November 10, 2021. Tune in to learn how Firebase can help you accelerate app development, release with confidence, and scale with ease. Register

Admin SDK for Python 3.0.0 迁移指南

适用于 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模块已经出台。在公共API authdbinstance_idmessagingproject_management模块现在提高的情况下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)