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()
예제 #2
0
파일: views.py 프로젝트: hongfirst/LAB
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')
예제 #3
0
파일: view.py 프로젝트: 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',)
예제 #4
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)
예제 #5
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")
예제 #6
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
예제 #7
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
예제 #8
0
파일: views.py 프로젝트: ZhaoYuxiao/Lab3
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})
예제 #9
0
파일: views.py 프로젝트: hetianyu/git
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/")
예제 #10
0
파일: view.py 프로젝트: 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())
예제 #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
예제 #12
0
파일: views.py 프로젝트: lsummer/lab4_2
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")  
예제 #13
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)}'))
예제 #14
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")
예제 #15
0
파일: view.py 프로젝트: feilifan/SE-Lab4
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')
            
예제 #16
0
파일: views.py 프로젝트: lsummer/lab4_2
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")  
예제 #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/')
예제 #18
0
파일: views.py 프로젝트: hongkailun/123
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})  
예제 #19
0
파일: views.py 프로젝트: Tongxin8287/lab4
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')
예제 #20
0
 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()
예제 #21
0
파일: views.py 프로젝트: martinchia/Lab4
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)
예제 #22
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()
예제 #23
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"))
예제 #24
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')
예제 #25
0
파일: views.py 프로젝트: hmdrgql/hello
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')
예제 #26
0
파일: views.py 프로젝트: w603019289/mysite
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')
예제 #27
0
파일: views.py 프로젝트: xinwuchen/work
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())
예제 #28
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")
예제 #29
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")
예제 #30
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})
예제 #31
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))
예제 #32
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模型描述的不仅仅是一个对象数据库表结构, 它也描述了对象知道怎样去做的功能

예제 #33
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.")
예제 #34
0
def authors():
    authors = []
    author = Author(first_name='Daimond', last_name='Samsher')
    author.save()
    authors.append(author)
    return authors
예제 #35
0
 def test_basic_author(self):
     """
     Test add author
     """
     create_author = Author(FIO="Ernest Miller Hemingway", birthday = "1899-07-21")
     create_author.save()
예제 #36
0
파일: views.py 프로젝트: chaoeward/Lab4-2
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)
예제 #37
0
파일: views.py 프로젝트: LIhuiDeng/scene1
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/')
예제 #38
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()
예제 #39
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