使用api下载Google文档

时间:2018-09-06 14:01:24

标签: python google-drive-api google-api-python-client

这是可共享的链接link to file

id = 1wzCjl51u131v1KBgpbiKLJs8DPPakhXCFosfYjp7BY0

manage downloads文档。

file_id = '11wzCjl51u131v1KBgpbiKLJs8DPPakhXCFosfYjp7BY0'
request = drive_service.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))

我将文件另存为dd.py,使用f5运行并收到此错误

  

第2行,在       request = drive_service.files()。export_media(fileId = file_id,   NameError:名称“ drive_service”未定义

1 个答案:

答案 0 :(得分:0)

首先,您不能确定在共享链接中找到的ID实际上是Google驱动器上文件的ID,但并非总是如此。其实我从来都不知道这种情况

  

drive_service'未定义

第二,您需要创建驱动器服务并进行身份验证,然后才能运行该代码。您应该尝试遵循python quickstart

ObjectProperty<Upload> upload = new SimpleObjectProperty();
ProgressListener progressListener = (ProgressEvent progressEvent) -> {
if (upload.get() == null) {
    return;
}
Platform.runLater(() -> {
    directory.setProgressIndicator(upload.get().getProgress().getPercentTransferred() / 100.0d);
    MainController.directoryList.set(MainController.directoryList.indexOf(directory), directory);
});
if (progressEvent.getEventType() == ProgressEventType.TRANSFER_COMPLETED_EVENT) {
    Platform.runLater(() -> {
        directory.setProgressIndicator(1.0d);
        MainController.directoryList.set(MainController.directoryList.indexOf(directory), directory);
    });
} else if (progressEvent.getEventType() == ProgressEventType.TRANSFER_FAILED_EVENT) {
    try {
        AmazonClientException ex = upload.get().waitForException();
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("Error Uploading File");
            alert.setContentText("Unable to upload file to Amazon S3:" + ex.getMessage());
            alert.showAndWait();
        });
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
};
//</editor-fold>
upload.set(s3Service.uploadFile(file, file.length(), file.getName(), progressListener));