我在ruby中有一个代码,用于调用创建电子表格报告的Google Apps脚本。但这一代将花费超过20分钟(很多信息),但几分钟后我收到消息错误调用API!执行过期。
我使用以下代码:
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
APPLICATION_NAME = 'GoogleService'
SCOPE = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets']
CERT_PATH = Gem.loaded_specs['google-api-client'].full_gem_path+'/lib/cacerts.pem'
ENV['SSL_CERT_FILE'] = CERT_PATH
def self.authorize
dir_path = File.dirname(__FILE__)
client_id = Google::Auth::ClientId.from_file("#{dir_path}/client_secret.json")
token_store = Google::Auth::Stores::FileTokenStore.new(file: "#{dir_path}/google_service.yaml")
authorizer = Google::Auth::UserAuthorizer.new(
client_id, SCOPE, token_store)
user_id = 'default'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(
base_url: OOB_URI)
p "Open the following URL in the browser and enter the " +
"resulting code after authorization"
p url
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI)
end
credentials
end
def self.create_spreadsheet(environment, root_path)
id_spreadsheet = nil
scrip_id = 'MerlVgs0vXonNfecv1XNrXTOzpl-Lo'
# Initialize the API
service = Google::Apis::ScriptV1::ScriptService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = self.authorize
# Create an execution request object.
request = Google::Apis::ScriptV1::ExecutionRequest.new
request.function = 'createSpreadsheet'
request.parameters = [environment, timestamp]
begin
# Make the API request.
resp = service.run_script(scrip_id, request)
if resp.error
# The API executed, but the script returned an error.
# Extract the first (and only) set of error details. The values of this
# object are the script's 'errorMessage' and 'errorType', and an array of
# stack trace elements.
error = resp.error.details[0]
puts "Script error message: #{error['errorMessage']}"
if error['scriptStackTraceElements']
# There may not be a stacktrace if the script didn't start executing.
puts "Script error stacktrace:"
error['scriptStackTraceElements'].each do |trace|
puts "\t#{trace['function']}: #{trace['lineNumber']}"
end
end
else
id_spreadsheet = resp.response['result']
end
rescue Exception => e
# The API encountered a problem before the script started executing.
puts "Error calling API!"
puts e.message
end
id_spreadsheet
end
如何修改代码以使令牌不会过期?
感谢任何指南,感谢
此致 沃尔特