Beispiel #1
0
    def get_authors(self, authors_string):
        """ Get authors object from string names
        sepparated by commas

        Args:
            authors_string (String): names separated by commas

        Returns:
            List of Author: List of author objects
        """

        names = self.separate(authors_string)

        authors = []

        for name in names:
            try:
                author = Author.objects.get(name=name)
                authors.append(author)
            except Author.DoesNotExist:
                author = Author()
                author.name = name
                author.save()
                authors.append(author)

        return authors
Beispiel #2
0
    def get_authors_list(self, author_names):
        """
        Process the list of authors names, returns a
        list of corresponding objects, creates new objects
        if don't exist

        Args:
            author_names (List of String): Author names

        Returns:
            List of Athor: Author objects
        """

        authors = []

        for author_name in author_names:
            try:
                author = Author.objects.get(name=author_name)
                authors.append(author)
            except Author.DoesNotExist:
                author = Author()
                author.name = author_name
                author.save()
                authors.append(author)

        return authors
Beispiel #3
0
def author(request):
    #创建作者
    if request.POST:
        post = request.POST
        error = []
        if Author.objects.filter(Name = post["Name"]):
            return render_to_response('author.html', {'Error': True})
        AuthorID = post["AuthorID"]
        Name = post["Name"]
        Age = post["Age"]
        Country = post["Country"]
        if not AuthorID or not Name or not Age or not Country:
            if not AuthorID:
                error.append('作者ID没有填写')
            if not Name:
                error.append('作者姓名没有填写')
            if not Age:
                error.append('作者年龄没有填写')
            if not Country:
                error.append('作者国家没有填写')
            return render_to_response('author.html', {'error': error})
        else:
            newauthor = Author(AuthorID = AuthorID,Name = Name,Age = Age, Country = Country)
            newauthor.save()
    else:
        return render_to_response('author.html')
    return render_to_response('start.html')
Beispiel #4
0
def insert_Author(request,lastname):
    author = Author(last_name = lastname,first_name = 'liu',email = '*****@*****.**')
    author.save()
    ret = {
            "result": True,
            }
    return HttpResponse(simplejson.dumps(ret), mimetype="application/json")
    def handle(self, *args, **kwargs):
        Book.objects.all().delete()
        Author.objects.all().delete()

        for name, books in [
            ('Alice', [
                ('The Great Read', datetime(2020, 11, 1)),
                ('Super Duper Book', datetime(2020, 12, 15)),
            ]),
            ('Bob', [
                ('Mystery Novel', datetime(2020, 10, 1)),
                ('Hidden Secrets', datetime(2020, 11, 10)),
                ('The Great Reveal', datetime(2020, 11, 20)),
            ]),
            ('Charlie', [
                ('Secrets of the Place', datetime(2021, 2, 15)),
                ('Survival Guide', datetime(2020, 12, 15)),
            ]),
        ]:
            author = Author(name=name)
            author.save()

            for book in books:
                Book(
                    title=book[0],
                    published=book[1],
                    author=author,
                ).save()
Beispiel #6
0
    def test_book_list_view_GET(self):
        response = self.client.get(self.book_list_url)

        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'books/book_list.html')
        self.assertEquals(Book.objects.count(), 0)

        author = Author(
            fullName='Author'
        )
        author.save()
        isbn = IndustryIdentifier(
            isbn='ISBN_10',
            identifier='1234567890'
        )
        isbn.save()
        book = Book(
            title='Title',
            publishedDate='2019',
            pageCount=0,
            language='en',
            smallThumbnail='http://books.google.com/books/content?id=hFfhrCWiLSMC&printsec=frontcover&img=1&zoom=5&source=gbs_api',
            thumbnail='http://books.google.com/books/content?id=hFfhrCWiLSMC&printsec=frontcover&img=1&zoom=1&source=gbs_api'
        )
        book.save()
        book.authors.add(author)
        book.industryIdentifiers.add(isbn)
        
        self.assertEquals(Book.objects.count(), 1)
Beispiel #7
0
Datei: view.py Projekt: OA1366/sq
def addau(request):
    name = request.POST['name']
    age = request.POST['age']
    country = request.POST['country']
    author = Author(Name=name,Age=age,Country=country)
    author.save()
    return render_to_response('addbook.html',)
Beispiel #8
0
def appauthor(request,book_id):
    errors = []
    bid = book_id
    if 'name' in request.GET:
        name = request.GET['name']
        try:
            author = Author.objects.get(name = name)
        except Author.DoesNotExist:
            Au = Author.objects.all()
            tmp = Au[0].authorid
            for i in range(1,len(Au)):
                if Au[i].authorid>tmp:
                    tmp=Au[i].authorid
            for j in range(tmp):
                aid = j+1
                try:
                    per=Author.objects.get(authorid=aid)
                except Author.DoesNotExist:
                    break
            authorid = aid
            age = request.GET['age']
            country = request.GET['country']
            p1 = Author(authorid=authorid, name=name, age=age, country=country)
            p1.save()
            
            book = Book.objects.get(isbn=bid)
            book.authorid_id = authorid
            book.save()
            return render_to_response('appendsuccess.html')  
        else:
            errors.append('输入的作者在作者库中已经存在')
            render_to_response('appauthor.html', {'book_id': bid,'errors': errors})
    return render_to_response('appauthor.html',{'book_id': bid,'errors': errors})
