Python 到 Google 没有密钥文件的工作表连接器

Python to Google sheets connector without key file

我设法让 Python 读取 Google Sheet。但是,因为我正在使用 PowerBI 中的脚本来读取 Google Sheet,所以我不能在我的计算机上使用本地机密 JSON 密钥文件,因为 PowerBI 不能访问这个文件。我目前按如下方式连接到 sheet:

scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json(r'C:\Users\Laila\Documents\google_spreadsheet_secret_key.json', scope)
gc = gspread.authorize(credentials)
return gc,credentials

我想做这样的事情:

secret_key={xxx:xxx}
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json(secret_key)
gc = gspread.authorize(credentials)
return gc,credentials

这可能吗?

我已经尝试用 JSON 转储添加密钥并像那样添加它,这会出现以下错误:

        ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-85-0b15fbe84ead> in <module>

----> 8 onboarding_yearmonth=get_onboarding_year_month()

<ipython-input-30-ff93a4b40320> in get_onboarding_year_month()
      1 def get_onboarding_year_month():
----> 2     onboarding_sheet = read_onboarding_sheet()
      3     onboarding_row=onboarding_sheet.loc[onboarding_sheet['ID'] == str(client_id)]
      4     onboarding_row = onboarding_row.iloc[0]['Live date']
      5     onboarding_dt = parse(onboarding_row)

<ipython-input-28-d0961c0ce7d1> in read_onboarding_sheet()
      1 def read_onboarding_sheet():
----> 2     gc,credentials = connect_to_gsheets()
      3     spreadsheet_key = '1zeUiWGMWp-xxx'
      4     spreadsheet = gc.open_by_key(spreadsheet_key)
      5     worksheet = spreadsheet.worksheet("Onboarding Dates")

<ipython-input-82-7b436cef1e5e> in connect_to_gsheets()
      1 def connect_to_gsheets():
      2     scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
----> 3     credentials = ServiceAccountCredentials.from_json(secret_key)
      4     gc = gspread.authorize(credentials)
      5     return gc,credentials

c:\users\laila\appdata\local\programs\python\python36-32\lib\site-packages\oauth2client\service_account.py in from_json(cls, json_data)
    440         password = None
    441         if pkcs12_val is None:
--> 442             private_key_pkcs8_pem = json_data['_private_key_pkcs8_pem']
    443             signer = crypt.Signer.from_string(private_key_pkcs8_pem)
    444         else:

KeyError: '_private_key_pkcs8_pem'

根据ServiceAccountCredentials.from_json documentation你可以传递已经解析过的字典。

您可以将文件内容作为字符串复制到变量中,然后使用 json.loads().

将它们作为字典对象加载
import json


# store contents of 'C:\Users\Laila\Documents\google_spreadsheet_secret_key.json' in secrets
secrets = 'STORE_FILE_CONTENT_HERE' # Use single quotation to wrap the content
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json(json.loads(secrets), scope)
gc = gspread.authorize(credentials)
return gc,credentials

免责声明:我没有测试过。

参考

这有效:

import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None
import re
import gspread
import csv
from oauth2client.service_account import ServiceAccountCredentials
from df2gspread import df2gspread as d2g
import glob
from datetime import datetime
from datetime import date
import calendar
import requests
from dateutil.parser import parse
import json
import oauth2client
from oauth2client import _helpers
from oauth2client import client
from oauth2client import crypt
from oauth2client import transport


def connect_to_gsheets():
    scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials._from_p12_keyfile_contents(
        "email from service account insert here",
         "-----BEGIN PRIVATE KEY-----\ xxxx\n-----END PRIVATE KEY-----\n"
        ,private_key_password=None, scopes=scope,
        token_uri="https://oauth2.googleapis.com/token",
        revoke_uri=oauth2client.GOOGLE_REVOKE_URI)
   # credentials = ServiceAccountCredentials.from_json(json.loads(secrets), scope)
    gc = gspread.authorize(credentials)
    return gc,credentials
def read_cost_sheet():
    gc,credentials = connect_to_gsheets()
    spreadsheet_key = 'xxxx'
    spreadsheet = gc.open_by_key(spreadsheet_key)
    worksheet = spreadsheet.worksheet("DATA")
    list_of_lists = worksheet.get_all_values()
    onboarding_dates=pd.DataFrame(list_of_lists)
    onboarding_dates.columns = onboarding_dates.iloc[0]
    return onboarding_dates

cost_data=read_cost_sheet()
print(cost_data)

另见此处;