如何解决Google Sheets API两次插入记录重复记录
我目前正在使用Google::Apis::Sheets
开发Ruby脚本应用程序。我遇到一个问题,试图找出从哪里产生的。基本上,当将数据追加到Google工作表中时,数据将被插入两次。因此,例如,如果传递了50条记录以附加到Google表格中,则会创建100条记录。
# data should be an array of arrays
class Sheets
#some code here
def append(data)
# Initialize the API
service = Google::Apis::SheetsV4::SheetsService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
# Prints the names and majors of students in a sample spreadsheet:
# https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
spreadsheet_id = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
range = "Sheet1!A:C"
request_body = Google::Apis::SheetsV4::ValueRange.new
request_body.values = data
service.append_spreadsheet_value(spreadsheet_id,range,request_body,value_input_option: 'USER_ENTERED')
end
end
上述方法append_spreadsheet_value将这些值附加到电子表格中。我正在尝试确定将range
传递到request_body
时,错误是来自data
还是request_body.values
。
正在从AWS Lambda上托管的另一个文件append
调用方法reporting.rb
。该方法具有以下脚本。
def self.process(event:,context:,db: MySQL.new)
FileUtils.cp('./token.yaml','/tmp/token.yaml')
last_day = db.get_last_day()
sheets = Sheets.new
data = []
last_day.each do |row|
data.push([row["created_at"].strftime("%Y-%m-%d"),row["has_email"],row["type"]])
end
sheets.append(data)
api_gateway_resp(statusCode: 204)
end
基本上是在方法last_day
中,我正在通过MySQL2
客户端从数据库中检索一些记录。然后,我遍历last_day
,并将每个rwo添加到data
中。因此,基本上data
是一个数组数组,用于保存以下格式的记录。
data = [
[2020-08-06,1,QUARANTINE],[2020-08-06,POSITIVE],QUARANTINE]
]
因此,当data
数据附加到Google绵羊时,如果sheets.append(data)
有10条记录,则会创建20条记录。
解决方法
由于我的其他帖子已被删除,请尝试替换
request_body = Google::Apis::SheetsV4::ValueRange.new
使用
request_body={
"range":range,"majorDimension":"ROWS","values":values
}
,
该问题是由于Lambda函数触发器的配置设置为每10小时运行一次。