Beispiel #9
0
 def setUp(self):
     books = Book.objects.bulk_create([
         Book(
             title="one",
             publication_date="1970-01-01",
             isbn="12345x",
             page_count=100,
             cover_photo="www.google.pl",
             publication_language="pl",
         ),
         Book(
             title="two",
             publication_date="1980-01-01",
             isbn="12346x",
             page_count=100,
             cover_photo="www.google.pl",
             publication_language="pl",
         ),
         Book(
             title="three",
             publication_date="1990-01-01",
             isbn="12347x",
             page_count=100,
             cover_photo="www.google.pl",
             publication_language="pl",
         ),
     ])
     authors = Author.objects.bulk_create([
         Author(name="Stephen King"),
         Author(name="Andriej Diakow"),
         Author(name="Dan Simmons"),
     ])
     for author, book in zip(authors, books):
         book.authors.add(author)
Beispiel #10
0
def addbook(require):
    if require.POST:
        post=request.POST
        a=Author(AuthorID=post['AID'],Name=post['AN'],Age=post['AA'],Country=post['AC'])
        a.save()
        b=Book(ISBN=post['BI'],Price=post['BP'],Publishdate=post['BPD'],Publisher=post['BPE'],Title=post['BT'],AuthorID=a)
        b.save()
    return HttpResponseRedirect("/home/")
Beispiel #11
0
 def _save_author(self):
     print('... Save Model Author ...')
     authors = self.df_books['author']
     for a in authors:
         author = Author(name=a)
         try:
             author.save()
         except IntegrityError:
             pass
Beispiel #12
0
def author_insert(request):    
    if request.POST:
        post=request.POST
        newauthor = Author(
             name = post["name"],
             age = post["age"],  
             country = post["country"])
        newauthor.save()
    return render_to_response("author_insert.html")  
Beispiel #13
0
Datei: view.py Projekt: OA1366/sq
def addAuthor(request):
    ID = request.POST['id']
    name = request.POST['name']
    age = request.POST['age']
    country = request.POST['country']
    author = Author(Name=name,Age=age,Country=country)
    author.save()
    book = Book.objects.get(id=ID)
    return render_to_response('update.html',locals())
Beispiel #14
0
def add_author(request):
    if request.GET:
        dic={'Name':request.GET['Name'],'Age':request.GET['Age'],'Country':request.GET['Country'],}
        my_Author=Author.objects.filter(AuthorId=request.GET['AuthorId'])
        if my_Author:
            dic['error']=True
            return render_to_response('add_author.html',dic)
        else:
            my_Author=Author(AuthorId=request.GET['AuthorId'],Name=request.GET['Name'],Age=request.GET['Age'],Country=request.GET['Country'],)
            my_Author.save()
            return HttpResponseRedirect('/add_success/')
    return render_to_response('add_author.html')
            
Beispiel #15
0
def getPostData(request):
    print request.POST
    print request.FILES
    if "name" in request.POST:
        lastname = request.POST['name']
    else:
        lastname = ""
    author = Author(last_name = lastname,first_name = 'liu',email = '*****@*****.**')
    author.save()
    ret = {
            "result": True,
            }
    return HttpResponse(simplejson.dumps(ret), mimetype="application/json")
Beispiel #16
0
def noauthor(request):
    try:
        if request.POST:
            post=request.POST
            newauthor = Author(
                 name = post['name'],
                 age = post["age"],  
                 country = post["country"])
            newauthor.save()
            return render_to_response("books_successed.html")
        return render_to_response("notfindauthor.html")
    except:
        return render_to_response("fail.html")  
Beispiel #17
0
def addBook(request):
    '''新加书籍, post request only'''
    if request.method != "POST":
        raise Http404
    
    authorName = request.REQUEST.get('authorName', None)
    authorDesc = request.REQUEST.get('authorDesc', None)
    bookName = request.REQUEST.get('bookName', None)
    bookPrice = request.REQUEST.get('bookPrice', None)
    bookIsbn = request.REQUEST.get('bookIsbn', None)
    bookPress = request.REQUEST.get('bookPress', None)
    bookDesc = request.REQUEST.get('bookDesc', None)
    bookBinding = request.REQUEST.get('bookBinding', None)
    bookPages = request.REQUEST.get('bookPages', None)
    bookSpic = request.REQUEST.get('bookSpic', None)
    bookMpic = request.REQUEST.get('bookMpic', None)
    bookLpic = request.REQUEST.get('bookLpic', None)
    bookPublishDate = request.REQUEST.get('bookPublishDate', None)
    stock = request.REQUEST.get('stock', None)
    category = request.REQUEST.get('category', None)
    
    author = Author(name=authorName, desc=authorDesc)
    author.save()
    
    price = float(''.join([ item for item in bookPrice if item in '1234567890.' ]))
    try:
        cate = Category.objects.get(label=category)
    except Category.DoesNotExist:
        raise Http404
    try:
        book = Book.objects.get(isbn=bookIsbn)
    except Book.DoesNotExist:
        book = Book()
    book.name=bookName
    book.author=author 
    book.price=price
    book.isbn=bookIsbn
    book.press=bookPress
    book.desc=bookDesc
    book.binding=bookBinding
    book.pages=bookPages
    book.spic=bookSpic
    book.mpic=bookMpic
    book.lpic=bookLpic 
    book.publish_date=bookPublishDate
    book.stock=stock
    book.category=cate
    book.save()
    utils.addMsg(request, messages.SUCCESS, '添加成功!')
    return HttpResponseRedirect('/manage/reg_book/')
