Skip to content

Instantly share code, notes, and snippets.

@mekarpeles
Created September 13, 2023 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mekarpeles/df3e3d11f8af1c0d4c3e2630de3f993a to your computer and use it in GitHub Desktop.
Save mekarpeles/df3e3d11f8af1c0d4c3e2630de3f993a to your computer and use it in GitHub Desktop.
@dataclass
class ImportRecordSchema:
...
class ImportRecord:
def __init__(self, **data):
self.data = ImportRecordSchema(data)
self.validate() # include promise item check, or raise exceptions
self.edition_key = self.find_matching_edition()
self.edition = self.edition_key and web.ctx.site.get(self.edition_key)
self.work_key = self.edition and self.edition.works[0].key
self.work = self.edition.works[0] if self.work_key else new_work(self.edition.dict(), self.data)
if not work_key:
self.edition.works = [{'key': self.work['key']}]
# this is where the business happens
fix_author_redirects()
update_edition_with_rec_data()
update_work_with_rec_data()
def validate(self):
...
def find_matching_edition(self):
...
def create(self, account_key=None):
"""i.e. load_data"""
...
def load(self):
"""Updates the record's work and edition with data in the record
"""
...
def has_edition_mods(self):
"""edition in db v. self's modified self.edition"""
original_edition = web.ctx.site.get(self.edition_key)
return original_edition == self.edition
def has_work_mods(self):
"""work in the db v. self's modified self.work"""
original_work = self.work_key and web.ctx.site.get(self.work_key)
return original_work == self.work
def import(rec, account_key=None):
r = ImportRecord(**rec) # performs normalize
if not r.edition:
return r.create(account_key=account_key)
has_work_mods, has_edition_mods = r.has_edition_mods(), r.has_work_mods()
edits = [
i for (i, modified) in
[(r.edition, has_edition_mods), (r.work, has_work_mods)]
if modified
]
if edits:
web.ctx.site.save_many(
edits, comment='import existing book', action='edit-book'
)
return {
'success': True,
'edition': {
'key': r.edition_key,
'status': 'matched' if has_edition_mods else 'created',
},
'work': {
'key': r.work_key,
'status': 'matched' if has_work_mods else 'created'
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment