Jon Bresler
Jon Bresler

Reputation: 21

gspread gives TypeError: expected bytes when trying to log in

I'm trying to use Google Spreadsheets OAuth with the gspread library. I get a TypeError: expected bytes, not str exception when sending credentials. How do I fix this?

import gspread
import json
from oauth2client.client import SignedJwtAssertionCredentials

json_key = json.load(open('Test for gspread-78c678a7fb15.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
  File "C:\Python33\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Python33\lib\site-packages\oauth2client\client.py", line 1515, in __init__
    self.private_key = base64.b64encode(private_key)
  File "C:\Python33\lib\base64.py", line 58, in b64encode
    raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str

Upvotes: 1

Views: 439

Answers (1)

Jon Bresler
Jon Bresler

Reputation: 21

The key is a string and needs to be encoded to bytes. Replace credentials = with the following:

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

Upvotes: 1

Related Questions