def test_get(self): language, created = Language.from_dict({"name": "English"}) self.assertTrue(created) self.assertIsNotNone(language.id) language2 = Language.get("English") self.assertIsNotNone(language2) self.assertEquals(language, language2) language2 = Language.get("en") self.assertIsNotNone(language2) self.assertEquals(language, language2) language2 = Language.get(str(language.id)) self.assertIsNotNone(language2) self.assertEquals(language, language2)
def test_from_to_dict(self): language, created = Language.objects.get_or_create(name="English") self.assertTrue(created) self.assertIsNotNone(language.id) self.assertEquals({"name": "English"}, language.to_dict()) self.assertEquals((language, False), Language.from_dict({"name": "English"}))
def test_print(self): language, created = Language.from_dict({"name": "English"}) self.assertTrue(created) self.assertIsNotNone(language.id) with StringIO() as cout: language.print(cout) self.assertEquals( "Field Value " + " \n==================================" + "==================================================================\n" + "Id 1 " + " \n__________________________________" + "__________________________________________________________________\n" + "Name English " + " \n__________________________________" + "__________________________________________________________________\n", cout.getvalue(), )
def test_delete(self): language, created = Language.from_dict({"name": "English"}) self.assertTrue(created) self.assertIsNotNone(language.id) deleted = language.delete() self.assertIsNone(language.id) self.assertEquals((1, {"languages.Language": 1}), deleted)
def test_save(self): language = Language(name="German") language.save() self.assertIsNotNone(language.id) self.assertEquals("german", language.slug) language = Language(name="English") language.save() self.assertIsNotNone(language.id) self.assertEquals("english", language.slug)
def from_dict(cls: Type[T], data: Dict, book: Book) -> Tuple[T, bool]: """Create from dict. Returns True if was crated, i. e. was not found in the DB. """ defaults: Dict = {} if "alternate_title" in data and data["alternate_title"]: defaults["alternate_title"] = data["alternate_title"] if "isbn" in data and data["isbn"]: defaults["isbn"] = data["isbn"] if "publishing_date" in data and data["publishing_date"]: defaults["publishing_date"] = datetime.datetime.strptime( data["publishing_date"], "%Y-%m-%d").date() if "publisher" in data and data["publisher"]: defaults["publisher"] = Publisher.from_dict(data["publisher"])[0] if "binding" in data and data["binding"]: defaults["binding"] = Binding.from_dict(data["binding"])[0] if "bibtex" in data and data["bibtex"]: defaults["bibtex"] = data["bibtex"] edition, created = cls.objects.get_or_create( book=book, alternate_title=data["alternate_title"] if "alternate_title" in data else None, isbn=data["isbn"] if "isbn" in data else None, publishing_date=data["publishing_date"] if "publishing_date" in data else None, defaults=defaults, ) if "cover_image" in data and data["cover_image"]: edition.cover_image.save( os.path.basename(data["cover_image"]), DJFile(open(data["cover_image"], "rb")), ) if "languages" in data and data["languages"]: for i in data["languages"]: edition.languages.add(Language.from_dict(i)[0]) if "links" in data and data["links"]: for i in data["links"]: edition.links.add(Link.from_dict(i)[0]) if "persons" in data and data["persons"]: for i in data["persons"]: edition.persons.add(Person.from_dict(i)[0]) if "acquisitions" in data and data["acquisitions"]: for i in data["acquisitions"]: Acquisition.from_dict(i, edition) if "files" in data and data["files"]: for i in data["files"]: File.from_dict(i, edition) if "reads" in data and data["reads"]: for i in data["reads"]: Read.from_dict(i, edition) edition.save() return edition, created
def edit(self: T, field: str, value: str, *args, **kwargs): """Change field by given value.""" assert field in [ "alternate_title", "alternate-title", "binding", "cover", "isbn", "person", "publishing_date", "publishing-date", "publisher", "language", "link", "file", ] if field == "alternate_title" or field == "alternate-title": self.alternate_title = value elif field == "binding": self.binding = Binding.get_or_create(value) elif field == "cover": self.cover_image.save(os.path.basename(str(value)), DJFile(open(str(value), "rb"))) elif field == "isbn": self.isbn = value elif field == "person": person = Person.get_or_create(value) if self.persons.filter(pk=person.pk).exists(): self.persons.remove(person) else: self.persons.add(person) elif field == "publishing_date" or field == "publishing-date": self.publishing_date = value elif field == "publisher": self.publisher = Publisher.get_or_create(value) elif field == "language": language = Language.get_or_create(value) if self.languages.filter(pk=language.pk).exists(): self.languages.remove(language) else: self.languages.add(language) elif field == "link": link = Link.get_or_create(value) if self.links.filter(pk=link.pk).exists(): self.links.remove(link) else: self.links.add(link) elif field == "file": file, created = File.from_dict({"path": value}) if self.files.filter(pk=file.pk).exists(): self.files.remove(file) file.delete() else: self.files.add(file) self.save(*args, **kwargs)
def test_get_or_create(self): language, created = Language.from_dict({"name": "English"}) self.assertTrue(created) self.assertIsNotNone(language.id) self.assertEquals(1, Language.objects.count()) language2 = Language.get_or_create("English") self.assertIsNotNone(language2) self.assertEquals(language, language2) self.assertEquals(1, Language.objects.count()) language2 = Language.get_or_create(str(language.id)) self.assertIsNotNone(language2) self.assertEquals(language, language2) self.assertEquals(1, Language.objects.count()) language2 = Language.get_or_create("German") self.assertIsNotNone(language2) self.assertNotEquals(language, language2) self.assertEquals(2, Language.objects.count())
def from_dict(cls: Type[T], data: Dict, magazine: Magazine) -> Tuple[T, bool]: """Create from dict. Returns True if was crated, i. e. was not found in the DB. """ defaults: Dict = {} if "publishing_date" in data and data["publishing_date"]: defaults["publishing_date"] = datetime.datetime.strptime( data["publishing_date"], "%Y-%m-%d" ).date() issue, created = cls.objects.get_or_create( issue=data["issue"], magazine=magazine, defaults=defaults ) if "cover_image" in data and data["cover_image"]: issue.cover_image.save( os.path.basename(data["cover_image"]), DJFile(open(data["cover_image"], "rb")), ) if "languages" in data and data["languages"]: for i in data["languages"]: if type(i) == dict: issue.languages.add(Language.from_dict(i)[0]) else: issue.languages.add(Language.get_or_create(i)) if "links" in data and data["links"]: for i in data["links"]: issue.links.add(Link.from_dict(i)[0]) if "acquisitions" in data and data["acquisitions"]: for i in data["acquisitions"]: Acquisition.from_dict(i, issue) if "files" in data and data["files"]: for i in data["files"]: File.from_dict(i, issue) if "reads" in data and data["reads"]: for i in data["reads"]: Read.from_dict(i, issue) issue.save() return issue, created
def edit(self: T, field: str, value: Union[str, datetime.date], *args, **kwargs): """Change field by given value.""" fields = [ "title", "author", "publishing_date", "publishing-date", "journal", "volume", "language", "file", "link", "bibtex", ] assert field in fields if field == "title": self.title = value elif field == "author" and isinstance(value, str): author = Person.get_or_create(value) if self.authors.filter(pk=author.pk).exists(): self.authors.remove(author) else: self.authors.add(author) elif field == "publishing_date" or field == "publishing-date": self.publishing_date = value elif field == "journal" and isinstance(value, str): self.journal = Journal.get_or_create(value) elif field == "volume": self.volume = value elif field == "bibtex": self.bibtex = value elif field == "language" and isinstance(value, str): language = Language.get_or_create(value) if self.languages.filter(pk=language.pk).exists(): self.languages.remove(language) else: self.languages.add(language) elif field == "link" and isinstance(value, str): link = Link.get_or_create(value) if self.links.filter(pk=link.pk).exists(): self.links.remove(link) else: self.links.add(link) elif field == "file": file, created = File.from_dict({"path": value}) if self.files.filter(pk=file.pk).exists(): self.files.remove(file) file.delete() else: self.files.add(file) self.save(*args, **kwargs)
def db_languages(self): """ Initializes 'Language' table and 'Translations' collection that contains commonly used text and their translations. **Authors**: Gagandeep Singh """ self.stdout.write('* Creating database entries for languages & translations (App:languages)...') from languages.models import Language, Translation # (a) Set 'Language' database self.stdout.write("\tLanguages: preparing data...") # Read json database with codecs.open(os.path.join(DIR_DB, "db_languages.json"), 'r', encoding="utf-8") as file_db: data_langs = json.load(file_db) # Loop & make entries counter = 0 for row in data_langs: list_new_langs = [] if not Language.objects.filter(code=row['code']).exists(): list_new_langs.append( Language( code = row['code'], name = row['name'], name_native = row['name_native'], description = row['description'], active = row['active'], ) ) counter += 1 if len(list_new_langs): Language.objects.bulk_create(list_new_langs) self.stdout.write("\tLanguages: {} languages inserted.".format(counter)) # (b) Set 'Translations' database self.stdout.write("\tTranslations: Inserting translations...") # Read json database with codecs.open(os.path.join(DIR_DB, "db_translations.json"), 'r', encoding="utf-8") as file_db: data_trans = json.load(file_db) # Loop & make entries counter = 0 for row in data_trans: if not Translation.objects.filter(unique_id=row['unique_id']).count(): trans = Translation(**row) trans.save() counter += 1 self.stdout.write("\tTranslations: {} translations inserted.".format(counter))
def test_search(self): language, created = Language.from_dict({"name": "English"}) self.assertTrue(created) self.assertIsNotNone(language.id) language, created = Language.from_dict({"name": "German"}) self.assertTrue(created) self.assertIsNotNone(language.id) language, created = Language.from_dict({"name": "Spanish"}) self.assertTrue(created) self.assertIsNotNone(language.id) languages = Language.objects.all() self.assertEquals(3, len(languages)) languages = Language.search("ish") self.assertEquals(2, len(languages)) languages = Language.search("an") self.assertEquals(2, len(languages))
def add_language(request): if request.method == 'POST': if request.body is None or len(request.body.decode('utf-8')) == 0: return JsonResponse(data=create_resp_dict(False, INCORRECT_REQUEST), safe=False, status=HTTPStatus.BAD_REQUEST) else: try: print(client) body_data = json.loads(request.body.decode('utf-8')) language_data = body_data['language_data'] for data in language_data: lang = Language.objects(text=data['text']).first() lang.update(**data).save() return JsonResponse(data=create_resp_dict(True, LANGUAGE_ADDED), safe=False, status=HTTPStatus.OK) except Exception as e: return JsonResponse(data=create_resp_dict(False, e), safe=False, status=HTTPStatus.OK)
def create_language(request): if request.method == 'POST': if request.body is None or len(request.body.decode('utf-8')) == 0: return JsonResponse(data=create_resp_dict(False, INCORRECT_REQUEST), safe=False, status=HTTPStatus.BAD_REQUEST) else: try: print(client) body_data = json.loads(request.body.decode('utf-8')) language_data = body_data['language_data'] for data in language_data: # print(data['english']) Language(text=data['text'], english=data['english']).save() return JsonResponse(data=create_resp_dict(True, CATEGORY_ADDED), safe=False, status=HTTPStatus.OK) except Exception as e: return JsonResponse(data=create_resp_dict(False, e), safe=False, status=HTTPStatus.OK)
def edit(self: T, field: str, value: Union[str, datetime.date], *args, **kwargs): """Change field by given value.""" fields = [ "issue", "publishing_date", "publishing-date", "cover", "language", "file", "link", ] assert field in fields if field == "issue": self.issue = value elif field == "publishing_date" or field == "publishing-date": self.publishing_date = value elif field == "cover": self.cover_image.save( os.path.basename(str(value)), DJFile(open(str(value), "rb")) ) elif field == "language" and isinstance(value, str): language = Language.get_or_create(value) if self.languages.filter(pk=language.pk).exists(): self.languages.remove(language) else: self.languages.add(language) elif field == "link" and isinstance(value, str): link = Link.get_or_create(value) if self.links.filter(pk=link.pk).exists(): self.links.remove(link) else: self.links.add(link) elif field == "file" and isinstance(value, str): file, created = File.from_dict({"path": value}) if self.files.filter(pk=file.pk).exists(): self.files.remove(file) file.delete() else: self.files.add(file) self.save(*args, **kwargs)
def from_dict(cls: Type[T], data: Dict) -> Tuple[T, bool]: """Create from dict. Returns True if was crated, i. e. was not found in the DB. """ defaults: Dict = {} if "journal" in data and data["journal"]: defaults["journal"] = Journal.from_dict(data["journal"])[0] if "volume" in data and data["volume"]: defaults["volume"] = data["volume"] if "publishing_date" in data and data["publishing_date"]: defaults["publishing_date"] = datetime.datetime.strptime( data["publishing_date"], "%Y-%m-%d").date() if "bibtex" in data and data["bibtex"]: defaults["bibtex"] = data["bibtex"] paper, created = Paper.objects.get_or_create(title=data["title"], defaults=defaults) if "authors" in data and data["authors"]: for i in data["authors"]: paper.authors.add(Person.from_dict(i)[0]) if "languages" in data and data["languages"]: for i in data["languages"]: paper.languages.add(Language.from_dict(i)[0]) if "links" in data and data["links"]: for i in data["links"]: paper.links.add(Link.from_dict(i)[0]) if "acquisitions" in data and data["acquisitions"]: for i in data["acquisitions"]: Acquisition.from_dict(i, paper) if "files" in data and data["files"]: for i in data["files"]: File.from_dict(i, paper) if "reads" in data and data["reads"]: for i in data["reads"]: Read.from_dict(i, paper) paper.save() return paper, created
def test_from_to_dict(self): author1, created = Person.from_dict({"name": "John Doe"}) self.assertTrue(created) self.assertIsNotNone(author1.id) author2, created = Person.from_dict({"name": "Jane Doe"}) self.assertTrue(created) self.assertIsNotNone(author2.id) journal, created = Journal.from_dict({"name": "Science Journal"}) self.assertTrue(created) self.assertIsNotNone(journal.id) paper, created = Paper.objects.get_or_create( title="Random new stuff", journal=journal, volume="1/2021" ) paper.authors.add(author1) paper.authors.add(author2) self.assertTrue(created) self.assertIsNotNone(paper.id) self.assertEquals( { "title": "Random new stuff", "authors": [ {"name": "Jane Doe", "links": None}, {"name": "John Doe", "links": None}, ], "journal": {"name": "Science Journal", "links": None}, "volume": "1/2021", "publishing_date": None, "languages": None, "files": None, "bibtex": None, "links": None, "acquisitions": None, "reads": None, }, paper.to_dict(), ) self.assertEquals( (paper, False), Paper.from_dict( { "title": "Random new stuff", "authors": [ {"name": "Jane Doe", "links": None}, {"name": "John Doe", "links": None}, ], "journal": {"name": "Science Journal", "links": None}, "volume": "1/2021", "publishing_date": None, "languages": None, "files": None, "bibtex": None, "links": None, "acquisitions": None, "reads": None, } ), ) self.assertEquals( (paper, False), Paper.from_dict( { "title": "Random new stuff", "authors": [ {"name": "Jane Doe"}, {"name": "John Doe"}, ], "journal": {"name": "Science Journal"}, "volume": "1/2021", } ), ) language, created = Language.from_dict({"name": "Englisch"}) self.assertTrue(created) self.assertIsNotNone(language.id) link, created = Link.from_dict({"url": "https://example.com"}) self.assertTrue(created) self.assertIsNotNone(link.id) paper, created = Paper.objects.get_or_create( title="Random Science stuff", publishing_date=datetime.strptime("2021-01-01", "%Y-%m-%d").date(), journal=journal, volume="2/2021", ) paper.authors.add(author1) paper.authors.add(author2) paper.languages.add(language) paper.links.add(link) self.assertTrue(created) self.assertIsNotNone(paper.id) acquisition, created = Acquisition.from_dict( {"date": "2021-01-02", "price": 10}, paper ) self.assertTrue(created) self.assertIsNotNone(acquisition.id) read, created = Read.from_dict( {"started": "2021-01-02", "finished": "2021-01-03"}, paper ) self.assertTrue(created) self.assertIsNotNone(read.id) self.assertEquals( { "title": "Random Science stuff", "authors": [ {"name": "Jane Doe", "links": None}, {"name": "John Doe", "links": None}, ], "journal": {"name": "Science Journal", "links": None}, "volume": "2/2021", "publishing_date": "2021-01-01", "languages": [{"name": "Englisch"}], "files": None, "bibtex": None, "links": [{"url": "https://example.com"}], "acquisitions": [{"date": "2021-01-02", "price": 10.0}], "reads": [{"started": "2021-01-02", "finished": "2021-01-03"}], }, paper.to_dict(), ) self.assertEquals( (paper, False), Paper.from_dict( { "title": "Random Science stuff", "authors": [ {"name": "Jane Doe", "links": None}, {"name": "John Doe", "links": None}, ], "journal": {"name": "Science Journal", "links": None}, "volume": "2/2021", "publishing_date": "2021-01-01", "languages": [{"name": "Englisch"}], "files": None, "bibtex": None, "links": [{"url": "https://example.com"}], "acquisitions": [{"date": "2021-01-02", "price": 10.0}], "reads": [{"started": "2021-01-02", "finished": "2021-01-03"}], } ), ) self.assertEquals( (paper, False), Paper.from_dict( { "title": "Random Science stuff", "authors": [ {"name": "Jane Doe"}, {"name": "John Doe"}, ], "journal": {"name": "Science Journal"}, "volume": "2/2021", "publishing_date": "2021-01-01", "languages": [{"name": "Englisch"}], "links": [{"url": "https://example.com"}], "acquisitions": [{"date": "2021-01-02", "price": 10.0}], "reads": [{"started": "2021-01-02", "finished": "2021-01-03"}], } ), ) with NamedTemporaryFile() as f: f.write(b"Lorem ipsum dolorem") file, created = File.from_dict({"path": f.name}) self.assertTrue(created) self.assertIsNotNone(file.id) self.assertEquals( os.path.basename(f.name), os.path.basename(file.file.name) ) paper, created = Paper.objects.get_or_create( title="Boring Science stuff", publishing_date=datetime.strptime("2021-02-01", "%Y-%m-%d").date(), journal=journal, volume="2/2021", ) paper.authors.add(author1) paper.authors.add(author2) paper.languages.add(language) paper.links.add(link) paper.files.add(file) paper.save() self.assertTrue(created) self.assertIsNotNone(paper.id) self.assertEquals( { "title": "Boring Science stuff", "authors": [ {"name": "Jane Doe", "links": None}, {"name": "John Doe", "links": None}, ], "journal": {"name": "Science Journal", "links": None}, "volume": "2/2021", "publishing_date": "2021-02-01", "languages": [{"name": "Englisch"}], "bibtex": None, "links": [{"url": "https://example.com"}], "files": [ { "path": os.path.join( settings.MEDIA_ROOT, "papers", str(paper.pk), os.path.basename(f.name), ) } ], "acquisitions": None, "reads": None, }, paper.to_dict(), )
class MenuAdminCreateForm(forms.ModelForm): model = Menu status = forms.ChoiceField(choices=Menu.LIST_STATUSES) name = forms.CharField() lang = forms.ChoiceField(choices=Language.get_list(True))
def _book(args: Namespace, file: TextIO = sys.stdout): book: Optional[Book] = None if args.subparser == "add": book, created = Book.from_dict({ "title": args.title, "authors": [Person.get_or_create(author).to_dict() for author in args.author], "series": Series.get_or_create(args.series).to_dict() if args.series else None, "volume": args.volume, "genres": [Genre.get_or_create(genre).to_dict() for genre in args.genre], "links": [Link.get_or_create(link).to_dict() for link in args.link], }) if created: stdout.write( _('Successfully added book "%(title)s" with id "%(pk)d".') % { "title": book.title, "pk": book.pk }, "=", file=file, ) book.print(file) else: stdout.write( _('The book "%(title)s" already exists with id "%(pk)d", aborting...' ) % { "title": book.title, "pk": book.pk }, "", file=file, ) elif args.subparser == "delete": book = Book.get(args.book) if book: book.delete() stdout.write( _('Successfully deleted book "%(title)s" with id "%(pk)d".') % { "title": book.title, "pk": book.pk }, "", file=file, ) else: stdout.write(_("No book found."), "", file=file) elif args.subparser == "edit": book = Book.get(args.book) if book: book.edit(args.edit_subparser, args.value) stdout.write( _('Successfully edited book "%(title)s" with id "%(pk)d".') % { "title": book.title, "pk": book.pk }, "=", file=file, ) book.print(file) else: stdout.write(_("No book found."), "", file=file) elif args.subparser == "edition": book = Book.get(args.book) if book: if args.edition_subparser == "acquisition" and book: edition = Edition.get(args.edition, book) acquisition: Optional[Acquisition] = None if args.acquisition_subparser == "add" and edition: acquisition, created = Acquisition.from_dict( { "date": args.date, "price": args.price }, edition) if created: stdout.write( _('Successfully added acquisition with id "%(pk)d".' ) % {"pk": acquisition.pk}, "=", file=file, ) else: stdout.write( _('The acquisition already exists with id "%(pk)d".' ) % {"pk": acquisition.pk}, "", file=file, ) acquisition.print(file) elif args.acquisition_subparser == "delete" and edition: acquisition = Acquisition.get(args.acquisition, editions=edition) if acquisition: acquisition.delete(acquisition) stdout.write( _('Successfully deleted acquisition with id "%(pk)d".' ) % {"pk": acquisition.pk}, "", file=file, ) else: stdout.write(_("No acquisition found."), "", file=file) elif args.acquisition_subparser == "edit" and edition: acquisition = Acquisition.get(args.acquisition, editions=edition) if acquisition: acquisition.edit(args.field, args.value) stdout.write( _('Successfully edited acquisition with id "%(pk)d".' ) % {"pk": acquisition.pk}, "=", file=file, ) acquisition.print(file) else: stdout.write(_("No acquisition found."), "", file=file) else: stdout.write([_("No edition found.")], "", file=file) elif args.edition_subparser == "add" and book: edition, created = Edition.from_dict( { "alternate_title": args.alternate_title, "isbn": args.isbn, "publishing_date": args.publishing_date, "cover": args.cover, "binding": Binding.get_or_create(args.binding).to_dict() if args.binding else None, "publisher": Publisher.get_or_create(args.publisher).to_dict() if args.publisher else None, "persons": [ Person.get_or_create(person).to_dict() for person in args.person ], "languages": [ Language.get_or_create(language).to_dict() for language in args.language ], "links": [ Link.get_or_create(link).to_dict() for link in args.link ], "files": [{ "path": file } for file in args.file], }, book, ) if created: stdout.write( _('Successfully added edition "%(edition)s" with id "%(pk)d".' ) % { "edition": edition, "pk": edition.pk }, "=", file=file, ) edition.print(file) else: stdout.write( _('The edition "%(edition)s" already exists with id "%(pk)d",' + " aborting...") % { "edition": edition, "pk": edition.pk }, "", file=file, ) elif args.edition_subparser == "edit" and book: edition = Edition.get(args.edition, book) if edition: edition.edit(args.edit_subparser, args.value) stdout.write( _('Successfully edited edition "%(edition)s" with id "%(pk)d".' ) % { "edition": edition, "pk": edition.pk }, "=", file=file, ) edition.print(file) else: stdout.write(_("No edition found."), "", file=file) elif args.edition_subparser == "info" and book: edition = Edition.get(args.edition, book) if edition: edition.print(file) else: stdout.write(_("No edition found."), "", file=file) elif args.edition_subparser == "list" and book: if args.shelf: editions = Edition.list.by_shelf(args.shelf, book) elif args.search: editions = Edition.list.by_term(args.search, book) else: editions = Edition.objects.filter(book=book) stdout.write( [ _("Id"), _("Title"), _("Binding"), _("ISBN"), _("Publishing date"), ], "=", [0.05, 0.55, 0.7, 0.85], file=file, ) for i, has_next in lookahead(editions): stdout.write( [ i.pk, i.get_title(), i.binding, i.isbn, i.publishing_date ], "_" if has_next else "=", [0.05, 0.55, 0.7, 0.85], file=file, ) elif args.edition_subparser == "open" and book: edition = Edition.get(args.edition, book) if edition: edition_file = edition.files.get(pk=args.file) path = settings.MEDIA_ROOT / edition_file.file.path if sys.platform == "linux": os.system(f'xdg-open "{path}"') else: os.system(f'open "{path}"') else: stdout.write(_("No edition found."), "", file=file) elif args.edition_subparser == "read" and book: edition = Edition.get(args.edition, book) read: Optional[Read] = None if args.read_subparser == "add" and edition: read, created = Read.from_dict( { "started": args.started, "finished": args.finished }, edition) if created: stdout.write( _('Successfully added read with id "%(pk)d".') % {"pk": read.pk}, "=", file=file, ) else: stdout.write( _('The read already exists with id "%(pk)d".') % {"pk": read.pk}, "", file=file, ) read.print(file) elif args.read_subparser == "delete" and edition: read = Read.get(args.read, editions=edition) if read: read.delete() stdout.write( _('Successfully deleted read with id "%(pk)d".') % {"pk": read.pk}, "", file=file, ) else: stdout.write(_("No read found."), "", file=file) elif args.read_subparser == "edit" and edition: read = Read.get(args.read, editions=edition) if read: read.edit(args.field, args.value) stdout.write( _('Successfully edited read with id "%(pk)d".') % {"pk": read.pk}, "=", file=file, ) read.info(file) else: stdout.write(_("No read found."), "", file=file) else: stdout.write(_("No edition found."), "", file=file) else: stdout.write(_("No book found."), "", file=file) elif args.subparser == "info": book = Book.get(args.book) if book: book.print(file) else: stdout.write(_("No book found."), "", file=file) elif args.subparser == "list": if args.search: books = Book.search(args.search) elif args.shelf: books = Book.by_shelf(args.shelf) else: books = Book.objects.all() stdout.write( [_("Id"), ("Title"), _("Authors"), _("Series"), _("Volume")], "=", [0.05, 0.5, 0.75, 0.9], file=file, ) for i, has_next in lookahead(books): stdout.write( [ i.pk, i.title, " ,".join(f"{a}" for a in i.authors.all()), i.series.name if i.series else "", i.volume, ], "_" if has_next else "=", [0.05, 0.5, 0.75, 0.9], file=file, )
def _paper(args: Namespace, file: TextIO = sys.stdout): paper: Optional[Paper] = None if args.subparser == "acquisition": paper = Paper.get(args.paper) acquisition: Optional[Acquisition] = None if args.acquisition_subparser == "add" and paper: acquisition, created = Acquisition.from_dict( { "date": args.date, "price": args.price }, paper) if created: stdout.write( _('Successfully added acquisition with id "%(pk)d".') % {"pk": acquisition.pk}, "=", file=file, ) else: stdout.write( _('The acquisition already exists with id "%(pk)d".') % {"pk": acquisition.pk}, "", file=file, ) acquisition.print(file) elif args.acquisition_subparser == "delete" and paper: acquisition = Acquisition.get(args.acquisition, papers=paper) if acquisition: acquisition.delete(acquisition) stdout.write( _('Successfully deleted acquisition with id "%(pk)d".') % {"pk": acquisition.pk}, "", file=file, ) else: stdout.write(_("No acquisition found."), "", file=file) elif args.acquisition_subparser == "edit" and paper: acquisition = Acquisition.get(args.acquisition, papers=paper) if acquisition: acquisition.edit(args.field, args.value) stdout.write( _('Successfully edited acquisition with id "%(pk)d".') % {"pk": acquisition.pk}, "=", file=file, ) acquisition.print(file) else: stdout.write(["No acquisition found."], "", file=file) else: stdout.write(_("No paper found."), "", file=file) elif args.subparser == "add": paper, created = Paper.from_dict({ "title": args.title, "authors": [Person.get_or_create(author).to_dict() for author in args.author], "publishing_date": args.publishing_date, "journal": Journal.get_or_create(args.journal).to_dict() if args.journal else None, "volume": args.volume, "languages": [ Language.get_or_create(language).to_dict() for language in args.language ], "links": [Link.get_or_create(link).to_dict() for link in args.link], "files": [{ "path": file } for file in args.file], }) if created: stdout.write( _('Successfully added paper "%(title)s" with id "%(pk)d".') % { "title": paper.title, "pk": paper.pk }, "=", file=file, ) else: stdout.write( _('The paper "%(title)s" already exists with id "%(pk)d".') % { "title": paper.title, "pk": paper.pk }, "", file=file, ) paper.print(file) elif args.subparser == "delete": paper = Paper.get(args.paper) if paper: paper.delete() stdout.write( _('Successfully deleted paper with id "%(title)s".') % {"title": paper.title}, "", file=file, ) else: stdout.write(_("No paper found."), "", file=file) elif args.subparser == "edit": paper = Paper.get(args.paper) if paper: paper.edit(args.edit_subparser, args.value) stdout.write( _('Successfully edited paper "%(title)s" with id "%(pk)d".') % { "title": paper.title, "pk": paper.pk }, "", file=file, ) paper.print(file) else: stdout.write(_("No paper found."), "", file=file) elif args.subparser == "info": paper = Paper.get(args.paper) if paper: paper.print(file) else: stdout.write(_("No paper found."), "", file=file) elif args.subparser == "list": if args.search: papers = Paper.search(args.search) elif args.shelf: papers = Paper.by_shelf(args.shelf) else: papers = Paper.objects.all() stdout.write( [_("Id"), _("Name"), _("Journal"), _("Volume")], "=", [0.05, 0.7, 0.85], file=file, ) for i, has_next in lookahead(papers): stdout.write( [i.pk, i.name, i.journal.name, i.volume], "_" if has_next else "=", [0.05, 0.7, 0.85], file=file, ) elif args.subparser == "open": paper = Paper.get(args.paper) if paper: paper_file = paper.files.get(pk=args.file) path = settings.MEDIA_ROOT / paper_file.file.path if sys.platform == "linux": os.system(f'xdg-open "{path}"') else: os.system(f'open "{path}"') else: stdout.write(_("No paper found."), "", file=file) elif args.subparser == "parse": for paper, created in Paper.from_bibfile(args.bibfile, args.file): if created: stdout.write( _('Successfully added paper "%(title)s" with id "%(pk)d".') % { "title": paper.title, "pk": paper.pk }, file=file, ) if args.acquisition: acquisition, created = Acquisition.from_dict( {"date": datetime.date.today()}, paper) if created: stdout.write( _('Successfully added acquisition with id "%(pk)d".' ) % {"pk": acquisition.pk}, "=", file=file, ) else: stdout.write( _('The acquisition already exists with id "%(pk)d".' ) % {"pk": acquisition.pk}, "=", file=file, ) else: stdout.write( _('The paper "%(title)s" already exists with id "%(pk)d".') % { "title": paper.title, "pk": paper.pk }, "=", file=file, ) paper.print(file) elif args.subparser == "read": paper = Paper.get(args.paper) read: Optional[Read] = None if args.read_subparser == "add" and paper: read, created = Read.from_dict( { "started": args.started, "finished": args.finished }, paper) if created: stdout.write( _('Successfully added read with id "%(pk)d".') % {"pk": read.pk}, "=", file=file, ) else: stdout.write( _('The read already exists with id "%(pk)d".') % {"pk": read.pk}, "", file=file, ) read.print(file) elif args.read_subparser == "delete" and paper: read = Read.get(args.read, papers=paper) if read: read.delete() stdout.write( _('Successfully deleted read with id "%(pk)d".') % {"pk": read.pk}, "", file=file, ) else: stdout.write(_("No read found."), "", file=file) elif args.read_subparser == "edit" and paper: read = Read.get(args.read, papers=paper) if read: read.edit(args.field, args.value) stdout.write( _('Successfully edited read with id "%(pk)d".') % {"pk": read.pk}, "=", file=file, ) read.info(file) else: stdout.write(_("No read found."), "", file=file) else: stdout.write(_("No paper found."), "", file=file)