简体   繁体   English

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

[英]I can`t authorize with gspread on Python 3

I have a simple script with creating googlesheet on Python 3.6 like: 我有一个简单的脚本,可以在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

But when I run it, I have a type-error: 但是当我运行它时,出现类型错误:

Traceback (most recent call last): File "C:/Users/admin/PycharmProjects/untitled/fjhdshfjs.py", line 11, in ... "C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\lib\\base64.py", line 58, in b64encode encoded = binascii.b2a_base64(s, newline=False) TypeError: a bytes-like object is required, not 'str' 追溯(最近一次通话):文件“ C:/Users/admin/PycharmProjects/untitled/fjhdshfjs.py”,行11,在...“ C:\\ Users \\ admin \\ AppData \\ Local \\ Programs \\ Python \\ Python36 \\ lib \\ base64.py“,第58行,在b64encode中编码为= binascii.b2a_base64(s,newline = False)TypeError:需要类似字节的对象,而不是'str'

Early, this trouble could be resolved with encoding: 早期,可以通过编码解决此问题:

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

But now, it doesn`t work after moving SignedJwtAssertionCredentials onto oauth2client.service_account.ServiceAccountCredentials 但是现在,在将SignedJwtAssertionCredentials移到oauth2client.service_account.ServiceAccountCredentials之后,它不起作用

Maybe somebody can help me? 也许有人可以帮我吗?

I think the code you are after is closer to this 我认为您所追求的代码更接近于此

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 将OAuth 2.0用于服务器到服务器应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM