def handle(self, *args, **options): filename = options['file'] if not filename: raise CommandError('No file was specified.') errors = False with open(filename, 'r', newline='', encoding='utf-8') as file: reader = csv.DictReader(file, delimiter=';') try: authors = [Author(name=row['name']) for row in reader] except KeyError: # File structure is incorrect, its first column must be "name". errors = True if errors: self.stdout.write( self.style.ERROR('File has incorrect format. It' 's missing a "name" column.')) return created = Author.objects.bulk_create(authors, ignore_conflicts=True) count = len(created) if not count: self.stdout.write( self.style.WARNING( 'File was imported but no author was registered.')) return self.stdout.write( self.style.SUCCESS( f'Successfully imported author file and registered {count} ' f'author{"s" if count != 1 else ""}. '))
def accept_suggested_book(request, pk): """View function for accepting a SuggestedBook and creating a Book.""" suggested_book = get_object_or_404(SuggestedBook, pk=pk) # if the request is a GET (the user requests the /suggestions/<book>/accept url) # create a Book from the SuggestedBook object and remove SuggestedBook if request.method == 'GET': # check to see if author already exists author = Author.objects.filter(name=suggested_book.author).first() if not author: author = Author(name = suggested_book.author) author.save() Book( title = suggested_book.title, author = author, url = suggested_book.url, description = suggested_book.description ).save() suggested_book.delete() messages.success(request, 'You accepted the suggested book.') # redirect to a new URL: return HttpResponseRedirect(request.GET.get("next"))
def handle(self, *args, **options): path = options['path'] with open(path, 'r') as f: for i, name in enumerate(f.readlines()): if i == 0: continue author = Author(name=self.clear_string(name)) author.save()
def handle(self, *args, **options): sheet_name = options.get('sheet_name')[0] authors = [] with open(sheet_name, 'r') as f: r = csv.reader(f) for row in r: authors.append(Author(name=row[0])) Author.objects.bulk_create(authors)
async def test_query_book(mocker): class AsyncMock(MagicMock): async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) book_id = '1' double = mocker.patch.object(PostgresPersistence, 'filter', new_callable=AsyncMock) author = Author(name='martin fowler') category = Category(title='software engineering') book = Book(id=1, external_id=book_id, title='refactoring', subtitle='improving the design of existing code', authors=[author], categories=[category], published_year=1999, editor=Editor(name='addison wesley'), description='whatever', saved=True) double.return_value = [book] book_DTO = BookDTO( external_id=book_id, title='refactoring', subtitle='improving the design of existing code', authors=[{ 'name': 'martin fowler' }], categories=[{ 'title': 'software engineering' }], published_year=1999, editor={'name': 'addison wesley'}, description='whatever', ) insert_controller = InsertBookController(data=book_DTO) await insert_controller.insert() controller = QueryBookController() books = await controller.filter(external_id=book_id) book = books[0] double.assert_called_once_with(external_id=book_id) assert book.id assert book.external_id == book_id assert book.title == 'refactoring' assert book.subtitle == 'improving the design of existing code' assert book.authors[0].name == 'martin fowler' assert book.categories[0].title == 'software engineering' assert book.published_year == 1999 assert book.editor.name == 'addison wesley' assert book.description == 'whatever' assert book.saved is True
def handle(self, *args, **options): csv_file = options.get('csv_file') try: reader = csv.DictReader(csv_file) new_authors = [Author(name=row.get('name').strip()) for row in reader] except Exception as e: self.stderr.write(f"Error on text extraction: {str(e)}") return Author.objects.bulk_create(new_authors, ignore_conflicts=True) self.stdout.write("Authors were created")
def setUp(self): self.author = Author(name='John Doe') self.author.save() self.category = Category(description='Comedy', ) self.category.save() self.book = Book(title='Any book', author=self.author, category=self.category, pages=900, description='', published_in=datetime.today()) self.book.save()
async def filter(self, external_id): author = Author(name='martin fowler') category = Category(title='software engineering') book = Book( id=1, external_id=external_id, title='refactoring', subtitle='improving the design of existing code', authors=[author], categories=[category], published_year=1999, editor=Editor(name='addison wesley'), description='whatever', saved=True ) return [book]
def handle(self, *args, **options): BookCheckout.objects.all().delete() Book.objects.all().delete() with open( r"C:\Users\Brandon\code\class_raccoon\Code\Brandon\Django\labs\library\management\commands\books.json", "r") as f: books = json.loads(f.read()) for book in books: author = book['author'] if not Author.objects.filter(author=author).exists(): author = Author(author=author) author.save() else: author = Author.objects.get(author=author) title = book['title'] year_published = book['year'] url = book['link'] book = Book(title=title, year_published=year_published, author=author, url=url) book.save()
def test_query_book(loop): def book_api(request): pass routes = [Route('/book', book_api)] app = Starlette(routes=routes, debug=True) client = TestClient(app) book_id = 1 book = Book(id=book_id, title='refactoring', subtitle='improving the design of existing code', author=[Author(name='martin fowler')], category=[Category(title='software engineering')], published_year=1999, editor='addison wesley', description='whatever', saved=True) loop.run_until_complete(book.save()) query_response = client.get('/books', params={'title': 'refactoring'}) result = query_response.json()[0] assert result == [{ 'id': book_id, 'title': 'refactoring', 'subtitle': 'improving the design of existing code', 'author': [{ 'name': 'martin fowler' }], 'category': [{ 'title': 'software engineering' }], 'published_year': 1999, 'editor': 'addison wesley', 'description': 'whatever', 'saved': True }]
def handle(self, *args, **options): BooksCheckedOut.objects.all().delete() Book.objects.all().delete() with open("/Users/salamandersmith/Desktop/class_raccoon/Code/Alex/django/mysite/library/management/commands/books.json", "r") as f: books = json.loads(f.read()) for book in books: author = book['author'] if not Author.objects.filter(name=author).exists(): author = Author(name=author) author.save() else: author = Author.objects.get(name=author) #print(f"Author: {author.name}") title = book['title'] #print(f"Title: {title}") year_published = book['year'] #print(f"Year: {year_published}") pages = book['pages'] link = book['link'] country = book['country'] language = book['language'] book = Book(title=title, year_published=year_published, pages=pages, link=link, country=country, language=language) book.save() book.authors.add(author)
def handle(self, *args, **options): try: file = open(options["file"], "r") except FileNotFoundError: raise CommandError("File not found") except TypeError: raise CommandError("A csv type file is required") if not file.name.endswith(".csv"): raise CommandError("A csv type file is required") reader = csv.reader(file) next(reader) try: authors = Author.objects.bulk_create( [Author(name=row[0]) for row in reader if row]) self.stdout.write( self.style.SUCCESS( f"Successfully imported {len(authors)} author(s) from CSV file" )) except: raise CommandError("There was an error while importing authors")
def setUp(self): self.author = Author(name='John Doe') self.author.save()
# for creating foreign key relationship between the tables from sqlalchemy.orm import sessionmaker # to create engine that ties to physical location of DB from sqlalchemy import create_engine from library.models import Base, Book, Author print("creating an empty database") # create engine instance of DB pointing to a physical DB engine = create_engine('sqlite:///books-collection.db') # This will convert all new classes derived from Base into new tables in the database Base.metadata.create_all(engine) print("Loading 3 books to empty database") # create a session instance for writing and reading from database Base.metadata.bind = engine session = sessionmaker(bind=engine)() session.add(Book(title="Unknown", author="pi/2", genre="Mathematics")) session.add(Book(title="I Know", author="None", genre="Mathematics")) session.add(Book(title="Cradle of Life", author="God", genre="Everything")) session.add(Author(name="pi/2", age=39)) session.add(Author(name="None", age=19)) session.add(Author(name="God", age=200)) session.add(Author(name="Ashish", age=30)) session.commit()
def test_author(self): author = Author(name="Daniel Cow", contact="9879344") self.assertEqual(author.name, "Daniel Cow") self.assertEqual(author.contact, "9879344")