python - 为 Google 云端硬盘中上传的私有(private)文件生成可下载链接

标签 python file google-drive-api drive

是否可以为在 Google 云端硬盘中上传的私有(private)文件生成可下载链接?

我尝试使用文件 API 并生成了“webContent 链接”,但只有所有者和共享用户才能访问它。

(期望可以与任何人共享的公共(public)链接)

def file_info_drive(access_token, file_id):
    headers = {'Authorization': 'Bearer ' + access_token, "content-type": "application/json"}
    response = requests.get('https://www.googleapis.com/drive/v2/files/{file_id}', headers=headers)
    response = response.json()

    link = response['webContentLink']
    return link

最佳答案

  • 您想让任何人都使用 webContentLink 下载该文件。
  • 您想要使用 Drive API v2。
  • 您希望使用 Python 的“请求”模块来实现此目的。
  • 您已经能够使用 Drive API 上传和下载文件。

如果我的理解是正确的,那么修改一下怎么样?

修改点:

  • 为了让任何人都可以使用 webContentLink 下载该文件,需要公开共享该文件。
    • 在此修改后的脚本中,文件以 {'role': 'reader', 'type': 'anyone', 'withLink': True} 条件公开共享。在这种情况下,知道 URL 的人就可以下载该文件。

修改后的脚本:

当你的脚本修改后,它会变成如下。

def file_info_drive(access_token, file_id):
    headers = {'Authorization': 'Bearer ' + access_token, "content-type": "application/json"}

    # Using the following script, the file is shared publicly. By this, anyone can download the file.
    payload = {'role': 'reader', 'type': 'anyone', 'withLink': True}
    requests.post('https://www.googleapis.com/drive/v2/files/{file_id}/permissions', json=payload, headers=headers)

    response = requests.get('https://www.googleapis.com/drive/v2/files/{file_id}', headers=headers)
    response = response.json()

    link = response['webContentLink']
    return link

注意:

  • 在本例中,使用 POST 方法。因此,如果范围发生错误,请将 https://www.googleapis.com/auth/drive 添加到范围。

引用:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

关于python - 为 Google 云端硬盘中上传的私有(private)文件生成可下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318228/

相关文章:

python - 在二值图像上查找厚物体

firebase - Google OAuth 刷新 token 未返回有效访问 token

google-drive-api - 使用 Google API 的 Google 云端硬盘上传文件

python - 更改我正在遍历的列表时的意外行为

python - Image.fromarray(pixels) 和 np.array(img) 是否应该保持数据不变?

javascript - PHP 使用 move_uploaded_file 上传图像两次(不应该的时候)

c++ - 发送文件时套接字写入失败

java - Google Drive 的正确授权方式是什么?

python - 如何在 IPython (Jupyter) Notebook 中的远程机器上添加内核?

c++ - 一次又一次尝试在给出错误路径的同时打开文件