Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Python(FLASK)实现Google Drive V3 API_Python_Flask_Request_Google Drive Api - Fatal编程技术网

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

如何用Python(FLASK)实现Google Drive V3 API,python,flask,request,google-drive-api,Python,Flask,Request,Google Drive Api,为了下载一个文件,我一直在尝试在FLASK中实现这个GoogleDriveAPI脚本,但我遇到了这个错误,它似乎影响了整个脚本 local variable 'request' referenced before assignment 如果我将变量重命名为req,错误就会消失,但是我认为请求没有被正确发送,因为我的print语句不会产生任何结果。它可能与从AJAX调用中检索数据的冲突请求有关,但我不确定。感谢您的帮助 service = build('drive', 'v3', credent

为了下载一个文件,我一直在尝试在FLASK中实现这个GoogleDriveAPI脚本,但我遇到了这个错误,它似乎影响了整个脚本

local variable 'request' referenced before assignment
如果我将变量重命名为req,错误就会消失,但是我认为请求没有被正确发送,因为我的print语句不会产生任何结果。它可能与从AJAX调用中检索数据的冲突请求有关,但我不确定。感谢您的帮助

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()
这是我的全部代码

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))

经过一天的进一步测试,我破解了它。对于将来希望通过Flask实现驱动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))