Beispiel #18
0
def add_author_a(request):
	
	AuthorID = request.GET['AuthorID']
	Name = glob.Author_name
	Age = request.GET['Age']
	Country = request.GET['Country']
	if not AuthorID:
		return render_to_response('No_in.html')
	else:
		auth_add = Author(AuthorID = AuthorID, Name = Name, Age = Age, Country = Country)
		auth_add.save()
		book_add = Book(ISBN = glob.ISBN,Title = glob.Title,AuthorID = Author.objects.get(Name = Name),Publisher = glob.Publisher,\
				PublishDate = glob.PublishDate, Price = glob.Price)
		book_add.save()
	return render_to_response('First_page.html')
Beispiel #19
0
def author(request):
    disk={'text':''}
    if request.POST:
        if not request.POST['Name'] or request.POST['Age']\
        or request.POST['Country']:
            disk['text']='有缺省项!'
        else:
            new=Author(Name=request.POST['Name'],\
                       Age=request.POST['Age'],\
                       Country=request.POST['Country'],
                        )
            new.save()
            disk['text']='添加成功!'
    page=render_to_response('html/author.html',disk, context_instance=\
    RequestContext(request))
    return HttpResponse(page)
 def handle(self, *args, **options):
   Book.objects.all().delete()
   Publisher.objects.all().delete()
   Author.objects.all().delete()
   print('* Populating books...')
   orderedLS = OrderedDict(lifestudies)
   p = Publisher(name='Living Stream Ministry', code='LSM')
   p.save()
   a = Author(first_name='Witness', last_name='Lee')
   a.save()
   for b, c in orderedLS.items():
     print b
     b = Book(publisher=p, name=b, chapters=c)
     b.save()
     b.author = (a,)
     b.save()
    def handle(self, *args, **options):
        time_start = datetime.now()

        # Get parameters
        path = options.get("csv_file", "")
        colname = options.get("column_name", "name")

        # Check if file exists
        if not path or not os.path.exists(path):
            raise CommandError("File not found: %s" % path)

        # Read file
        try:
            content = read_csv(path,
                               usecols=[colname],
                               skip_blank_lines=True,
                               chunksize=1000000)
        except Exception as e:
            raise CommandError("Error reading the file: %s" % str(e))

        # Import authors
        imported = 0
        for chunk in content:
            values = chunk.to_dict()[colname].values()
            Author.objects.bulk_create([Author(name=name) for name in values])
            imported += chunk.size
            print(imported, 'imported')

        time_end = datetime.now() - time_start
        print("Finished! %d authors successfully imported. Time: %s" %
              (imported, str(time_end)))
Beispiel #22
0
    def setUp(self):
        folder = "%s/test_files/" % os.path.dirname(os.path.realpath(__file__))

        # Load authors
        authors = json.loads(open(folder + 'authors.json', 'r').read())
        Author.objects.bulk_create(
            [Author(name=item["name"]) for item in authors])
Beispiel #23
0
 def test_models(self):
     data_dicts = set_up_data()
     self.assertTrue(Collection(data_dicts['c']))
     self.assertTrue(Publisher(data_dicts['p']))
     self.assertTrue(Author(data_dicts['a']))
     self.assertTrue(Book(data_dicts['b1']))
     self.assertTrue(Book(data_dicts['b2']))
Beispiel #24
0
    def handle(self, *args, **kwargs):
        file_path = kwargs['file_path']
        with open(file_path) as csv_file:
            csv_reader = csv.reader(csv_file)
            next(csv_reader, None)

            for row in csv_reader:
                name = str(row).strip("'[]")
                try:
                    author = Author(name=name)
                    author.save()

                    self.stdout.write(
                        self.style.SUCCESS(
                            f"Author {name} added successfully"))
                except:
                    self.stdout.write(self.style.ERROR("Something went wrong"))
Beispiel #25
0
def import_authors(all_data, options):
    """"Import authors from JSON data."""

    for k, val in all_data["authors"].items():
        # If already there, overwrite:
        try:
            author = Author.objects.get(pk=k)
        except ObjectDoesNotExist:
            author = Author(pk=k)

        author.name = val["name"]

        msg = f"Imported [AUTHOR] {author}"
        print(msg)

        if not options.dry_run:
            author.save()
