所以我正在编写一个脚本来批量删除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的'batch'方法上给出未定义的方法错误。在Google文档的示例中,我注意到他们以不同的方式调用API(zoo = Google::Apis::ZooV1::ZooService.new
而不是zoo = client.discovered_api('zoo', 'v1')
)。我不知道这会如何产生影响。
答案 0 :(得分: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)