关于 Gspread

Gspread & Oauth2 on Python 3.4 - Oauth does not support indexing

我想使用 gspread,由于客户端身份验证已过时,我正在尝试使用 Oauth2。我都是 gspread 的新手


您可以通过两种方式使用 OAUTH 2.0。

  • 服务帐号
  • Calls Google API's on behalf of your application instead of an end
    user

    点击这里了解更多详情:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import json
    import gspread
    from oauth2client.client import SignedJwtAssertionCredentials

    json_key = json.load(open('gspread-april-2cd … ba4.json'))
    scope = ['https://spreadsheets.google.com/feeds']

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

    gc = gspread.authorize(credentials)

    wks = gc.open("Where is the money Lebowski?").sheet1
  • Web应用程序
  • Accessed by web browsers over the network

    关注此博客了解更多详情

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import requests, gspread
    from oauth2client.client import SignedJwtAssertionCredentials

    def authenticate_google_docs():
        f = file(os.path.join('your-key-file.p12'), 'rb')
        SIGNED_KEY = f.read()
        f.close()
        scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds']
        credentials = SignedJwtAssertionCredentials('[email protected]', SIGNED_KEY, scope)

        data = {
            'refresh_token' : '<refresh-token-copied>',
            'client_id' : '<client-id-copied>',
            'client_secret' : '<client-secret-copied>',
            'grant_type' : 'refresh_token',
        }

        r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
        credentials.access_token = ast.literal_eval(r.text)['access_token']

        gc = gspread.authorize(credentials)
        return gc

    我已经想通了。如果其他人有兴趣,这就是我需要做的

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import json
    import gspread
    from oauth2client.client import SignedJwtAssertionCredentials
    json_key = json.load(open('Gspread-762ec21ac2c5.json'))
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = SignedJwtAssertionCredentials(json_key['client_email']
        , bytes(json_key['private_key']
        , 'utf-8')
        , scope)
    gc = gspread.authorize(credentials)
    wks = gc.open("mytestfile").sheet1