Beispiel #26
0
def regFromDouban(request):
    '''利用豆瓣API获取书籍信息加入数据库'''
    try:
        DOUBAN = "https://api.douban.com/v2/book/search?q="
        q = request.REQUEST.get('q', '')
        q = urllib.quote(q.decode('utf8').encode('utf8'))  
        DOUBAN += q
    
        req = urllib.urlopen(DOUBAN)
        resp = req.read()
        result = simplejson.loads(resp)
        books = result['books']
        
        
        for i in range(len(books)):
            author = Author()
            author.name = books[i]['author'][0]
            author.desc = books[i]['author_intro']
            author.save()
            
            try:
                book = Book.objects.get(isbn=books[i]['isbn13'])
            except Book.DoesNotExist:
                book = Book()
                book.name = books[i]['title']
                book.author = author
                book.price = float(''.join([ item for item in books[i]['price'] if item in '1234567890.' ]))
                if not books[i]['isbn13']:
                    book.isbn = books[i]['isbn10']
                else:
                    book.isbn = books[i]['isbn13']
                book.press = books[i]['publisher']
                book.desc = books[i]['summary']
                book.binding = books[i]['binding']
                book.pages = books[i]['pages']
                book.spic = _downloadImg(books[i]['images']['small'], 'small')   
                book.mpic = _downloadImg(books[i]['images']['medium'], 'medium')   
                book.lpic = _downloadImg(books[i]['images']['large'], 'large')   
                book.stock = 140
                book.publish_date = books[i]['pubdate']
                book.category = _getBookCate('letter')
                book.save()
                
        return HttpResponse('success')
    except Exception:
        return HttpResponse('error')
Beispiel #27
0
def new(request):
    if 'na' in request.GET and request.GET['na']:
            pu=request.GET['pu']
            bn=request.GET['bn']
            pud=request.GET['pud']
            pr=request.GET['pr']
            na=request.GET['na']
            ag=request.GET['ag']
            co=request.GET['co']
            ib=request.GET['ib']
            ai=request.GET['ai']
            a2=Author(name=na,authorid=ai,country=co,age=ag)
            a2.save()
            b2=Book(authorid=ai,title=bn,isbn=ib,price=pr,publisher=pu,publication_date=pud)
            b2.save()
            return render_to_response('delete.html')
    else:
        return  render_to_response('new.html')
Beispiel #28
0
def addbook(request):
    j=request.GET['p']
    k=request.GET['q']
    l=request.GET['i']
    if Author.objects.filter(Name=j):
        Athor=Author.objects.get(Name=j)
        p1=book(AuthorID=Athor.AuthorID,Title=k)
        p1.save()
        return render_to_response('search_form.html')
    else:
        if Author.objects.filter(AuthorID=l):
            return HttpResponse("The ID already exists!")
        else:
            p2=Author(Name=j,AuthorID=l)
            p2.save()
            p=book(AuthorID=l,Title=k)
            p.save()
            return render_to_response('search_form.html')
Beispiel #29
0
 def handle(self, *args, **options):
     faker = Faker("pl_PL")
     for i in range(10):
         author = Author()
         author.first_name = faker.first_name()
         author.last_name = faker.last_name()
         author.birthday = faker.date_of_birth()
         author.save()
         self.stdout.write(self.style.SUCCESS(f'Create: {str(author)}'))
Beispiel #30
0
 def handle(self, *args, **kwargs):
     fake = Faker()
     total = kwargs['total']
     authors_list = []
     for _ in range(total):
         name = fake.name()
         first_name = name.split()[0]
         last_name = name.split()[1]
         date_of_birth = fake.date()
         date_of_death = fake.date()
         country = fake.country()
         gender = random.choice(['male', 'female'])
         native_language = random.choice(
             ['English', 'French', 'Russian', 'Ukrainian'])
         authors_list.append(
             Author(
                 first_name=first_name,
                 last_name=last_name,
                 date_of_birth=date_of_birth,
                 date_of_death=date_of_death,
                 country=country,
                 gender=gender,
                 native_language=native_language,
             ))
     Author.objects.bulk_create(authors_list)
     category_list = []
     for _ in range(total):
         name = random.choice([
             'Action', 'Detectives', 'Romance novels', 'Adventures',
             'Fantasy', 'Humorous literature', 'Contemporary prose',
             'History', 'Classic literature', "Children's books",
             'Psychology', 'Business books', 'Journalism',
             'Sports, health, beauty', 'For parents'
         ])
         category_list.append(Category(name=name, ))
     Category.objects.bulk_create(category_list)
     books_list = []
     for _ in range(total):
         author = Author.objects.order_by('?').last()
         title = fake.word()
         category = Category.objects.order_by('?').last()
         publish_year = random.randint(0, datetime.now().year)
         review = fake.text()
         condition = random.randint(1, 5)
         books_list.append(
             Book(
                 author=author,
                 title=title,
                 category=category,
                 publish_year=publish_year,
                 review=review,
                 condition=condition,
             ))
     Book.objects.bulk_create(books_list)
