【发布时间】:2015-01-04 10:23:58
【问题描述】:
我是 Rails 新手,我想从我的网络应用程序将数据导出到 Google 电子表格。
- 我创建了一个应用程序来获取客户端 ID 和客户端密码,并为此启用了驱动器 API。
- 我已经安装了 google drive 和 google api client gem
- 我使用了here 中的代码
此代码成功运行,打开一个新选项卡进行授权,并显示要粘贴的代码。这就是我卡住的地方。谷歌授权要求的代码在我的控制器代码中,因此我的用户可以将该代码粘贴到我的控制器中。我知道问这个问题很愚蠢,但我没有找到一种方法来自动从 api 获取代码以进一步执行,就像我们通常在我们的 facebook oauth 应用程序中所做的那样。那你能指导我怎么做吗?代码看起来像
def export_spred_sheet
require 'rubygems'
require 'google/api_client'
require 'launchy'
# Get your credentials from the console
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Create a new API client & load the Google Drive API
client = Google::APIClient.new
drive = client.discovered_api('drive', 'v2')
# Request authorization
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.scope = OAUTH_SCOPE
client.authorization.redirect_uri = REDIRECT_URI
uri = client.authorization.authorization_uri
Launchy.open(uri)
# Exchange authorization code for access token
$stdout.write "Enter authorization code: "
client.authorization.code = gets.chomp
client.authorization.fetch_access_token!
# Insert a file
file = drive.files.insert.request_schema.new({
'title' => 'My document',
'description' => 'A test document',
'mimeType' => 'text/plain'
})
media = Google::APIClient::UploadIO.new('document.txt', 'text/plain')
result = client.execute(
:api_method => drive.files.insert,
:body_object => file,
:media => media,
:parameters => {
'uploadType' => 'multipart',
'alt' => 'json'})
# Pretty print the API result
jj result.data.to_hash
end
如果我走错了路,还有其他方法可以完成任务吗?
【问题讨论】:
-
您能在电子表格中写入数据吗?我能够获得访问令牌,但 session.spreadsheets 返回 []
-
@Shweta,我最近写了一个 gem,用于将您的 ActiveRecord/Mongoid 模型记录导出到 googlesheets:github.com/lakesare/model_to_googlesheet,这可能会有所帮助。
标签: ruby-on-rails ruby google-sheets google-oauth