Python Spanner客户端API INSERT DML不插入数据或返回错误

时间:2018-10-31 18:48:26

标签: python google-cloud-platform google-cloud-spanner

我有一个允许我重新使用扳手客户端连接的类。我正在尝试使用DML进行基本插入,但无法在我的课程中完成此操作。我可以使用命令行插入数据:

cloud spanner databases execute-sql queue --instance=sandbox --sql="INSERT MESSAGE_STORE (MessageId,Message,MessageRecipient,MessageSender) VALUES ( 'id','hello spanner','fred','bob')"

但是,当我尝试使用python客户端库进行等效操作时,它不会插入行,甚至不会引发错误。我已将调试设置为true,所以这不应该成为问题。我来自C / C ++背景,并且是python的新手,所以不确定,错误可能就在那儿。

这是我的班级代码:

class DataStore():

def __init__(self):

        self.logger = logging.getLogger('manager.sub')
        loghandler = logging.StreamHandler(sys.stdout)
        loghandler.setFormatter(logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
         self.logger.addHandler(loghandler)
         self.logger.setLevel(logging.DEBUG)

        client = spanner.Client()
        self.instance = client.instance(INSTANCE_ID)
        database = self.instance.database(DATABASE_ID)
        self.client = database

def insertmessage(self, newmsg):
    messageid = uuid.uuid4()
    sender = newmsg['Sender']
    recipient = newmsg['Recipient']
    message = newmsg['Message']

    # Values are hardcoded for now until I can get it to work

    def insert_message(transaction):
            row_ct = transaction.execute_update(
                "INSERT MESSAGE_STORE (MessageId, Message, MessageRecipient, MessageSender) "
            " VALUES ('id','hello spanner' , 'fred' , 'bob') "
            )

            print("{} record(s) inserted.".format(row_ct))

            try:
                self.client.run_in_transaction(insert_message)
            except Exception as e:
                self.logger.debug(e)

    # Hardcoded for now until I can actually get the data inserted
    output = "{ 'Message Id':" +  str(messageid) +", 'Result Code': '1' }"
    return output

1 个答案:

答案 0 :(得分:0)

您的问题似乎是由于Python对适当间距和缩进的严格要求所致。更新insert_message函数,使其结构如下:

def insert_message(transaction):
    row_ct = transaction.execute_update(
        "INSERT MESSAGE_STORE (MessageId, Message, MessageRecipient, MessageSender) "
        " VALUES ('id', 'hello spanner', 'fred', 'bob')"
    )

    print("{} record(s) inserted.".format(row_ct))

try:
    self.client.run_in_transaction(insert_message)
except Exception as e:
    self.logger.debug(e)