Beispiel #31
0
def addA(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('AuthorID',''):
            errors.append('请填写作者ID。')
        if not request.POST.get('Name',''):
            errors.append('请填写作者姓名。')
        if not request.POST.get('Age',''):
            errors.append('请填写作者年龄。')
        if not request.POST.get('Country',''):
            errors.append('请填写作者国籍。')
        if not errors:
            post = request.POST
            author = Author(AuthorID=post['AuthorID'],
                  Name=post['Name'],
                  Age=post['Age'],
                  Country=post['Country'],)
            author.save()
            return render_to_response('edit_success.html',locals())
    return render_to_response('addA.html',locals())
Beispiel #32
0
 def authors_db(cls, books):
     """ put authors' name into the table """
     for book in books:
         authors = book["volumeInfo"].get("authors")
         if authors is not None:
             for author in authors:
                 try:
                     Author.objects.bulk_create(
                         [Author(author_name=author)])
                 except (IntegrityError, DataError):
                     continue
Beispiel #33
0
def new_author_book(request ) :
    json_data = simplejson.loads( request.body )
    book_title = json_data['title']
    name = json_data['name']
    if not Book.objects.filter( title=book_title, author_name=name).exists() :
        b = Book( title = book_title, author_name = name )
        b.save()
    else :
        return HttpResponse("Success")
    author_name = name
    if Author.objects.filter( name = author_name ).exists() :
        a = Author.objects.get( name = author_name)
        a.books.add( b )
        a.save()
    else :
        a = Author(name = author_name )
        a.save()
        a.books.add( b)
        a.save()
    return HttpResponse("Success")
Beispiel #34
0
    def form_valid(self, form):
        title = form.cleaned_data['title']
        isbn = form.cleaned_data['isbn']
        authors = form.cleaned_data['authors']
        create_new_author = form.cleaned_data['create_new_author']
        categories = form.cleaned_data['categories']
        author_name = form.cleaned_data['author_name']
        author_surname = form.cleaned_data['author_surname']
        book = Book(title=title, isbn=isbn, average_rating=0)
        book.save()
        if create_new_author is True:
            new_author = Author(name=author_name, surname=author_surname)
            new_author.save()
            book.book_author.add(new_author)
        else:
            author_list = Author.objects.filter(pk__in=authors)
            for author in author_list:
                book.book_author.add(author)
        category_list = Category.objects.filter(pk__in=categories)
        for category in category_list:
            book.book_category.add(category)

        return redirect('books/{}'.format(book.id))
    def handle(self, *args, **options):
        fake = Faker()

        # generate Categories
        for _ in range(20):
            Category.objects.create(name=fake.word())

        # create authors
        authors = []
        for _ in range(1_000):
            first_name = fake.name()
            last_name = fake.word()
            authors.append(Author(
                first_name=first_name,
                last_name=last_name,
            ))
Beispiel #36
0
def addauthor(request):
    author_list = Author()
    if request.POST:
        author_list.Name = request.POST['Name']
        author_list.AuthorID = request.POST['AuthorID']
        author_list.Age = request.POST['Age']
        author_list.Country = request.POST['Country']
        author_list.save()
        author_id = author_list.AuthorID
    try:
         author = Author.objects.get(AuthorID = author_id)
         return render_to_response('add_Successed.html')
    except:     
         return render(request,'addauthor.html',{'author':author_list})  
Beispiel #37
0
    def setUp(self):
        folder = "%s/test_files/" % os.path.dirname(os.path.realpath(__file__))

        # Load authors
        authors = json.loads(open(folder + 'authors.json', 'r').read())
        Author.objects.bulk_create(
            [Author(name=item["name"]) for item in authors])

        # Load books
        books = json.loads(open(folder + 'books.json', 'r').read())
        for b in books:
            book = Book.objects.create(
                name=b["name"],
                edition=b["edition"],
                publication_year=b["publication_year"],
            )
            book.authors.add(*b["authors"])
Beispiel #38
0
def update(request):

    if request.method == "POST":
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode) if body_unicode != "" else {}
        add = body.get('add')  #Также без условия на нахождение
        delete = body.get('delete')
        update = body.get('update')
        author_id = body.get('author_id')
        author = Author.get(id=author_id)
        answer = {'deleted': [], 'added': [], 'updated': []}
        for delete_id in delete:
            book = Book.get(id=delete_id)
            if book is not None:
                book.delete()
                answer['deleted'].append(delete_id)
        for book_update in update:
            book = Book.get(id=book_update['id'])
            if book is not None:
                title = book_update.get('title')
                description = book_update.get('description')
                price = book_update.get('price')
                if title == "" or description == "" or price == "":
                    book_update['status'] = 'error'
                else:
                    book.title = title
                    book.description = description
                    book.price = price
                    book.save()
                    book_update['status'] = ''
                answer['updated'].append(book_update)
        for book_add in add:
            title = book_add.get('title')
            description = book_add.get('description')
            price = book_add.get('price')
            if title == "" or description == "" or price == "":
                book_add['status'] = 'error'
            else:
                book = Book.create(title, description, price, author)
                book_add['status'] = ''
                book_add['new'] = False
                book_add['id'] = book.id
            answer['added'].append(book_add)
        return HttpResponse(json.dumps(answer))
    else:
        return HttpResponseRedirect('/')
Beispiel #39
0
def get(request):

    if request.method == "POST":
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode) if body_unicode != "" else {}
        data = body.get(
            'data'
        )  #Не стал делать условие на отсутствие параметров, ибо всё равно сам пишу данные отправки (хотя стоило бы)
        if data == 'authors':
            authors = Author.objects.all()
            return HttpResponse(
                json.dumps([author.serialize() for author in authors]))
        elif data == 'books':
            author_id = body.get('author_id')
            author = Author.get(id=author_id)
            books = Book.get(all=True, author=author)
            return HttpResponse(
                json.dumps([book.serialize() for book in books]))
    else:
        return HttpResponseRedirect('/')
Beispiel #40
0
def set_up_data():
    # model1: Collection
    c = Collection(name="Life Studies", code="LS")
    # model2: Publisher
    p = Publisher(name="Living Stream Ministry", code="LSM")
    # model3: Author
    a = Author(first_name="Witness", last_name="Lee", code="WL")
    # make sure all fields allowing blanks are tested
    # model4: Book without author and chapters ascribed
    b1 = Book(isbn=1234567890,
              name="Life Study of Genesis volume 1",
              code="LSG1",
              collection=c,
              publisher=p)
    # model5: Book without collection ascribed
    b2 = Book(isbn=1234567891,
              name="Life Study of Genesis volume 2",
              code="LSG2",
              chapters=25,
              publisher=p)
    return dict([('c', c), ('p', p), ('a', a), ('b1', b1), ('b2', b2)])
    def handle(self, *args, **kwargs):
        fake = Faker()
        amount = kwargs['amount']
        authors = []
        for _ in range(amount):
            first_name = fake.word().capitalize()
            last_name = fake.word().capitalize()
            date_of_birth = fake.date()
            date_of_death = fake.date()
            country = fake.country()
            gender = random.choice(['Male', 'Female'])
            language = fake.word()
            authors.append(
                Author(first_name=first_name,
                       last_name=last_name,
                       date_of_birth=date_of_birth,
                       date_of_death=date_of_death,
                       country=country,
                       gender=gender,
                       language=language))
        Author.objects.bulk_create(authors)

        books_list = []
        for _ in range(amount):
            author = Author.objects.order_by('?').last()
            title = fake.word()
            category = random.choice(Category.objects.all())
            publish_year = random.randint(0, datetime.now().year)
            review = fake.text()
            condition = random.randint(1, 5)
            books_list.append(
                Book(
                    author=author,
                    title=title,
                    category=category,
                    publish_year=publish_year,
                    review=review,
                    condition=condition,
                ))
        Book.objects.bulk_create(books_list)
Beispiel #42
0
    def handle(self, *args, **options):
        fake = Faker()
        authors_list = []

        for _ in range(options['quant']):
            first_name = fake.first_name()
            last_name = fake.last_name()
            country = fake.country()
            date_of_birth = fake.date()
            date_of_death = fake.date()
            gender = bool(random.getrandbits(1))
            native_language = fake.country_code()

            authors_list.append(
                Author(first_name=first_name,
                       last_name=last_name,
                       country=country,
                       date_of_birth=date_of_birth,
                       date_of_death=date_of_death,
                       gender=gender,
                       native_language=native_language))
        Author.objects.bulk_create(authors_list)
Beispiel #43
0
def addAuthor(request):
    new_author = Author()
    if request.method == 'POST':
        form = AuthorForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            age = form.cleaned_data['age']

            new_author.first_name = first_name
            new_author.last_name = last_name
            new_author.email = email
            new_author.age = age
            new_author.save()

            #return HttpResponse("Author Added")
            #return render(request, 'auth_users.html')
            return redirect('/books/home/')
    else:
        form = AuthorForm()
    return render(request, 'author.html', {'form': form})
Beispiel #44
0
def new_author_book(request):
    json_data = simplejson.loads(request.body)
    book_title = json_data['title']
    name = json_data['name']
    if not Book.objects.filter(title=book_title, author_name=name).exists():
        b = Book(title=book_title, author_name=name)
        b.save()
    else:
        return HttpResponse("Success")
    author_name = name
    if Author.objects.filter(name=author_name).exists():
        a = Author.objects.get(name=author_name)
        a.books.add(b)
        a.save()
    else:
        a = Author(name=author_name)
        a.save()
        a.books.add(b)
        a.save()
    return HttpResponse("Success")
Beispiel #45
0
        __str__()唯一的条件是返回一个string, 如果不返回 string 的话如返回一个 integer ,会触发一个TypeError异常
        __str__()方法告诉Python怎样显示对象的string显示:

        # 修改前面的 Author 类
        class Author(models.Model):
            name = models.CharField(max_length=30)
            salutation = models.CharField(max_length=10)

            def __str__(self):
                return self.name

            def __unicode__(self):
                return unicode(self.name)

       # 执行命令
       python manage.py shell

       # 执行python
       from books.models import Author # import模型类
       a = Author(name='Jhon', salutation='salutation1')
       a.save()
       a = Author(name='Kevin', salutation='salutation2')
       a.save()
       author_list = Author.objects.all()
       print(author_list) # 打印: [<Author: Jhon>, <Author: Kevin>]
       print(author_list[0].name) # 打印:  Jhon

    注意 __str__() 是给模型添加行为的好习惯
    一个Django模型描述的不仅仅是一个对象数据库表结构, 它也描述了对象知道怎样去做的功能

