Exemplo n.º 1
0
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/")
Exemplo n.º 2
0
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"))
Exemplo n.º 3
0
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")
Exemplo n.º 4
0
 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()
Exemplo n.º 5
0
 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)
Exemplo n.º 6
0
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")
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
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))
Exemplo n.º 9
0
    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()
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
    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()
Exemplo n.º 12
0
 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 ""}. '))
Exemplo n.º 13
0
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")
Exemplo n.º 14
0
    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)
Exemplo n.º 15
0
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")
Exemplo n.º 16
0
    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))
Exemplo n.º 17
0
 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)
Exemplo n.º 18
0
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
Exemplo n.º 19
0
 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")
Exemplo n.º 20
0
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') 
Exemplo n.º 21
0
    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()
Exemplo n.º 22
0
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))
Exemplo n.º 23
0
 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)
Exemplo n.º 24
0
 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()
Exemplo n.º 25
0
 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]
Exemplo n.º 26
0
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 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()
Exemplo n.º 28
0
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
    }]
Exemplo n.º 29
0
    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")
Exemplo n.º 30
0
 def setUp(self):
     self.author = Author(name='John Doe')
     self.author.save()
Exemplo n.º 31
0
 def test_author(self):
     author = Author(name="Daniel Cow", contact="9879344")
     self.assertEqual(author.name, "Daniel Cow")
     self.assertEqual(author.contact, "9879344")
Exemplo n.º 32
0
# 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()