Google 致力于为黑人社区推动种族平等。查看具体举措

Python 版 Admin SDK 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 模块。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 错误处理更改

JWT 验证

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)