简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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