問(wèn)題描述
我想使用它的 API 將文件上傳到谷歌驅(qū)動(dòng)器,我正在使用代碼
I want to upload a file to google drive using its API, I am using the code
def newer():
url= 'https://USERNAME:PASSWORD@www.googleapis.com/upload/drive/v3/files?uploadType=media'
data='''{{
"name":"testing.txt",
}}'''
response = requests.post(url, data=data)
print response.text
但是,我收到如下響應(yīng)錯(cuò)誤消息.
However, I am getting response error message as below.
{錯(cuò)誤":{錯(cuò)誤":[{域":全球",原因":authError","message": "此 API 不支持 HTTP 基本身份驗(yàn)證",位置類型":標(biāo)題","location": "Authorization" } ], "code": 401, "message": "HTTP Basic Authentication is not supported for this API" } }
{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "HTTP Basic Authentication is not supported for this API", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "HTTP Basic Authentication is not supported for this API" } }
還有其他方法可以使用 python 完成我的工作嗎?
Is there some other way to do my job using python.
我是否需要登錄谷歌云才能訪問(wèn) API 以獲取身份驗(yàn)證令牌或憑據(jù)
Should I need to sign in to google cloud to access API for authentication token or credentials
推薦答案
終于明白如何使用api上傳文件到google drive了.
Finally I Understood how do I upload file to google drive using api.
首先你需要安裝 python 庫(kù),它提供了使用驅(qū)動(dòng) api 的方法.安裝庫(kù): pip install google-api-python-client然后代碼如下.
first you need to install python library which gives the methods to use drive api. installing the library: pip install google-api-python-client then code as below.
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from apiclient.http import MediaFileUpload,MediaIoBaseDownload
import io
# Setup the Drive v3 API
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
drive_service = build('drive', 'v3', http=creds.authorize(Http()))
上面的代碼片段是創(chuàng)建對(duì)象/變量,允許您使用正確的憑據(jù)進(jìn)入驅(qū)動(dòng)器.這里 drive_service
可以做到這一點(diǎn).
above code snippet is to create object/variable which allow you to get inside the drive with a right credential. here drive_service
does that work.
文件上傳代碼如下.
def uploadFile():
file_metadata = {
'name': 'fileName_to_be_in_drive.txt',
'mimeType': '*/*'
}
media = MediaFileUpload('Filename_of_your_local_file.txt',
mimetype='*/*',
resumable=True)
file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print ('File ID: ' + file.get('id'))
文件 ID 很重要,因?yàn)槿绻獜尿?qū)動(dòng)器下載文件,則需要文件 ID.
The file ID is important because if you want to download the file from the drive you need the file ID.
這篇關(guān)于如何使用 python 的驅(qū)動(dòng)器 API 將文件上傳到谷歌驅(qū)動(dòng)器?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!