0
votes

I have a simple script with creating googlesheet on Python 3.6 like:

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

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'

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

Maybe somebody can help me?

1
you can use the credential file you download from Google directly in gspread.authorize("credentials.json")fcsr

1 Answers

1
votes

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