Beispiel #46
0
def run(inp_list=None, tbr_name=None):

    cont = []
    log = []
    new_author = 0
    new_book = 0
    new_genres = 0
    new_tbr = 0
    records_json = json.loads(inp_list)

    if tbr_name:
        tbr_slug = unique_slug_generator(tbr_name)
        try:
            tbr = TBR.objects.get(slug=tbr_slug)
            return None
        except TBR.DoesNotExist:
            log.append("Creating a new TBR:  {}".format(tbr_name))
            tbr = TBR(title=tbr_name)
            tbr.save()
            new_tbr = +1
            tbr = TBR.objects.get(slug=tbr_slug)

            for record in records_json:
                auth_name_refined = remove(record['author_name'])
                auth_name = auth_name_refined.split(",")

                # Loading Authors to the database, if doesn't exist. Creating one
                for ind_auth_name in auth_name:
                    firstname = ind_auth_name.strip().split(' ')[0]
                    lastname = ' '.join(
                        (ind_auth_name + ' ').split(' ')[1:]).strip()
                    auth_slug = unique_slug_generator_author(ind_auth_name)
                    try:
                        author = Author.objects.get(slug=auth_slug)
                        log.append("Auhtor: {},{} exists.".format(
                            lastname, firstname))

                    except Author.DoesNotExist:
                        log.append("Author: {} {} does not exist.".format(
                            lastname, firstname))
                        author = Author(first_name=firstname,
                                        last_name=lastname)
                        author.save()
                        new_author = +1
                        log.append("Author: {} {} Added.".format(
                            lastname, firstname))

                #Loading Books to the database. if doesn't exist. Creating one
                try:
                    book = Book.objects.get(slug=record["book_slug"])
                    for auth in auth_name:
                        auth_slug = unique_slug_generator_author(auth)
                        log.append("Book: {} Exists.".format(
                            record["book_title"]))
                        author = Author.objects.get(slug=auth_slug)
                        book.author.add(author)
                        book.save()
                        log.append("Added Author to Book: {}.".format(
                            record["book_title"]))
                        tbr.book.add(book)
                        tbr.save()
                        log.append(
                            "Added Book to Reading List: {}.".format(tbr_name))

                except Book.DoesNotExist:
                    log.append("Book: {} does not exist.".format(
                        record["book_title"]))
                    book = Book(title=record["book_title"],
                                image_url=record["image_url"])
                    book.save()
                    new_book += 1
                    log.append("Book: {} Added.".format(record["book_title"]))
                    book = Book.objects.get(slug=record["book_slug"])
                    for auth in auth_name:
                        auth_slug = unique_slug_generator_author(auth)
                        author = Author.objects.get(slug=auth_slug)
                        book.author.add(author)
                        book.save()
                        log.append("Added Author to Book: {}.".format(
                            record["book_title"]))
                        tbr.book.add(book)
                        tbr.save()
                        log.append(
                            "Added Book to Reading List: {}.".format(tbr_name))

                # Loading Genre to the database. if doesn't exist. Creating One
                if record['genre']:
                    genre_refined = remove(record['genre'])
                    genre_name = genre_refined.split(",")

                    for genre in genre_name:
                        genre_slug = unique_slug_generator(genre)
                        try:
                            gen = Genre.objects.get(slug=genre_slug)
                            log.append("Genre: {} Exists.".format(genre))

                        except Genre.DoesNotExist:
                            log.append(
                                "Genre: {} does not exist.".format(genre))
                            gen = Genre(name=genre)
                            gen.save()
                            new_genres += 1
                            log.append("Genre: {} added.".format(genre))

                # Adding Genres to the books
                try:
                    book = Book.objects.get(slug=record["book_slug"])
                    for genre in genre_name:
                        genre_slug = unique_slug_generator_author(genre)
                        log.append("Book: {} Exists.".format(
                            record["book_title"]))
                        genre = Genre.objects.get(slug=genre_slug)
                        book.genre.add(genre)
                        book.save()
                        log.append("Added Genre{} to Book: {}.".format(
                            genre, record["book_title"]))

                except Exception as e:
                    pass

    else:
        for record in records_json:
            auth_name_refined = remove(record['author_name'])
            auth_name = auth_name_refined.split(",")

            # Loading Authors to the database, if doesn't exist. Creating one
            for ind_auth_name in auth_name:
                firstname = ind_auth_name.strip().split(' ')[0]
                lastname = ' '.join(
                    (ind_auth_name + ' ').split(' ')[1:]).strip()
                auth_slug = unique_slug_generator_author(ind_auth_name)
                try:
                    author = Author.objects.get(slug=auth_slug)
                    log.append("Auhtor: {},{} exists.".format(
                        lastname, firstname))

                except Author.DoesNotExist:
                    log.append("Author: {} {} does not exist.".format(
                        lastname, firstname))
                    author = Author(first_name=firstname, last_name=lastname)
                    author.save()
                    new_author += 1
                    log.append("Author: {} {} Added.".format(
                        lastname, firstname))

            #Loading Books to the database. if doesn't exist. Creating one
            try:
                book = Book.objects.get(slug=record["book_slug"])
                for auth in auth_name:
                    auth_slug = unique_slug_generator_author(auth)
                    log.append("Book: {} Exists.".format(record["book_title"]))
                    author = Author.objects.get(slug=auth_slug)
                    book.author.add(author)
                    book.save()
                    log.append("Added Author to Book: {}.".format(
                        record["book_title"]))

            except Book.DoesNotExist:
                log.append("Book: {} does not exist.".format(
                    record["book_title"]))

                # book = Book(title=record["book_title"])
                book = Book(title=record["book_title"],
                            image_url=record["image_url"])
                book.save()
                new_book += 1
                log.append("Book: {} Added.".format(record["book_title"]))
                book = Book.objects.get(slug=record["book_slug"])
                for auth in auth_name:
                    auth_slug = unique_slug_generator_author(auth)
                    author = Author.objects.get(slug=auth_slug)
                    book.author.add(author)
                    book.save()
                    log.append("Added Author to Book: {}.".format(
                        record["book_title"]))

            # Loading Genre to the database. if doesn't exist. Creating One
            if record['genre']:
                genre_refined = remove(record['genre'])
                genre_name = genre_refined.split(",")

                for genre in genre_name:
                    genre_slug = unique_slug_generator(genre)
                    try:
                        gen = Genre.objects.get(slug=genre_slug)
                        log.append("Genre: {} Exists.".format(genre))

                    except Genre.DoesNotExist:
                        log.append("Genre: {} does not exist.".format(genre))
                        gen = Genre(name=genre)
                        gen.save()
                        new_genres = +1
                        log.append("Genre: {} added.".format(genre))

            # Adding Genres to the books
            try:
                book = Book.objects.get(slug=record["book_slug"])
                for genre in genre_name:
                    genre_slug = unique_slug_generator_author(genre)
                    log.append("Book: {} Exists.".format(record["book_title"]))
                    genre = Genre.objects.get(slug=genre_slug)
                    book.genre.add(genre)
                    book.save()
                    log.append("Added Genre{} to Book: {}.".format(
                        genre, record["book_title"]))

            except Exception as e:
                pass

    cont.append(new_author)
    cont.append(new_book)
    cont.append(new_genres)
    cont.append(new_tbr)
    cont.append(log)

    return cont
Beispiel #47
0
 def _handle_json(self, file_path):
     with open(file_path) as f:
         book_dict = self._json_file_to_json(file_path)
         
         print( book_dict['id'], book_dict['a_title'] )
         
         if book_dict['words'] == 0:
             raise ValueError("Ebooks containing zero words are not allowed.")
         
         book_dict['a_status'] = Status.objects.get( status = book_dict['a_status'] )
         book_dict['rating'] = Rating.objects.get( pk = book_dict['rating'] )
         
         a_categories = [];
         for category in book_dict['a_categories']:
             a_categories.append( Category.objects.get( category = category ) )
         del book_dict['a_categories']
         
         author_dict = book_dict['author']
         del book_dict['author']
         try:
             author = Author.objects.get( id = author_dict['id'] )
         except ObjectDoesNotExist as ex:
             author = Author(**author_dict)
             author.save()
         
         existing_book = None
         
         try:
             existing_book = Book.objects.get( id = book_dict['id'] )
         except:
             # Book does not exist, lets make one.
             book = Book(**book_dict)
             book.save()
             book.a_authors.add(author)
             [book.a_categories.add(category) for category in a_categories]
             book.save()
 
         if existing_book != None:
             if not existing_book.sameAsDict(book_dict):
                 print("Updating book")
                 
                 existing_book.updated = book_dict.get('updated')
                 existing_book.fimfic_updated = book_dict.get('fimfic_updated')
                 existing_book.words = book_dict.get('words')
                 existing_book.views = book_dict.get('views')
                 existing_book.comments = book_dict.get('comments')
                 existing_book.likes = book_dict.get('likes')
                 existing_book.dislikes = book_dict.get('dislikes')
                 existing_book.rating = book_dict.get('rating')
                 existing_book.a_thumbnail = book_dict.get('a_thumbnail')
                 existing_book.a_cover = book_dict.get('a_cover')
                 existing_book.a_status = book_dict.get('a_status')
                 existing_book.a_title = book_dict.get('a_title')
                 if 'a_published' in book_dict:
                     existing_book.a_published = book_dict.get('a_published')
                 existing_book.a_summary = book_dict.get('a_summary')
                 existing_book.a_content = book_dict.get('a_content')
                 if 'a_rights' in book_dict:
                     existing_book.a_rights = book_dict.get('a_rights')
                 existing_book.dc_language = book_dict.get('dc_language')
                 if 'dc_publisher' in book_dict:
                     existing_book.dc_publisher = book_dict.get('dc_publisher')
                 existing_book.dc_issued = book_dict.get('dc_issued')
                 if 'dc_identifier' in book_dict:
                     existing_book.dc_identifier = book_dict.get('dc_identifier')
                 
                 existing_book.a_authors.add(author)
                 [existing_book.a_categories.add(category) for category in a_categories]
                 existing_book.save()
             else:
                 print("Not updating book. Book is the same.")
Beispiel #48
0
def submit_author(request):
    p1=Author(authorid=request.GET['authorid'],name=request.GET['name'],age=request.GET['age'],
              country=request.GET['country'])
    p1.save()
    return HttpResponseRedirect('/author/')
Beispiel #49
0
 def setUp(self):
     self.book = Book(**example_book_attrs)
     self.author = Author(**example_author_attrs)
     self.isbn = ISBN(**example_isbn_attrs)
Beispiel #50
0
def Add3(request):
    if request.POST:
        post = request.POST
        a = Author(AuthorID=post['aid'],Name=post['target'],Age=post['age'],Country=post['coun'])
        a.save()
        return Search(request)
Beispiel #51
0
 def test_create_author_with_exists_name_raises_error(self):
     author = AuthorFactory()
     new_author = Author(first_name=author.first_name, last_name=author.last_name)
     with self.assertRaises(IntegrityError):
         new_author.save()
Beispiel #52
0
 def test_basic_author(self):
     """
     Test add author
     """
     create_author = Author(FIO="Ernest Miller Hemingway", birthday = "1899-07-21")
     create_author.save()