使用Google Drive API与Python上传文件至共享驱动器的路径问题
问题解决:将Jira附件上传到Google Drive共享驱动器的指定子文件夹
问题核心原因
你的代码错误在于uploadFileToGDrive方法的文件元数据配置:
- 传入了目标子文件夹ID(
parentFolderId),但构造fileMetaData时却把共享驱动器ID(driveId)设为了父目录,完全未使用子文件夹ID - 上传共享驱动器内的子文件夹时,需要同时指定子文件夹ID作为父目录,并明确标注共享驱动器ID,否则API会默认使用个人驱动器
修正后的代码
Google Manager模块修正版
def uploadFileToGDrive(self, driveService, filename, filepath, mimetype, parentFolderId, driveId): try: # 正确配置元数据:父目录设为目标子文件夹ID,同时指定共享驱动器ID fileMetaData = { 'name': filename, 'mimeType': mimetype, 'parents': parentFolderId, 'driveId': driveId } media = MediaFileUpload(filepath, mimetype=mimetype) results = driveService.files().create( body=fileMetaData, media_body=media, fields='id', supportsAllDrives=True ).execute() print(f"文件上传成功,ID: {results.get('id')}") except Exception as e: print(f"{cm.WARNING}上传文件 {filepath} 到文件夹 {parentFolderId} 时出错\n{e}{cm.ENDC}")
额外需要修正的细节
- Jira附件下载逻辑:原代码仅创建了空文件,未写入下载内容,补充写入逻辑:
r = requests.get(dictAttachment["jira-path"], auth=("xxxxxxxx@xxxxxxxx.com", "(xxxxxxxxx)"), stream=True) path = os.path.expanduser("Desktop/holding-cell/") os.makedirs(path, exist_ok=True) # 确保目录存在 storedPath = join(path, dictAttachment['filename']) # 写入文件内容 with open(storedPath, 'wb') as file: for chunk in r.iter_content(chunk_size=1024): file.write(chunk) - 主程序缩进修正:原代码中权限创建、附件循环等逻辑存在缩进错误,需调整确保代码块归属正确,避免逻辑执行异常
内容的提问来源于stack exchange,提问作者Steve Suranie
相关产品推荐
相关产品推荐

