def save_row_to_db(self, row, stream=sys.stdout): """Save a row from the Common Names sheet to the database. Args: row: The number of the row to save. stream: Optional IO stream to print messages to. Returns: bool: `True` if changes have been made, `False` if not. """ cn_json = self.cell(row, self.cols['Common Name (JSON)']).value cn_dict = json.loads(cn_json) section = dbify(self.cell(row, self.cols['Section']).value) description = self.cell(row, self.cols['Description']).value print('-- BEGIN editing/creating Section \'{0}\' from row #{1}. ' '--'.format(section, row), file=stream) edited = False cn = CommonName.get_or_create(name=dbify(cn_dict['Common Name']), index=dbify(cn_dict['Index']), stream=stream) sec = None if not cn.created: sec = Section.query\ .filter(Section.name == section, Section.common_name_id == cn.id)\ .one_or_none() if sec: print('The Section \'{0}\' has been loaded from the database.' .format(sec.name), file=stream) else: edited = True sec = Section(name=section) sec.common_name = cn print('CommonName for the Section \'{0}\' set to: {1}' .format(sec.name, cn.name), file=stream) db.session.add(sec) print('The Section \'{0}\' does not yet exist in the database, ' 'so it has been created.'.format(sec.name), file=stream) if description != sec.description: edited = True if description: sec.description = description print('Description for the Section \'{0}\' set to: {1}' .format(sec.name, sec.description), file=stream) else: sec.description = None print('Description for the Section \'{0}\' has been cleared.' .format(sec.name), file=stream) if edited: db.session.flush() print('Changes to the Section \'{0}\' have been flushed to ' 'the database.'.format(sec.name), file=stream) else: print('No changes were made to the Section \'{0}\'.' .format(sec.name), file=stream) print('-- END editing/creating Section \'{0}\' from row #{1}. ' '--'.format(sec.name, row), file=stream) return edited