【问题标题】:I can`t authorize with gspread on Python 3我无法在 Python 3 上使用 gspread 进行授权
【发布时间】:2018-09-03 11:39:03
【问题描述】:

我有一个在 Python 3.6 上创建 googlesheet 的简单脚本,例如:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

mail = 'my_mail@gmail.com'
secret_file = "C:\\Users\\admin\\Downloads\\my_file.json"

SCOPES = ['https://spreadsheets.google.com/feeds']

credentials = ServiceAccountCredentials.from_json_keyfile_name(secret_file, SCOPES)

gss_client = gspread.authorize(credentials)
gss = gss_client.open('test-doc')
worksheet = gss.sheet1

但是当我运行它时,我有一个类型错误:

Traceback(最近一次调用最后一次):文件 “C:/Users/admin/PycharmProjects/untitled/fjhdshfjs.py”,第 11 行,在 ... "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\base64.py", 第 58 行,在 b64 编码中 encoded = binascii.b2a_base64(s, newline=False) TypeError: a bytes-like object is required, not 'str'

早期,这个问题可以通过编码解决:

credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)

但是现在,将 SignedJwtAssertionCredentials 移动到 oauth2client.service_account.ServiceAccountCredentials 上后它不起作用

也许有人可以帮助我?

【问题讨论】:

  • 您可以直接在gspread.authorize("credentials.json")使用从Google下载的凭证文件

标签: python google-api google-sheets-api google-api-python-client service-accounts


【解决方案1】:

我认为你所追求的代码更接近这个

from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('sheets', 'v4', http=creds.authorize(Http()))

# Call the Sheets API
SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
RANGE_NAME = 'Class Data!A2:E'
result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
                                            range=RANGE_NAME).execute()
values = result.get('values', [])

Using OAuth 2.0 for Server to Server Applications

【讨论】:

  • 我再次编写了代码:credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) service = apiclient.discovery.build('sheets', 'v4', credentials=credentials) 但是它仍然无法解决相同的错误。哪里错了?
  • 听起来您的凭据文件有问题您是否尝试按照文档链接进行操作?
  • 是的,我创建了服务帐户并以 JSON 格式获取凭据文件。它看起来像这样: { "type": "service_acc", "project_id": docs", "private_key_id": sdadasd221312312 "private_key": "-----BEGIN -END PRIVATE KEY", "client_email": "sdsdsdsds@ .iam.gserviceaccount.com", "client_id": 1223213213211 "auth_uri": "accounts.google.com/o/oauth2/auth", "token_uri": "oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "@98764 @" }
猜你喜欢
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 2012-02-25
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多