如何使用Python和Drive API v3下载Google云端硬盘文件 [英] How to download a Google Drive file using Python and the Drive API v3

查看:130
本文介绍了如何使用Python和Drive API v3下载Google云端硬盘文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用python脚本从Google云端硬盘将文件下载到本地系统,但是在运行Python脚本时遇到禁止"问题.脚本如下:

I have tried downloading file from Google Drive to my local system using python script but facing a "forbidden" issue while running a Python script. The script is as follows:

import requests

url = "https://www.googleapis.com/drive/v3/files/1wPxpQwvEEOu9whmVVJA9PzGPM2XvZvhj?alt=media&export=download"

querystring = {"alt":"media","export":"download"}

headers = {
    'Authorization': "Bearer TOKEN",

    'Host': "www.googleapis.com",
    'Accept-Encoding': "gzip, deflate",
    'Connection': "keep-alive",
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.url)
#
import wget
import os
from os.path import expanduser


myhome = expanduser("/home/sunarcgautam/Music")
### set working dir
os.chdir(myhome)

url = "https://www.googleapis.com/drive/v3/files/1wPxpQwvEEOu9whmVVJA9PzGPM2XvZvhj?alt=media&export=download"
print('downloading ...')
wget.download(response.url)

在此脚本中,我有禁止的问题.我在脚本中做错了什么吗?

In this script, I have got forbidden issue. Am I doing anything wrong in the script?

我还尝试了在Google Developer页面上找到的另一个脚本,如下所示:

I have also tried another script that I found on a Google Developer page, which is as follows:

import auth
import httplib2
SCOPES = "https://www.googleapis.com/auth/drive.scripts"
CLIENT_SECRET_FILE = "client_secret.json"
APPLICATION_NAME = "test_Download"
authInst = auth.auth(SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME)
credentials = authInst.getCredentials()
http = credentials.authorize(httplib2.Http())
drive_serivce = discovery.build('drive', 'v3', http=http)

file_id = '1Af6vN0uXj8_qgqac6f23QSAiKYCTu9cA'
request = drive_serivce.files().export_media(fileId=file_id,
                                             mimeType='application/pdf')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print ("Download %d%%." % int(status.progress() * 100))

此脚本给我一个 URL不匹配错误.

那么Google控制台凭据中的重定向URL应该给出什么?或任何其他解决方案?是否需要在两个脚本中都从Google授权我的Google控制台应用程序?如果是这样,那么由于我还没有找到与该应用有关的任何文件,因此对该应用进行授权的过程将如何?

So what should be given for redirect URL in Google console credentials? or any other solution for the issue? Do I have to authorise my Google console app from Google in both the script? If so, what will the process of authorising the app because I haven't found any document regarding that.

推荐答案

要向Google API发出请求,工作流程本质上如下:

To make requests to Google APIs the work flow is in essence the following:

  1. 转到开发者控制台,如果尚未登录,请登录.
  2. 创建一个Cloud Platform项目.
  3. 为您的项目启用您感兴趣的与项目的应用程序一起使用的API(例如:Google Drive API).
  4. 创建并下载 OAuth 2.0客户端ID 凭据,这些凭据将允许您的应用获得使用启用的API的授权.
  5. 转到,然后使用按钮. (范围: https://www.googleapis.com/auth/drive.readonly ).根据需要选择内部/外部",现在忽略警告(如果有).
  6. 要获取用于发出API请求的有效令牌,应用将通过OAuth流程接收授权令牌. (因为需要征得同意)
  7. 在OAuth流程中,用户将被重定向到您的OAuth同意屏幕,并在该屏幕上被要求批准或拒绝访问您应用所请求的范围.
  8. 如果获得同意,您的应用将获得授权令牌.
  9. 将请求中的令牌传递到授权的API端点. [ 2 ]
  10. 构建驱动器服务以发出API请求(您将需要有效的令牌) [ 1 ]
  1. Go to developer console, log in if you haven't.
  2. Create a Cloud Platform project.
  3. Enable for your project, the APIs you are interested in using with you projects' apps (for example: Google Drive API).
  4. Create and download OAuth 2.0 Client IDs credentials that will allow your app to gain authorization for using your enabled APIs.
  5. Head over to and add your scope using the button. (scope: https://www.googleapis.com/auth/drive.readonly for you). Choose Internal/External according to your needs, and for now ignore the warnings if any.
  6. To get the valid token for making API request the app will go through the OAuth flow to receive the authorization token. (Since it needs consent)
  7. During the OAuth flow the user will be redirected to your the OAuth consent screen, where it will be asked to approve or deny access to your app's requested scopes.
  8. If consent is given, your app will receive an authorization token.
  9. Pass the token in your request to your authorized API endpoints.[2]
  10. Build a Drive Service to make API requests (You will need the valid token)[1]


注意:

用于Drive API v3的文件资源的可用方法是此处.

使用Python Google API客户端时,您可以将export_media()get_media()用作

When using the Python Google APIs Client, then you can use export_media() or get_media() as per Google APIs Client for Python documentation

此外,请检查所使用的示波器是否实际上允许您执行所需的操作(从用户的驱动器下载文件)并进行相应设置.在ATM机上,您的目标范围不正确.请参见 OAuth 2.0 API范围

Also, check that the scope you are using, actually allows you to do what you want (Downloading Files from user's Drive) and set it accordingly. ATM you have an incorrect scope for your goal. See OAuth 2.0 API Scopes

  1. 构建驱动器服务:

import google_auth_oauthlib.flow
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
 
 
class Auth:
 
    def __init__(self, client_secret_filename, scopes):
        self.client_secret = client_secret_filename
        self.scopes = scopes
        self.flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(self.client_secret, self.scopes)
        self.flow.redirect_uri = 'http://localhost:8080/'
        self.creds = None
 
    def get_credentials(self):
        flow = InstalledAppFlow.from_client_secrets_file(self.client_secret, self.scopes)
        self.creds = flow.run_local_server(port=8080)
        return self.creds

 
# The scope you app will use. 
# (NEEDS to be among the enabled in your OAuth consent screen)
SCOPES = "https://www.googleapis.com/auth/drive.readonly"
CLIENT_SECRET_FILE = "credentials.json"
 
credentials = Auth(client_secret_filename=CLIENT_SECRET_FILE, scopes=SCOPES).get_credentials()
 
drive_service = build('drive', 'v3', credentials=credentials)

  1. 提出导出或获取文件的请求

request = drive_service.files().export(fileId=file_id, mimeType='application/pdf')

fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%" % int(status.progress() * 100))

# The file has been downloaded into RAM, now save it in a file
fh.seek(0)
with open('your_filename.pdf', 'wb') as f:
    shutil.copyfileobj(fh, f, length=131072)

这篇关于如何使用Python和Drive API v3下载Google云端硬盘文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