def updateauthor(request): if request.method == "POST": title = request.POST["Title"] authorid = request.POST["AuthorID"] name = request.POST["Name"] age = request.POST["Age"] country = request.POST["Country"] try: Author.objects.get(AuthorID = authorid) except: newauthor = Author(AuthorID = authorid, Name = name, Age = age, Country = country) newauthor.save() Book.objects.filter(Title = title).update(AuthorID = newauthor) return HttpResponseRedirect("/booklist/") else: author = Author.objects.get(AuthorID = authorid) author.Name = name author.Age = age author.Country = country author.save() Book.objects.filter(Title = title).update(AuthorID = author) return HttpResponseRedirect("/booklist/")
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 add(request): if request.POST and request.POST['Name'] and request.POST['Title'] and request.POST['ISBN_PK'] and request.POST['AuthorID_FK']: post = request.POST new_author=Author( AuthorID_FK = post['AuthorID_FK'], Name = post['Name'], Age = post['Age'], Country = post['Country'], ) tmp = list(Author.objects.filter(Name=post['Name'])) tmp0 = list(Author.objects.filter(AuthorID_FK=post['AuthorID_FK'])) if tmp0 != []: return render_to_response("addauerror.html") else: if tmp == [] : new_author.save() else: new_author=Author.objects.filter(Name=post['Name'])[0] new_book = Book( ISBN_PK = post["ISBN_PK"], Title = post["Title"], AuthorID_FK = new_author, Publisher = post["Publisher"], PublishDate = post["PublishDate"], Price = post["Price"], ) tmp1 = list(Book.objects.filter(ISBN_PK=post['ISBN_PK'])) if tmp1!=[]: return render_to_response("addboerror.html") else: new_book.save() return render_to_response("addbosuccess.html") else: return render_to_response("addboerror1.html")
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 post(self, request): a = Author(name=request.POST['author_name']) try: a.save() except Exception as e: output = "Whoops! There was an error: " + str(e) else: output = 'Success! We added an author named: ' + a.name return HttpResponse(output)
def add_author(request): if request.POST: post = request.POST new_author = Author( AuthorID=post["AuthorID"], Name = post["Name"], Age = post["Age"], Country = post["Country"]) new_author.save() return render_to_response("add_author.html")
def test_bulk_create_invalid_authors(self): invalid_authors_names = [ self.existing_author.name, '', ' ', '\t', None ] for author_name in invalid_authors_names: with self.subTest(author_name=author_name): with self.assertRaises(ValidationError): Author.bulk_create([author_name]) self.assertEqual(self.authors.count(), self.authors_count_before)
class AuthorTest(TestCase): def setUp(self): self.author = Author(name='John Doe') self.author.save() def test_create(self): 'Author may be saved' self.assertEqual(1, self.author.pk) def test_str(self): 'Author string representation may be the name.' self.assertEqual('John Doe', str(self.author))
def init_author(self): # Remove existing Author models from the DB. Author.objects.all().delete() first_names = ["Fred", "George", "Juan", "Pablo", "Rohit", "Graham", "Jessica"] last_names = ["Salvador", "Gonzales", "Miller", "Walker", "Crofford", "Adams"] for i in range(1, 100): # Create a random name for the author. name = self.rand_join(' ', first_names, last_names) # Save the author in the DB. author = Author(name=name) author.save()
def add_author(request): if request.method == 'GET': output = FORM_HTML % request.path else: a = Author(name=request.POST['author_name']) try: a.save() except Exception as e: output = "Whoops! There was an error: " + str(e) else: output = 'Success! We added an author named: ' + a.name return HttpResponse(output)
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()
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 insertauthor(request): if request.method == "POST": authorID = request.POST["AuthorID"] newauthor = Author(AuthorID = request.POST["AuthorID"], Name = request.POST["Name"], Age = request.POST["Age"], Country = request.POST["Country"]) newauthor.save() newbook = Book(ISBN = request.POST["ISBN"], Title = request.POST["Title"], AuthorID = Author.objects.get(AuthorID = authorID), Publisher = request.POST["Publisher"], PublishDate = request.POST["PublishDate"], Price = request.POST["Price"]) newbook.save() return HttpResponseRedirect("/booklist/") return render_to_response("insertauthor.html")
def import_authors_from_file_and_save_to_database( self, filepath: str) -> List[Author]: names = self.get_authors_names_from_file(filepath) try: return Author.bulk_create(names) except ValidationError as e: raise CommandError(e.messages)
def addauthor(request): if request.POST and request.POST['Name'] and request.POST['AuthorID_FK']: post = request.POST new_author=Author( AuthorID_FK = post['AuthorID_FK'], Name = post['Name'], Age = post['Age'], Country = post['Country'], ) tmp2 = list(Author.objects.filter(AuthorID_FK=post['AuthorID_FK'])) if tmp2!=[]: return render_to_response("addauerror.html") else: new_author.save() return render_to_response("addausuccess.html") else: return render_to_response("addauerror1.html")
def test_bulk_create_valid_authors(self): new_authors_names = [ 'William Shakespeare', 'William Faulkner', 'Henry James', 'Jane Austen' ] new_authors = Author.bulk_create(new_authors_names) self.assertEqual(self.authors.count(), self.authors_count_before + len(new_authors))
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 addwriter(request): AUTHOR = Author() AUTHOR.AuthorID = request.POST['author_ID'] AUTHOR.Age = request.POST['author_age'] AUTHOR.Country = request.POST['author_country'] AUTHOR.Name = request.POST['author_name'] AUTHOR.save() AuthorList = Author.objects.all() return render_to_response('addbook.html')
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()
class BookTest(TestCase): 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() def test_create(self): 'Book instance may be saved' self.assertEqual(1, self.book.pk) def test_str(self): 'Book string representation may be the name.' self.assertEqual('Any book', str(self.book))
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 save(self, file_csv): records = csv.reader(file_csv) next(records) # skip the first line for line in records: if len(line) == 7: title = line[0] author_lf = line[2] isbn = line[4] or None isbn13 = line[5] or None yr_published = line[6] or None author = Author.create_from_csv(author_lf) book = Book(title=title, isbn=isbn, isbn13=isbn13, year_published=yr_published) book.save() book.authors = author 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 AddBook2(request): AUTHOR = Author() AUTHOR.AulthorID = request.POST['author_ID'] AUTHOR.Age = request.POST['author_age'] AUTHOR.Country = request.POST['author_country'] AUTHOR.Name = request.POST['author_name'] AUTHOR.save() BOOK = Book() BOOK.Title = request.POST['book_name'] BOOK.AulthorID_id = request.POST['author_ID'] BOOK.Publisher = request.POST['book_publisher'] BOOK.PublishDate = request.POST['book_date'] BOOK.Price = float(request.POST['book_price']) BOOK.save() BookList = Book.objects.all() return render_to_response('BookList.html',{'BookList':BookList})
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): 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()
def test_author(self): author = Author(name="Daniel Cow", contact="9879344") self.assertEqual(author.name, "Daniel Cow") self.assertEqual(author.contact, "9879344")
# 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()