0

所以我正在编写一个脚本来批量删除 Google Apps for Education 域中的用户。代码如下所示:

#! /usr/bin/env ruby
require 'google/api_client'
require 'csv'

service_account_email = 'XXXXXXX@developer.gserviceaccount.com'
key_file = 'key.p12'
key_secret = 'notasecret'
admin_email = 'XXX@xxx'

# Build the API Client object
client = Google::APIClient.new(
  :application_name => 'XXX',
  :application_version => '0.1'
)
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience => 'https://accounts.google.com/o/oauth2/token',
  :scope => 'https://www.googleapis.com/auth/admin.directory.user',
  :issuer => service_account_email,
  :signing_key => key,
  :person => admin_email,
)
client.authorization.fetch_access_token!
directory = client.discovered_api('admin', 'directory_v1')

# Reads and parses CSV input into a hash
# Takes file path as an argument
def import_csv(file)
  csv = CSV.new(
    File.open(file).read,
    :headers => true,
    :header_converters => :symbol
  )

  return csv.to_a.map {|row| row.to_hash}
end

users_to_delete = import_csv('accounts.csv')

puts 'Preparing to delete users...'

users_to_delete.each_slice(1000) do |chunk|  
  directory.batch do |directory|
    chunk.each do |user|
      client.execute!(
        :api_method => directory.users.delete,
        :parameters => { :userKey => user[:emailaddress].downcase }
      )
    end
  end
end

puts 'Users successfully deleted!'

当我在没有两个外部批处理块的情况下运行脚本时,脚本运行完美(尽管速度非常慢)。

我想知道的是我需要更改什么以停止在目录 API 的“批处理”方法上给我未定义的方法错误。在 Google 文档的示例中,我注意到它们调用 API 的方式不同(zoo = Google::Apis::ZooV1::ZooService.new而不是zoo = client.discovered_api('zoo', 'v1'))。不过,我不明白这会有什么不同。

4

1 回答 1

1

您可以通过以下方式实现它:

client = Google::APIClient.new(
 :application_name => 'XXX',
 :application_version => '0.1'

)

directory = client.discovered_api('admin', 'directory_v1')
batch = Google::APIClient::BatchRequest.new do |result|
 puts result.data
end
batch.add(:api_method => directory.users.delete,:parameters => { :userKey =>       user[:emailaddress].downcase })
client.execute(batch)
于 2015-12-15T14:49:41.203 回答