简体   繁体   English

如何使用 Python (FLASK) 实现 Google Drive V3 API

[英]How to Implement Google Drive V3 API with Python (FLASK)

I've been stuck trying to implement this Google Drive API script in FLASK in order to download a file but I am getting this error which seems to be impacting the entire script;我一直在尝试在 FLASK 中实现此 Google Drive API 脚本以下载文件,但我收到此错误,这似乎影响了整个脚本;

local variable 'request' referenced before assignment

If I rename the variable to req instead the error goes away, however I don't think the request is being properly sent as my print statements produce no results.如果我将变量重命名为 req,错误就会消失,但是我认为请求没有被正确发送,因为我的打印语句没有产生任何结果。 It could have something to do with conflicting requests that are made to retrieve data from my AJAX call but I'm not sure.它可能与从我的 AJAX 调用中检索数据的冲突请求有关,但我不确定。 Any help is appreciated.任何帮助表示赞赏。

service = build('drive', 'v3', credentials=creds);

    request = service.files().get_media(fileId=file_id)
    fh = io.FileIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print ("Download %d%%." % int(status.progress() * 100), file=sys.stderr)
    return fh.getvalue()

Here is my entire code;这是我的全部代码;

from __future__ import print_function
from flask import Flask, render_template, jsonify, request
import sys, requests, mimetypes
import pickle
import io
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload


@app.route('/drive_download')
def drive_download():

try:
    file_id = request.args.get("fileID") #this is being used to retrieve values from AJAX

    creds = None
    # credentials stuff goes here 
    # credentials stuff goes here 
    # credentials stuff goes here 
    # credentials stuff goes here 
    # credentials stuff goes here 

    service = build('drive', 'v3', credentials=creds);

    request = service.files().get_media(fileId=file_id)
    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), file=sys.stderr)

    return jsonify(result="it works kk  ") #for testing purposes

except Exception as e:
    return(str(e))

After a day of further testing, I cracked it.经过一天的进一步测试,我破解了它。 To anyone in the future looking for a solution to implementing Drive API Download with Flask, feel free to use my code as a boilerplate.对于未来正在寻找使用 Flask 实现 Drive API 下载的解决方案的任何人,请随意使用我的代码作为样板。

from __future__ import print_function
from flask import Flask, render_template, jsonify, request
import sys, requests, mimetypes
import pickle
import io
import os.path
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

@app.route('/drive_download')
def drive_download():


    #CREDENTIALS
    try:

        SCOPES = ['https://www.googleapis.com/auth/drive']
        ##this might need to be swapped out to work with google picker authentication
        creds = None
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', SCOPES) #Client_secret.json is what I called my credentials.json
                creds = flow.run_local_server()
        # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)




        #DOWNLOAD FILE (I'm downloading a json file)

        #Get file_id from AJAX call (this uses Picker to return the id of a file)  
        file_id = request.args.get("fileID")

        drive_service = build('drive', 'v3', credentials=creds)

        requests = drive_service.files().get_media(fileId = file_id)
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, requests)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print("Download %d%%." % int(status.progress() * 100), file=sys.stderr)
            fh.seek(0)
            json = fh.read()
            jsonRead = json.decode('utf-8') #decode from bytes into string

        return jsonify(jsonRead) #Return file contents back to AJAX call

    except Exception as e:
        return(str(e))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中使用 Google Drive API v3 更改所有者? - How to change the owner with Google Drive API v3 in Python? 如何使用Google Drive API v3上传到Python中的共享驱动器? - How do I upload to a shared drive in Python with Google Drive API v3? 如何使用 Python 和 Drive API v3 将文件上传到 Google Drive - How to upload a file to Google Drive using Python and the Drive API v3 如何使用 Python 和 Drive API v3 从 Google Drive 下载文件 - How to download a file from Google Drive using Python and the Drive API v3 在Python中覆盖Google Drive API v3 Argparse - Overwriting Google Drive API v3 Argparse in Python Google Client API v3 - 使用 Python 更新驱动器上的文件 - Google Client API v3 - update a file on drive using Python 通过python的Google Drive api v3文件上传错误 - Google Drive api v3 file upload errors via python 如何通过Python API使用Google Drive v3 API限制编辑者共享电子表格? - How to use Google Drive v3 API via Python API to restrict editors from sharing a spreadsheet? 如何使用 Python 将文件插入/上传到 Google Drive API v3 中的特定文件夹 - How can I insert/upload files to a specific folder in Google Drive API v3 using Python 如何使用 Google 云端硬盘 API v3 向 Python 中的共享文件夹进行可续传上传? - How do I do a resumable upload to a shared folder in Python using Google Drive API v3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM