pygsheets能否从字典而非文件加载凭证?云函数场景需求
Great question—this is such a common need for serverless environments like Cloud Functions where uploading credential files isn't ideal. The error you're hitting comes down to one key detail: pygsheets.authorize()'s custom_credentials parameter expects an instantiated OAuth2 credentials object, not a raw dictionary.
Unlike gspread which has a built-in method to handle dictionaries directly, pygsheets requires you to first convert your credential dict into a proper Google Credentials instance. Here's how to make it work:
Step-by-Step Solution
- First, fix the tiny syntax error in your
secretdict (you missed a comma afterprivate_key—easy typo!). - Import the Google auth class that lets you convert a dict into a valid credentials object.
- Define the scopes pygsheets needs (these match the default scopes it uses when loading from a service file).
- Initialize the credentials from your dict, then pass that to
pygsheets.authorize().
Full Working Code
import pygsheets from google.oauth2.service_account import Credentials # Your corrected service account credential dictionary secret = { "type": "service_account", "project_id": "XXXXXXXXXX", "private_key_id": "XXXXXXXXXX", "private_key": "XXXXXXXXXX", "client_email": "XXXXXXXXXX", "client_id": "XXXXXXXXXX", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "XXXXXXXXXX" } # Required scopes for pygsheets (matches default behavior) PYGSHEETS_SCOPES = [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive" ] # Convert the dictionary to a valid Credentials object service_account_creds = Credentials.from_service_account_info( secret, scopes=PYGSHEETS_SCOPES ) # Authorize pygsheets with the instantiated credentials gc = pygsheets.authorize(custom_credentials=service_account_creds)
Why Your Original Code Failed
The AttributeError: 'dict' object has no attribute 'before_request' occurs because custom_credentials is designed to accept a credentials instance that implements OAuth2-specific methods like before_request. A raw dictionary doesn't have these methods, hence the error.
Bonus Tip for Cloud Functions
In a Cloud Function, avoid hardcoding your credential dict. Instead, store it as an encrypted environment variable, then parse it into a dict at runtime:
import os import json # Pull and parse the credential dict from an environment variable secret = json.loads(os.environ.get("GOOGLE_SERVICE_ACCOUNT_CREDS"))
内容的提问来源于stack exchange,提问作者PythonSherpa

