【问题标题】:How can I create a Google spreadsheet for a user with Ruby, as a Google Apps Admin?作为 Google Apps 管理员,我如何为使用 Ruby 的用户创建 Google 电子表格?
【发布时间】:2012-11-12 22:01:54
【问题描述】:

我想为我们的 Google Apps 服务用户自动创建文档。
注意事项:

  • 无法为用户启用 OAuth
  • 我有超级管理员 API 访问令牌
  • 我只知道用户的电子邮件地址

这可以通过现有的 Ruby 库实现吗? (大多数使用 2-legged auth 作为用户而不是管理员来完成此操作。)

【问题讨论】:

    标签: ruby google-api google-drive-api google-sheets google-apps


    【解决方案1】:

    我能够通过“服务帐户”和 Google 的(alpha)gem google-api-client 来实现这一点。这是一个从不同的 Google 文档中抽取的 Ruby 类,它在实例化时获取用户的电子邮件(来自您管理的 Google Apps 域)。

    require 'google/api_client'
    
    class GoogleDriveConnection
      def initialize(user_email=nil)
        @client = Google::APIClient.new
        @drive = @client.discovered_api('drive', 'v2')
    
        key_file_name = '<DOWNLOADED WHEN CREATING A SERVICE ACCOUNT>.p12'
        key = Google::APIClient::PKCS12.load_key("#{Rails.root.to_s}/config/#{key_file_name}", 'notasecret')
    
        asserter = Google::APIClient::JWTAsserter.new(
          '<THE EMAIL ADDRESS OF YOUR SERVICE ACCOUNT>',
          'https://www.googleapis.com/auth/drive',
        key)
    
        @client.authorization = asserter.authorize(user_email)
      end
    
      def insert_file(title, description, parent_id, mime_type, file_name)
        file = @drive.files.insert.request_schema.new({
          'title' => title,
          'description' => description,
          'mimeType' => mime_type
        })
        # Set the parent folder.
        if parent_id
          file.parents = [{'id' => parent_id}]
        end
        media = Google::APIClient::UploadIO.new(file_name, mime_type)
        result = @client.execute(
          :api_method => @drive.files.insert,
          :body_object => file,
          :media => media,
          :parameters => {
            'uploadType' => 'multipart',
            'convert' => true,
            'alt' => 'json'})
        if result.status == 200
          return result.data
        else
          puts "An error occurred: #{result.data['error']['message']}"
          return nil
        end
      end
    
      def list_files
        result = @client.execute!(:api_method => @drive.files.list)
        result.data.to_hash
      end
    
      def get_file(file_id)
        result = @client.execute!(
          :api_method => @drive.files.get,
          :parameters => { 'fileId' => file_id })
        result.data.to_hash
      end
    
      private
    
        def token
          @client.authorization.access_token
        end
    end
    

    用法很简单:

    g = GoogleDriveConnection.new('me@mycompany.com')
    g.insert_file('My file', 'File stuff', nil, 'text/csv', "#{Rails.root}/tmp/test.csv")
    

    * 创建服务帐户和管理“API 项目”很棘手。 This guide 似乎是最有用的。

    【讨论】:

    • 该课程有几个奖励方法(#list_files#get files)来帮助浏览用户的云端硬盘文件。
    猜你喜欢
    • 2017-03-27
    • 1970-01-01
    • 2022-11-17
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多