Skip to content

Instantly share code, notes, and snippets.

@cdrini
Last active September 19, 2023 23:42
Show Gist options
  • Save cdrini/a02a82153dbef1e130f5da6b77dc2555 to your computer and use it in GitHub Desktop.
Save cdrini/a02a82153dbef1e130f5da6b77dc2555 to your computer and use it in GitHub Desktop.
from dataclasses import dataclass
import web
@dataclass
class ImportRecord:
title: str
subtitle: str
...
def from_web_data(data: bytes) -> 'ImportRecord':
if blah:
return ImportRecord.from_json(data)
elif blah:
return ImportRecord.from_marc(data)
...
pass
def from_json(data: dict) -> 'ImportRecord':
pass
def from_marc(data: dict) -> 'ImportRecord':
pass
def to_edition(self) -> EditionDict:
pass
def to_work(self) -> WorkDict:
pass
def find_edition(self) -> Edition | None:
pass
def find_work(self) -> Work | None:
pass
#----- API ------
class importapi(delegate.page):
path = "/api/import"
def POST(self):
data = web.data()
try:
import_record = ImportRecord.from_web_data(web.data())
do_import(import_record)
except ValidationError:
# Blah
pass
except ImportError:
# Blah
pass
def do_import(record: ImportRecord, dry_run=False, allow_validation_errors=False) -> None:
import_source = determine_import_source(record)
validation_errors = import_source.validate(record)
if validation_errors and not allow_validation_errors:
raise ValidationError(validation_errors)
edition = matched_edition = record.find_edition()
if not matched_edition:
edition = create_stub_edition()
work = matched_work = edition.works[0] if matched_edition else record.find_work()
if not matched_work:
work = create_stub_work()
resulting_edition = merge_edition(edition, record.to_edition())
resulting_work = merge_work(work, record.to_work())
if not dry_run:
resulting_work['key'] = resulting_work['key'] or create_work_key()
resulting_edition.works = [resulting_work]
resulting_edition['key'] = resulting_edition.key or create_edition_key()
edits = []
if resulting_edition != edition:
edits.append(resulting_edition)
if resulting_work != work:
edits.append(resulting_work)
## Errr authors..... nested edits....
#----- IMPORT SOURCES ------
def determine_import_source(record: ImportRecord) -> ImportSource:
for source in ImportSource.all():
if source.matches(record):
return source
class ImportSource:
def matches(record: ImportRecord) -> bool:
pass
class BWBImportSource(ImportSource):
def matches(record: ImportRecord) -> bool:
return record.title.startswith("BWB")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment