import time from tablestore import * # 定义一个自定义错误类 class customError(Exception): def __init__(self, message,original_exception=None): super().__init__(message) self.message = message self.original_expection = original_exception print("original exception:",original_exception) class tableStore: def __init__(self,ots_client,table_name): self.ots_client = ots_client self.table_name = table_name self.email = None self.stored_password = None self.is_vip = None self.expired_at = None self.balance = None def getUserInfo(self,email)->"void or throw error": #通过email主键查询用户信息 primary_key = [ ['email', email], ] columns_to_get = ['isVip', 'expiredAt', 'password','balance'] try: consumed, return_row, next_token = self.ots_client.get_row( table_name=self.table_name, primary_key=primary_key, columns_to_get=columns_to_get ) if return_row is None: raise customError('email not exist') else: # 创建一个字典来存储键值对 attributes = {} for key, value, _ in return_row.attribute_columns: attributes[key] = value self.email = email self.expired_at = attributes['expiredAt'] self.is_vip = attributes['isVip'] self.stored_password = attributes['password'] self.balance = attributes['balance'] except Exception as e: raise customError("请求getUserInfo失败",e) def checkInit(self)->"bool or throw error": # 使用 all() 函数检查所有属性是否都存在且不为 None return all([self.email is not None, self.stored_password is not None, self.is_vip is not None, self.expired_at is not None]) def login(self, email, password)-> "user info or throw error": self.getUserInfo(email) #检测登录前先获取用户信息 if self.checkInit(): #都存在说明正常初始化 if self.email==email and self.stored_password==password: return {"ec":200,"expiredAt":self.expired_at ,"balance":self.balance,"email":email,"password":password} else: raise customError("login验证失败-账户不匹配") else: raise customError("login调用时发现用户信息没有正常初始化") def checkVipStatus(self)->"bool or throw error": current_time = int(time.time()) if self.checkInit(): if self.expired_at > current_time: #只看截止时间 return True else: return False else: raise customError("checkVipStatus调用时发现用户信息没有正常初始化") def userSignUp(self,email,password)->"user info or throw error": #如果收到参数不够,那么务必设置默认值 expiredAt->0 ,isVip->false primary_key = [ ['email', email], ] attribute_columns = [ ['isVip', False], # 注册用户不为vip ['password', password], ['expiredAt', int(time.time())], # 第一次创建过期时间为当前时间 ['balance', int(0)], # 第一次创建balance为0 ] try: self.ots_client.put_row( table_name=self.table_name, row=Row( primary_key=primary_key, attribute_columns=attribute_columns ), condition=Condition(RowExistenceExpectation.EXPECT_NOT_EXIST) # 这种只要存在就不执行(多次注册只有第一次生效) ) return {"ec":200,"expiredAt":0 ,"balance":0,"email":email,"password":password} except Exception as e: raise customError("userSignUp 失败",e) def userDelete(self,email,password)->"user info or throw error": self.getUserInfo(email) # 检测登录前先获取用户信息 primary_key = [ ['email', email], ] if self.checkInit(): # 都存在说明正常初始化 try: if not (self.email==email and self.stored_password==password): raise customError("用户或密码不正确") # 删除用户信息 self.ots_client.delete_row( table_name=self.table_name, primary_key=primary_key, condition=Condition(RowExistenceExpectation.EXPECT_EXIST) # 只有存在的行才能删除 ) return {"ec": 200, "message": "用户删除成功", "email": email} except Exception as e: raise customError("userDelete 失败", e) else: raise customError("login调用时发现用户信息没有正常初始化") def updateColumnByPrimaryKey(self,key:str,key_value:'dynamic', update_column:str,update_column_value:'dynamic')\ -> "bool or throw error": #比如支付回调的时候没有密码,故而只根据主键email更新时间 primary_key = [ (key, key_value), ] update_of_attribute_columns = { 'PUT': [(update_column, update_column_value)] } updateRow = Row( primary_key=primary_key, attribute_columns=update_of_attribute_columns ) try: table_meta = self.ots_client.describe_table(table_name=self.table_name) defined_columns = table_meta.table_meta.defined_columns # 定义的非主键列-不受意外列添加影响 isColumnExist = any(column_name == update_column for column_name, _ in defined_columns) condition = Condition(RowExistenceExpectation.EXPECT_EXIST) if isColumnExist: # 执行UpdateRow操作 self.ots_client.update_row( table_name=self.table_name, row=updateRow, condition=condition ) return True else: raise customError("更新列名不存在") except Exception as e: raise customError('更新操作发生问题',e) if __name__ == '__main__': access_key_id = 'LTAI5tNwpEHCMTupADmx6xA4' access_key_secret = "vX1q5Tvj3LSsIMUXN6SPbMUBCET3qG" end_point = 'https://v2b-user-table.ap-southeast-1.ots.aliyuncs.com' instance_name = 'v2b-user-table' table_name = 'user' ots_client = OTSClient( end_point=end_point, access_key_id=access_key_id, access_key_secret=access_key_secret, instance_name=instance_name ) tablestore = tableStore(ots_client=ots_client,table_name=table_name) # tablestore.updateColumnByPrimaryKey(key='email',key_value='user@example.com', # update_column='balance',update_column_value=1728877808) resp = tablestore.userDelete('1234567891011@qq.com','12345678910') print(resp)