gpt4 book ai didi

python - 从 Google Drive Python API 获取 createdDate 以供下载

转载 作者:行者123 更新时间:2023-11-28 21:44:26 27 4
gpt4 key购买 nike

我想创建一个 Python 脚本来备份 Google Drive 文件作为一种乐趣/学习,但我被卡住了。我下面的脚本确实有效,但它只是将我本地驱动器上所有文件的最后修改日期和创建日期作为备份日期,并且没有保留原始创建日期/修改日期,因为它们在谷歌驱动器上。

这是我的脚本:

from __future__ import print_function
import sys, httplib2, os, datetime, io
from time import gmtime, strftime
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from datetime import date

#########################################################################
# Fixing OSX el capitan bug ->AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urlencode'
os.environ["PYTHONPATH"] = "/Library/Python/2.7/site-packages"
#########################################################################

CLIENT_SECRET_FILE = 'client_secrets.json'
TOKEN_FILE="drive_api_token.json"
SCOPES = 'https://www.googleapis.com/auth/drive'
APPLICATION_NAME = 'Drive File API - Python'
OUTPUT_DIR=str(date.today())+"_drive_backup"

try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None

def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, TOKEN_FILE)
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials

def prepDest():
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
return True
return False

def downloadFile(file_name, file_id, file_createdDate, mimeType, service):
request = service.files().get_media(fileId=file_id)
if "application/vnd.google-apps" in mimeType:
if "document" in mimeType:
request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
file_name = file_name + ".docx"
else:
request = service.files().export_media(fileId=file_id, mimeType='application/pdf')
file_name = file_name + ".pdf"
print("Downloading -- " + file_name)
response = request.execute()
with open(os.path.join(OUTPUT_DIR, file_name), "wb") as wer:
wer.write(response)

def listFiles(service):
def getPage(pageTok):
return service.files().list(q="mimeType != 'application/vnd.google-apps.folder'",
pageSize=1000, pageToken=pageTok, fields="nextPageToken,files(id,name, createdDate, mimeType)").execute()
pT = ''; files=[]
while pT is not None:
results = getPage(pT)
pT = results.get('nextPageToken')
files = files + results.get('files', [])
return files

def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
for item in listFiles(service):
downloadFile(item.get('name'), item.get('id'), item.get('createdDate'), item.get('mimeType'), service)

if __name__ == '__main__':
main()

要尝试获取创建日期,您可以在我在 createdDate 中添加的上述脚本中看到,它看起来像是我可以从文件中获取的一些元数据: https://developers.google.com/drive/v2/reference/files

但我不知道我是否正确地获取了该元数据,如果是这样,我实际上是如何将它分配给我下载的文件的。

编辑:真的很抱歉,但我没有指定操作系统 - 这是用于 mac 的。

最佳答案

File v2 createdDate 在 v3 中重命名为 createdTime

文件引用you linked适用于 v2,但您的代码连接到 v3 服务。当我运行你的代码时,它使用 createdDate v2 API 发生错误(createdDate 是无效的元数据字段)。

我切换到v3 File API,列出创建时间为createdTime , 并且能够无误地检索时间。

文件创建时间仅在 Windows 中可变

Linux/Unix 不允许设置文件的创建时间,但可以通过os.utime() 修改文件的修改时间和访问时间。 (此功能需要两次)。 Drive API 提供 createdTimemodifiedTime但是对于访问时间没有任何意义(这可能在那里没有意义),尽管修改时间也可以作为访问时间。

在 Windows 中,文件创建时间可以用 win32file.SetFileTime 设置.

时间转换

请注意,传递给上述时间戳函数的时间以纪元以来的秒数为单位。 Drive API 返回 ISO 8601我们转换为秒的字符串:

dt = datetime.datetime.strptime(dateTime, "%Y-%m-%dT%H:%M:%S.%fZ")
secs = int(dt.strftime("%s"))

修改

  1. createdDate 的所有实例替换为 createdTime

  2. listFiles() > getPage() 中,将 modifiedTime 添加到元数据字段:

    def listFiles(service):
    def getPage(pageTok):
    return service.files().list(q="mimeType != 'application/vnd.google-apps.folder'",
    pageSize=1000, pageToken=pageTok, fields="nextPageToken,files(id,name, createdTime, modifiedTime, mimeType)").execute()
  3. main()for 循环中,将 modifiedTime 传递给 downloadFiles() :

    downloadFile(item.get('name'), item.get('id'), item.get('createdTime'), item.get('modifiedTime'), item.get('mimeType'), service)
  4. downloadFiles()中,在file_createdTime之后的参数列表中添加modifiedTime

  5. 添加这些函数来设置文件时间戳:

    def dateToSeconds(dateTime):
    return int(datetime.datetime.strptime(dateTime, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%s"))

    def setFileTimestamps(fname, createdTime, modifiedTime):
    ctime = dateToSeconds(createdTime)
    mtime = dateToSeconds(modifiedTime)
    setFileCreationTime(fname, ctime)
    setFileModificationTime(fname, mtime)

    def setFileModificationTime(fname, newtime):
    # Set access time to same value as modified time,
    # since Drive API doesn't provide access time
    os.utime(fname, (newtime, newtime))

    def setFileCreationTime(fname, newtime):
    """http://stackoverflow.com/a/4996407/6277151"""
    if os.name != 'nt':
    # file creation time can only be changed in Windows
    return

    import pywintypes, win32file, win32con

    wintime = pywintypes.Time(newtime)
    winfile = win32file.CreateFile(
    fname, win32con.GENERIC_WRITE,
    win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
    None, win32con.OPEN_EXISTING,
    win32con.FILE_ATTRIBUTE_NORMAL, None)

    win32file.SetFileTime(winfile, wintime, None, None)

    winfile.close()
  6. downloadFiles() 中,写入文件后立即调用 setFileTimestamps()(作为函数的最后一行):

    def downloadFile(file_name, file_id, file_createdTime, modifiedTime, mimeType, service):
    request = service.files().get_media(fileId=file_id)
    if "application/vnd.google-apps" in mimeType:
    if "document" in mimeType:
    request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    file_name = file_name + ".docx"
    else:
    request = service.files().export_media(fileId=file_id, mimeType='application/pdf')
    file_name = file_name + ".pdf"
    print("Downloading -- " + file_name)
    response = request.execute()
    prepDest()
    fname = os.path.join(OUTPUT_DIR, file_name)
    with open(fname, "wb") as wer:
    wer.write(response)

    setFileTimestamps(fname, file_createdTime, modifiedTime)

GitHub repo

关于python - 从 Google Drive Python API 获取 createdDate 以供下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738961/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com