首页 > 解决方案 > Google Drive API:如何读取 Google Drive 上的 XLSX 文件并将其作为 CSV 存储在 AWS S3 上

问题描述

我正在尝试列出 Google 驱动器上某个文件夹中的所有文件,并根据模式(2021 JAN user_data.xlsx)读取最新文件。之后,我想将其存储到 AWS S3 上。

到目前为止,我已经能够使用 oAuth2 身份验证生成的 client_secret.json 文件列出所有文件,然后使用 fileId 我使用 gspread 读取内容(无法直接读取 .xlsx 文件,因此手动将其存储为电子表格) 使用服务帐户的 credentials.json 文件。

这很好用,除了它会弹出浏览器以征得用户同意,我想摆脱它,因为我计划将脚本作为 cronjob 运行到 EC2 服务器上。

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/drive']
flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", SCOPES)
cred = flow.run_local_server()
service = build('drive', 'v3', credentials=cred)
response = service.files().list(supportsAllDrives=True,includeItemsFromAllDrives=True).execute()
files_to_read = []
for each_file in response['files']:
    if 'JAN' in each_file['name']:
        files_to_read.append((each_file['id'],each_file['name']))
print("reading file content")
scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets', 
        "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
client = gspread.authorize(creds)
sheet = client.open_by_key(files_to_read[0].split(',')[0]).worksheet(files_to_read[0].split(',')[1])
all_records = sheet.get_all_records()
print(all_records)

我认为有更好的方法来实现以下功能,但不太确定如何 -

  1. 如何自动提供用户同意,避免脚本打开浏览器征求用户同意,因为脚本将在 AWS EC2 实例上运行。

  2. 使用单一的身份验证方法来完成这两个任务(列出驱动器上文件夹中的所有文件,并读取文件的内容),而不是同时使用 oAuth2 和服务帐户。

如果有人能指出我正确的方向,那就太好了。TIA

标签: pythonamazon-web-servicesgoogle-sheetsoauth-2.0google-drive-api

解决方案


推荐阅读