python - 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)
我认为有更好的方法来实现以下功能,但不太确定如何 -
如何自动提供用户同意,避免脚本打开浏览器征求用户同意,因为脚本将在 AWS EC2 实例上运行。
使用单一的身份验证方法来完成这两个任务(列出驱动器上文件夹中的所有文件,并读取文件的内容),而不是同时使用 oAuth2 和服务帐户。
如果有人能指出我正确的方向,那就太好了。TIA
解决方案
推荐阅读
- sql - SQL 语句中的预期参数问题
- python - Python 使用正则表达式匹配破折号
- arrays - 在MATLAB中计算数组的平均值
- java - 一次对 2 个数组进行排序,无需额外空间
- reactjs - 使用情绪/反应的组件包时出现运行时错误“对象(...)不是函数”
- android - Flutter Admob Interstitial Ad 将系统底部导航栏颜色覆盖为白色
- spring-logback - 如何为 logback 填充自定义字段值?
- c# - Application.Run 在新桌面上执行但不运行表单
- android - Kotlin和Android中内部类的作用是什么
- python - 在 GNU Octave 中执行 Python 文件