def set_metadata(self, key, value): if not re.match(PERMISSION_VALIDATION, key): raise ValueError('Metadata key does not match regex.') row = None for try_row in self.my_metadata(): if try_row.data_key == key: row = try_row break if row: if value is None: row.delete(self.session) else: row.data_value = value else: if value is None: # Do nothing, a delete on a key that's not set return else: row = UserMetadata(user_id=self.id, data_key=key, data_value=value) row.add(self.session) Counter.incr(self.session, "updates") self.session.commit()
def add_metadata_to_user(self, key, value, user): # type: (str, str, str) -> None sql_user = User.get(self.session, name=user) assert sql_user metadata = UserMetadata(user_id=sql_user.id, data_key=key, data_value=value) metadata.add(self.session)
def set_user_metadata(session, user_id, data_key, data_value): # type: (Session, int, str, Optional[str]) -> Optional[UserMetadata] """Set a single piece of user metadata. Args: session(models.base.session.Session): database session user_id(int): id of user in question data_key(str): the metadata key (limited to 64 character by db schema) data_value(str): the metadata value (limited to 64 character by db schema) if this is None, the metadata entry is deleted. Returns: the UserMetadata object or None if entry was deleted """ assert re.match(PERMISSION_VALIDATION, data_key), "proposed metadata key is valid" user_md = get_user_metadata_by_key( session, user_id, data_key) # type: Optional[UserMetadata] if user_md: if data_value is None: user_md.delete(session) user_md = None else: user_md.data_value = data_value user_md.add(session) else: if data_value is None: # do nothing, a delete on a key that's not set return None else: user_md = UserMetadata(user_id=user_id, data_key=data_key, data_value=data_value) user_md.add(session) Counter.incr(session, "updates") session.commit() return user_md
def set_user_metadata(session, user_id, data_key, data_value): """Set a single piece of user metadata. Args: session(models.base.session.Session): database session user_id(int): id of user in question data_key(str): the metadata key (limited to 64 character by db schema) data_value(str): the metadata value (limited to 64 character by db schema) if this is None, the metadata entry is deleted. Returns: the UserMetadata object or None if entry was deleted """ assert re.match(PERMISSION_VALIDATION, data_key), 'proposed metadata key is valid' user_md = None for try_user_md in get_user_metadata(session, user_id): if try_user_md.data_key == data_key: user_md = try_user_md break if user_md: if data_value is None: user_md.delete(session) Counter.incr(session, "updates") user_md = None else: user_md.data_value = data_value else: if data_value is None: # do nothing, a delete on a key that's not set return else: user_md = UserMetadata(user_id=user_id, data_key=data_key, data_value=data_value) user_md.add(session) Counter.incr(session, "updates") session.commit() return user_md