我无法在Python 3上使用gspread进行授权

问题描述 投票:0回答:1

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

import gspread
from oauth2client.service_account import ServiceAccountCredentials

mail = '[email protected]'
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

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

回溯(最近一次调用最后一次):文件“C:/Users/admin/PycharmProjects/untitled/fjhdshfjs.py”,第11行,在...“C:\ Users \ admin \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ base64.py“,第58行,在b64encode encoded = binascii.b2a_base64(s,newline = False)TypeError:类似字节的对象是必需的,而不是'str'

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

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

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

也许有人可以帮助我?

python google-api google-sheets-api google-api-python-client service-accounts
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.