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模塊。 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)