def add(): form = request.form name = form.get('name') author = form.get('author') book = Book(name=name, author=author, date_created=datetime.now()) book.save() return jsonify(status='success')
def test_001_new_charfield(self): Attribute.factory(Book, name='new_charfield', kind='django.db.models.fields.CharField').save() book = Book(name=u'Breaking Django', new_charfield='Easy !') book.save() book = Book.objects.get(name=u'Breaking Django') self.assertEquals(book.new_charfield, 'Easy !')
def edit_book_new(request): book = Book(subject="New Book", ccl_left="by", ccl_right="-", summary="", open_yn = "N", creator=request.user) book.save() book.user.add(request.user) page = Page(book=book, subject="FrontPage") page.save() return redirect("/edit/book/%s" % book.id)
def add_book(request): if request.method == 'POST': book = Book(user=request.user, title=request.POST.get("title"), author=request.POST.get("author"), reading_status=request.POST.get("status"), end_date=datetime.datetime.now()) book.save() return HttpResponseRedirect("/profile") else: return HttpResponseNotAllowed(["POST"])
def get_book_inf(xml, messages=None): ''' Reads information from xml, finds or creates the book author, the book files, annotations, etc Returns tupel of (NOT saved models.Book with information about it in its fileds, list of authors, list of book files, list of annotations) Or raises InputDataServerException, if the book title not found. ''' if messages == None: messages = [] book = Book(title='', lang='') authors = [] book_files = [] annotations = [] # unused flag #is_author_created = False for node in xml.getchildren(): if node.tag == 'title': book.title = strip_str(node.text) if node.tag == 'lang': book.language = get_language(node.text) if node.tag == 'authors' and book.title: (authors, is_author_created) = get_authors(node, messages) if node.tag == 'files' and book.title: book_files = get_files(node) if node.tag == 'annotation' and book.title: annotation_txt = strip_str(node.text) if annotation_txt: annotation = \ Annotation.objects.get_or_create(name=annotation_txt)[0] annotations.append(annotation) # if there are not the title of the book, raise exception if not book.title: analyzer_log.warning('In request there is not the title of the book') raise InputDataServerException( 'In request there is not the title of the book') # if there are not the book_file, raise exception elif not book_files: analyzer_log.warning('In request there is not the book_file') raise InputDataServerException('In request there is not the book_file') return (book, authors, book_files, annotations)
def create_book(request): form = CreateBookForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] book = Book(title=title, user_id=request.user.id) book.save() assign_perm("work", request.user, book) return redirect(reverse("book.views.work_book", kwargs={"book_id": book.id})) else: errors = form.errors return render(request, 'profil/page.html', locals())
def addbook(request): if 'addsub' in request.GET: temp_add = request.GET['addsub'] if 'again' in request.GET: again = request.GET['again'] if 'add_Author' in request.GET: add_Author = request.GET['add_Author'] if temp_add: add_ISBN = request.GET['ISBN'] add_Title = request.GET['Title'] add_Name = request.GET['Author_name'] add_Publisher = request.GET['Publisher'] add_PublishDate = request.GET['PublishDate'] add_Price = request.GET['Price'] if not add_ISBN: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_book':'书籍信息:'}) if not add_Title: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_book':'书籍信息:'}) if not add_Name: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_book':'书籍信息:'}) if not add_Publisher: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_book':'书籍信息:'}) if not add_PublishDate: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_book':'书籍信息:'}) if not add_Price: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_book':'书籍信息:'}) for temp_author in Author.objects.all(): if(add_Name,temp_author.Name)==0: p = Book( ISBN = add_ISBN, Title = add_Title, AuthorID = temp_author, Publisher = add_Publisher, PublishDate = add_PublishDate, Price = add_Price) p.save() return render_to_response('addbook.html',{'ret': '已添加书籍!', 'add_book':'书籍信息:'}) return render_to_response('addbook.html',{'ret':'No this author', 'add_author':'作者信息:'}) if add_Author: add_AuthorName = request.GET['Name'] add_AuthorID = request.GET['AuthorID'] add_Age = request.GET['Age'] add_Country = request.GET['Country'] if not add_AuthorName: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_author':'作者信息:'}) if not add_AuthorID: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_author':'作者信息:'}) if not add_Age: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_author':'作者信息:'}) if not add_Country: return render_to_response('addbook.html',{'ret': '请输入完整信息!', 'add_author':'作者信息:'}) k = Author(AuthorID = add_AuthorID, Name = add_Name, Age = add_Age, Country = add_Country) k.save() return render_to_response('addbook.html',{'ret': '已添加作者!', 'add_book':'书籍信息:'}) if again: return render_to_response('addbook.html',{'add_book':'书籍信息:'}) return render_to_response('addbook.html',{'add_book':'书籍信息:'})
def post(request): if request.GET: l = request.GET ADD = Book(Title=l['Title'], ISBN=l['ISBN'], AuthorID=l['AuthorID'], Publisher=l['Publisher'], PublishDate=l['PublishDate'], Price=l['Price']) ADD.save() return render_to_response('choose.html',{'right':True}) else: return render_to_response('post1.html',{'right':True})
def test_search(self): """ tests search response""" client = Client() lang = Language(id=0) lang.save() book = Book(title="Book", language=lang) book.save() response = client.get('/search?query=Book') print 'status code for good search request', response.status_code self.failUnlessEqual(response.status_code, 200) response = client.get('/search.atom?query=Book') print 'status code for good search request', response.status_code self.failUnlessEqual(response.status_code, 200)
def search(request): q = request.GET.get('q', None) if not q: return JsonResponse({ 'ok': 0, 'msg': u'검색어가 없습니다.', }) page, book_a, book_z = paginate(request.GET, Book.SEARCH_COUNT) books = Book.objects\ .filter(Q(author__contains=q) | Q(title__contains=q) | Q(isbn=q))\ .order_by('-created_at')[book_a:book_z] if books.exists(): item = books else: item = Book.search(search_type='all', q=q, embago=Book.SEARCH_COUNT, page=page) return JsonResponse({ 'ok': 1, 'item': serialize(item), 'page': int(page), 'q': q, })
def create_new_order(request): req = request.POST user = CustomUser.get_by_email(req.get('user_email')) book = Book.get_by_id(req.get('book_id')) plated_end_at = req.get('plated_end_at') new_order = Order.create(user, book, plated_end_at) return render(request, 'order/neworder.html', context={'new_order': new_order})
def test_create_positive_name_description_empty(self): """ Positive Test of the CustomUser.create method """ book = Book.create(name="testBook", description="") self.assertIsInstance(book, Book) self.assertEqual(book.name, "testBook") self.assertEqual(book.description, "") self.assertEqual(book.count, 10) self.assertListEqual(list(book.authors.all()), [])
def populate(): print('Populating Book...', end='') titles = [ 'python', '小王子', 'Java', '黑子的籃球', 'Django', '管理數學', '計概', 'c++', 'vb', '少年陰陽師' ] authornames = ['王一', '王二', '王三'] Book.objects.all().delete() for title in titles: book = Book() book.title = title book.authorname = authornames[random.randint(0, len(authornames) - 1)] book.publisher = book.authorname book.date = datetime.datetime.today() book.version = '1' book.price = 1000 book.save() print('done')
def add_fk1(): from book.models import Publisher, Book p = Publisher.objects.get(name='机械工业出版社') b = Book() b.name = 'Python 高并发实战' b.publisher_state = 2 b.desc = 'Good' b.publisher = p # ForeignKey b.save()
def post(self, req): try: book = Book( isbn=req.POST['isbn'], title=req.POST['title'], author=req.POST['author'], publisher=req.POST['publisher'], pubdate=datetime.datetime.strptime(req.POST['pubdate'], "%Y%m%d").date(), price=req.POST['price'], description=req.POST['description'], image=req.POST['image'], ) book.save() # success message messages.info(req, req.POST['title']) finally: return redirect('/book')
def populate(): print('Populating articles and comments ... ', end='') Book.objects.all().delete() Review.objects.all().delete() for title, content in zip(titles, contents): book = Book() book.title = title book.content = content book.author = authors book.publisher = publishers book.publicationDate = publicationDate book.price = 999 book.save() for review, score in zip(reviews, scores): Review.objects.create(book=book, review=review, score=score) print('done')
def insert_book(request): if request.POST: post = request.POST try: book_remain = Book.objects.filter(ISBN = post["ISBN"])[0] message="this book already exists ,can not be inserted again\nbut you can update it" return render_to_response("mistake.html",{'message': message}) except IndexError: #if the author not exits,need to add try: author = Author.objects.filter(AuthorID = post["author_id"])[0] new_book = Book( ISBN= post["ISBN"],Title = post["title"] ,Publisher=post["publisher"], AuthorID=post["author_id"],Price=(float)(post["price"]),PublishDate=post["publishDate"]) new_book.save() return render_to_response("success.html")# except IndexError: message="we cannot find this author id ,please insert the author firstly" return render_to_response("mistake.html",{'message': message}) return render_to_response("insert_book.html")
def tests(self): Book(id=1, title='Title', rating=0.0).save() links = [ '/admin/', '/register/', '/login/', '/', '/books', '/books/p0', '/book/1', '/book/2', '/user/1' ] codes = [200, 200, 200, 200, 200, 200, 200, 200, 404] for link, code in zip(links, codes): self.assertEqual( self.client.get(link, follow=True).status_code, code)
def updateBook(request, pk): book = Book.get_by_id(pk) form = BookForm(instance=book) if request.method == 'POST': form = BookForm(request.POST, instance=book) if form.is_valid(): form.save() return redirect("/books") context = {'form': form} return render(request, 'book_form.html', context)
def test_create_positive_name_description_count_a(self): """ Positive Test of the CustomUser.create method """ book = Book.create(name="testBook", description="testDescription", count=5, authors=[self.author1, self.author2]) self.assertIsInstance(book, Book) self.assertEqual(book.name, "testBook") self.assertEqual(book.description, "testDescription") self.assertEqual(book.count, 5) self.assertListEqual(list(book.authors.all()), [self.author1, self.author2])
def initialize_book(book_form, pk=None): if pk: book = Book.objects.get(pk=pk) book.title = book_form.cleaned_data['title'] book.pages = book_form.cleaned_data['pages'] book.description = book_form.cleaned_data['description'] book.author = book_form.cleaned_data['author'] else: title = book_form.cleaned_data['title'] pages = book_form.cleaned_data['pages'] description = book_form.cleaned_data['description'] author = book_form.cleaned_data['author'] book = Book( title=title, pages=pages, description=description, author=author, ) book.save() return redirect(index)
def populate(): print('Populating book...', end='') titles = ['如何像電腦科學家一樣思考', '10 分鐘內學好 Python', '簡單學習 Django' '如何像電腦科學家一樣思考2', '10 分鐘內學好 Python2', '簡單學習 Django2' '如何像電腦科學家一樣思考3', '10 分鐘內學好 Python3', '簡單學習 Django3' '如何像電腦科學家一樣思考4', '10 分鐘內學好 Python4', '簡單學習 Django4'] authors =['張三','李四','王五','趙六','錢七'] Book.objects.all().delete() for title in titles: book = Book() book.title = title n = random.randint(0,len(authors)-1) book.author = authors[n] book.publisher = book.author book.time = datetime.datetime.today() book.version = '1' book.price = 1000 book.save() print('done')
def load_book(request): if request.method == 'POST': load_book_form = BookEditForm(request.POST, request.FILES) if load_book_form.is_valid(): cleaned_data = load_book_form.cleaned_data book = Book(**cleaned_data) # book.cover_id = cover.id book.loaded_by_id = get_current_user_id(request) book.save() return render(request, 'book/load_book_done.html', { 'book': book, }) else: messages.error(request, 'File is not Epub!') else: load_book_form = BookEditForm() return render(request, 'book/load_book.html', { 'form': load_book_form, })
def fake(): db.create_all() books = [ { 'title': 'My Neighbor Totoro', 'year': '1988' }, { 'title': 'Dead Poets Society', 'year': '1989' }, { 'title': 'A Perfect World', 'year': '1993' }, { 'title': 'Leon', 'year': '1994' }, { 'title': 'Mahjong', 'year': '1996' }, { 'title': 'Swallowtail Butterfly', 'year': '1996' }, { 'title': 'King of Comedy', 'year': '1999' }, { 'title': 'Devils on the Doorstep', 'year': '1999' }, { 'title': 'WALL-E', 'year': '2008' }, { 'title': 'The Pork of Music', 'year': '2012' }, ] all_books = [ Book(title=book['title'], year=book['year']) for book in books ] db.session.add_all(all_books) try: db.session.commit() click.echo('Success.') except: db.session.rollback() click.echo('Done.')
def order_on_click(request, id): user = request.user book = Book.get_by_id(book_id=id) order_form = OrderOnClick() if request.method == 'POST': order_form = OrderOnClick(request.POST) if order_form.is_valid(): temp_order = Order.create(user=user, book=book, planned_end_at=datetime.now()) order = temp_order.update(**order_form.cleaned_data) return redirect('order_by_id', temp_order.id) return render(request, 'order_confirm_.html', context={'form': order_form, 'user': user, 'book': book})
def add_book(request): book_list = Book.objects.all() author_list = Author.objects.all() if request.POST: post = request.POST if post['Title'] and post['ISBN_PK'] and post['AuthorID_FK'] and post['Publisher'] and post['PublishDate'] and post['Price']: new_book = Book( Title = post['Title'], ISBN_PK = post['ISBN_PK'], AuthorID_FK = post['AuthorID_FK'], Publisher = post['Publisher'], PublishDate = post['PublishDate'], Price = post['Price'], ) if Author.objects.filter(AuthorID_PK = new_book.AuthorID_FK): new_book.save() else: return render_to_response('author_not_exist.html') return HttpResponseRedirect('/redirect/') return render_to_response('add_book.html')
def book_edit(request, book_id=None): """書籍の編集""" # return HttpResponse('書籍の編集') if book_id: # book_id が指定されている (修正時) book = get_object_or_404(Book, pk=book_id) else: # book_id が指定されていない (追加時) book = Book() if request.method == 'POST': form = BookForm(request.POST, instance=book) # POST された request データからフォームを作成 if form.is_valid(): # フォームのバリデーション book = form.save(commit=False) book.save() return redirect('book:book_list') else: # GET の時 form = BookForm(instance=book) # book インスタンスからフォームを作成 return render(request, 'book/book_edit.html', dict(form=form, book_id=book_id))
def book_category(request, category_id): page = int(request.GET.get('page', 1)) count = int(request.GET.get('count', 6)) start = (page - 1) * count category = Category.objects.get(id=category_id) books = Book.get_books_by_category_id(category_id, start, count) total_category_books = int(Book.get_books_count_by_category_id(category_id)) has_prev_page = False has_next_page = False prev_page = 1 next_page = 1 if page > 1: has_prev_page = True prev_page = page - 1 if page * count < total_category_books: has_next_page = True next_page = page + 1 return render_to_response('category_book.html', locals())
def test_post_request_without_valid_email(client): new_book = Book(title="4H work week") db.session.add_all([new_book]) db.session.commit() rs = client.post("/request", json={ "email": "[invalid!email]", "title": "4H work week" }) assert rs.status_code == 400
def change_book(request,id): try: id = int(id) except ValueError: raise Http404() book = Book.objects.filter(id = id)[0] if request.POST: post = request.POST if post["Title"]: new_book = Book( Title = post['Title'], ISBN_PK = book.ISBN_PK, AuthorID_FK = post['AuthorID_FK'], Publisher = post['Publisher'], PublishDate = post['PublishDate'], Price = post['Price'], ) new_book.save() book.delete() return HttpResponseRedirect('/redirect/') return render_to_response('change_book.html',)
def populate_data(file): currentDirectory = os.path.dirname(__file__) dataFilePath = os.path.join(currentDirectory, file) with open(dataFilePath) as f: stringNew = f.read() data = json.loads( re.sub(r"(?i)(?:\\u00[0-9a-f]{2})+", unmangle_utf8, stringNew)) lengthOfData = len(data["titles"]) print("total is " + str(lengthOfData)) for i in range(lengthOfData): print(i) title = data["titles"][i] summary = data["summaries"][i]["summary"] parts = summary.split(":") summary1 = parts[1] parts = re.split(r'[;\-,.\s]\s*', summary1) titleParts = re.split(r'[;\-,.\s]\s*', title) parts.extend(titleParts) nonEmptyParts = [ part.lower() for part in parts if len(part) > 0 and (not hasNumbers(part)) ] dict = {} for part in nonEmptyParts: if part in dict: dict[part] += 1 else: dict[part] = 1 id = data["summaries"][i]["id"] author = get_author_details(id) b = Book(title=title, id=id, summary=summary, author=author) b.save() for key in dict: try: w = Words.objects.get(word=key) except: w = Words(word=key) w.save() wc = WordCount(book=b, word=w, count=dict[key]) wc.save()
def populate(): # for authors for _ in range(100): Author.objects.create(first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email()) genres = [ 'Action', 'Crime', 'Drama', 'Fiction', 'Science fiction', 'Horror', 'Thriller', 'Fairytale', 'Adventure', 'Biography' ] for g in genres: Genre.objects.create(name=g) # for publisher for _ in range(100): Publisher.objects.create(name=fake.company(), address=fake.address(), website=fake.url()) # for books for _ in range(10000): book = Book(title=fake.sentence()) choices = range(1, 101) book.publisher_id = random.choice(range(1, 101)) book.genre_id = random.choice(range(1, 11)) book.price = random.randint(10, 500) book.published_date = fake.past_date(start_date="-100y") book.save() no_choice = [1, 2, 3, 4, 5] authors = random.choices(choices, k=random.choice(no_choice)) book.author.add(*authors) book.save() if _ % 100 == 0: print(f'{_} objects created')
def addBook( request): # request method 确定与服务器交互的方法,GET一般用于获取/查询资源信息,POST一般用于更新资源信息 user = request.user try: staff = Staff.objects.get(account__username__exact=user.username) except: return HttpResponse('Permission denied') else: if request.POST: isbn = request.POST.get('isbn', None) title = request.POST.get('title', None) author = request.POST.get('author', None) publisher = request.POST.get('publisher', None) details = request.POST.get('douban link', None) category = request.POST.get('category', None) quantity = request.POST.get('quantity', None) remain = request.POST.get('remain', None) isbns = Book.objects.filter(isbn__exact=isbn) if isbns: resp1 = { 'info': 'Already exists!', 'result': 'Already exists!' } return HttpResponse(json.dumps(resp1), content_type="application/json") else: book = Book(isbn=isbn, title=title, author=author, publisher=publisher, details=details, category=category, quantity=quantity, remain=remain) book.save() return HttpResponseRedirect('/staff/manage') return render_to_response('book/add.html')
def test_cannot_save_empty_title_books(self): publisher = Publisher.objects.create(name='Pub', country='China', website='http://www.pub.com') classfication = Classfication.objects.create() book = Book(classfication=classfication, publisher=publisher) book.title = '' with self.assertRaises(ValidationError): book.save() book.full_clean()
def get_author_by_id(request, id=0): author_by_id = Author.get_by_id(id) bks = [ book for book in list(Book.get_all()) if author_by_id in book.authors.all() ] # books = list(Book.get_all()) return render(request, 'author/get_author_by_id.html', context={ 'author_by_id': author_by_id, 'books': bks })
def create_book(request): if request.method == 'POST': createbookform = CreateBookForm(request.POST, request.FILES) if createbookform.is_valid(): book = Book() book.category = createbookform.cleaned_data['category'] book.name = createbookform.cleaned_data['name'] book.cover = createbookform.cleaned_data['cover'] book.summary = createbookform.cleaned_data['summary'] book.author = request.user.author book.save() return redirect(reverse('author:update_book', args=[book.pk])) else: print(createbookform.errors) else: createbookform = CreateBookForm() context = dict() context['createbookform'] = createbookform return render(request, 'author_area/manage/create_book.html', context)
def get_order_by_id(request, id=0): order_found = Order.get_by_id(id) usr = CustomUser.get_by_id(order_found.user_id) bk = Book.get_by_id(order_found.book_id) al = [authors for authors in list(bk.authors.all())] return render(request, 'order/get_order_by_id.html', context={ 'order': order_found, 'user': usr, 'book': bk, 'authors_list': al })
def populate(): print('Populating bkName ... ', end='') Book.objects.all().delete() i = 1 for bkName in bkNames: book = Book() book.bkName = bkName book.authorName = 'at' + str(i) book.publisher = 'pub' + str(i) book.pubversion = 1 book.price = i * 100 book.inventory = 10 i += 1 book.save() print('done')
def book_edit(request, book_id=None): # 書籍の編集 if book_id: book = get_object_or_404(Book, pk=book_id) else: book = Book() # POST リクエスト # POST されたデータからフォームを作成する if request.method == 'POST': form = BookForm(request.POST, instance=book) if form.is_valid(): book = form.save(commit=False) book.save() return redirect('book_list') # GET リクエストの時 else: form = BookForm(instance=book) return render_to_response('book_edit.html', dict(form=form, book_id=book_id), context_instance=RequestContext(request))
def update_book(xml): "Executes xml, creates book or updates inf about it." entity_id = get_id(xml) now_created = False if entity_id: # Modify existing book book = Book.objects.get(id=entity_id) else: # Create new book book = Book() now_created = True title = get_tag_text(xml, 'title') lang = get_tag_text(xml, 'lang') lang = get_language(lang) try: credit_str = get_tag_text(xml, 'credit') if credit_str: book.credit = int(credit_str) except ValueError, ex: raise InputDataServerException(ex)
def test_book(self): """ tests book response""" client = Client() lang = Language(id=0) lang.save() book = Book(title="Book", language=lang) book.save() book_id = book.id response = client.get('/book.atom/id%s/' %(book_id,)) print 'status code for good book request in atom', response.status_code self.failUnlessEqual(response.status_code, 200) response = client.get('/book/id%s/' %(book_id,)) print 'status code for good book request in xhtml', response.status_code self.failUnlessEqual(response.status_code, 200) response = client.get('/book.atom/id%s/' %(book_id + 1,)) print 'status code for bad book request in atom', response.status_code self.failUnlessEqual(response.status_code, 404) response = client.get('/book/id%s/' %(book_id + 1,)) print 'status code for bad book request in xhtml', response.status_code self.failUnlessEqual(response.status_code, 404)
def populate(): print('Populating Book...', end='') titles = [ '如何像電腦科學家一樣思考', '10 分鐘內學好 Python', '簡單學習 Django' '如何像電腦科學家一樣思考2', '10 分鐘內學好 Python2', '簡單學習 Django2' '如何像電腦科學家一樣思考3', '10 分鐘內學好 Python3', '簡單學習 Django3' '如何像電腦科學家一樣思考4', '10 分鐘內學好 Python4', '簡單學習 Django4' ] authors = ["張三", "李四", "王五", "趙六", "錢七"] Book.objects.all().delete() for title in titles: book = Book() book.title = title n = random.randint(0, len(authors) - 1) book.author = authors[n] book.publisher = book.author book.pubDate = datetime.datetime.today() book.price = 1000 book.save() print('done')
def book_listing_view(request): template_name = "books_listing.html" context = {} books = Book.get_all() paginator = Paginator(books, 10) page = request.GET.get('page', 1) try: context["books"] = paginator.page(page) except PageNotAnInteger: context["books"] = paginator.page(1) except EmptyPage: context["books"] = paginator.page(paginator.num_pages) context["page_title"] = "Books in stock" context["page"] = page return render(request, template_name, context)
def make_order_view(request): context = {} template_name = "make_order.html" user = CustomUser.get_by_id(request.user.id) if request.method == "GET": form = MakeOrderForm(request.GET) if form.is_valid(): book = Book.get_by_id(request.GET.get("book").split("//")[1]) date = form.data["plated_end_at"] new_order = Order.create(user=user, book=book, plated_end_at=date) return redirect("order_details", pk=new_order.id) else: form = MakeOrderForm() context["page_title"] = "Make order" context["form"] = form return render(request, template_name, context)
def test_post_request_for_book_in_db(client): new_book = Book(title="4H work week") db.session.add_all([new_book]) db.session.commit() rs = client.post("/request", json={ "email": "*****@*****.**", "title": "4H work week" }) assert rs.status_code == 200 ret_dict = rs.json assert ret_dict["data"]["email"] == "*****@*****.**" assert ret_dict["data"]["title"] == "4H work week" assert ret_dict["data"]["id"] is not None assert ret_dict["data"]["timestamp"] is not None
def do_import(data, if_book_exists='continue'): """import a book in the database. Expects a dict of the following format: { 'publisher': (u'oreilly', u"Farnham ; O'Reilly, 2002 printing, c2003."), 'authors': [(u'ray_randy_j', u'Ray, Randy J.'), (u'kulchenko_pavel', u'Kulchenko, Pavel')], 'subjects': [(u'perl_computer_program_language', u'Perl (Computer program language)'), (u'internet_programming', u'Internet programming')], 'language': u'eng', 'title': u'Programming Web services with Perl', 'ddc': u'5.2762', 'long_title': None, 'edition_info': u'', 'summary': None } which other importers have to deliver. if_book_exists may be eighter one of 'continue', 'overwrite', 'error' """ try: book = Book.objects.get(isbn=data['isbn']) except Book.DoesNotExist: book = Book(isbn=data['isbn'], title=data['title'], long_title=data.get('long_title'), language=data.get('language'), ddc=data.get('ddc'), edition_info=data.get('edition_info'), summary=data.get('summary')) try: publisher = Publisher.objects.get(publisher_id=data['publisher'][0]) except Publisher.DoesNotExist: publisher = Publisher(publisher_id=data['publisher'][0], name=data['publisher'][1]) publisher.save() book.publisher = publisher for authordata in data['authors']: try: author = Author.objects.get(author_id=authordata[0]) except Author.DoesNotExist: author = Author(author_id=authordata[0], name=authordata[1]) author.save() book.authors.add(author) for subjectdata in data['subjects']: try: subject = Subject.objects.get(subject_id=subjectdata[0]) except Subject.DoesNotExist: subject = Subject(subject_id=subjectdata[0], name=subjectdata[1]) subject.save() book.subjects.add(subject) book.save() else: if if_book_exists.lower() == "error": raise ValueError("Book %s already exists!" % data['isbn']) elif if_book_exists.lower() == "overwrite": book.delete() do_import(data) elif if_book_exists.lower() != "continue": raise ValueError("if_book_exists must be eighter one of 'continue', 'overwrite', 'error'")
def create_book(request): """ @note: 添加图书信息 """ models = request.POST.get("models", "{}") models_json = json.loads(models) print models_json try: datalist = [] for data in models_json: if Book.objects.filter(title=data["title"]): return HttpResponse(json.dumps({"result": False, "message": u"书籍 %s 的信息已存在!" % data["title"]})) else: print "create" print data["publication_date"] print data["authors"] print data["publisher"] publisher = Publisher.objects.filter(name=data["publisher"])[0] print publisher book = Book() book.title = data["title"] book.publication_date = gt(data["publication_date"]) book.publisher = publisher book.price = data["price"] book.save() # 解析authors并添加 authors = data["authors"].split(",") authorlist = [] for name in authors: authorlist.append(Author.objects.filter(name=name)[0]) print authorlist for author in authorlist: book.authors.add(author) datalist.append(data) except Exception, e: print e return HttpResponse(json.dumps({"result": False, "message": u"添加记录失败, %s" % e}))
def add_doc_form(request): """ Displays form for converting and adding book in doc """ if request.method == "POST": form = DocCreateForm(request.POST, request.FILES) if form.is_valid(): temp_name = tempfile.mkstemp()[1] cd = form.cleaned_data properties = BookProperties(temp_name, cd['title'].encode("utf-8")) properties.language = cd['language'] properties.author = request.user.first_name + ' ' + request.user.last_name properties.subject = cd['subject'].encode("utf-8") properties.description = cd['description'].encode("utf-8") properties.genre = cd['type'].encode("utf-8") properties.date = cd['date'].encode("utf-8") properties.rights = cd['rights'].encode("utf-8") properties.author = request.user.first_name + " " + request.user.last_name file = request.FILES['file'] doc_file_name = tempfile.mkstemp()[1] doc_file = open(doc_file_name, 'wb') doc_file.write(file.read()) doc_file.close() doc_parser = DocParser(doc_file_name, properties) out_file_name = tempfile.mkdtemp() + "tmp.html" doc_parser.parse() try: language = Language.objects.get(short=cd['language']) except: return render_response(request, "epub/add_doc_form.html", {'errors': [_('No such language.')], 'user': request.user, 'menu_on': True, 'form': form}) lang_code = LANG_CODE[0] for lang_code in LANG_CODE: if lang_code[0] == cd['language']: break book_model = Book(language=language, title = cd['title'].encode("utf-8"), pagelink="") try: author = Author.objects.get(name=request.user.first_name + ' ' + request.user.last_name) except: author = Author.objects.create(name=request.user.first_name + ' ' + request.user.last_name) book_model.save() book_model.author = [author] ebook = EpubBook.objects.create(book=book_model) print "creating" ebook.name.save(cd['title'].encode("utf-8") + ".epub", _ExistingFile(temp_name)) try: book_file = BookFile(link="/" + MEDIA_URL + "/uploads/" + quote(cd['title'].encode("utf-8")) + '.epub') book_file.type = 'epub' book_file.save() except: return render_response(request, "epub/add_doc_form.html", {'errors': [_("Book name should be unique")], 'menu_on': True, 'form': form}) book_model.book_file = [book_file] book_model.save() ebook.save() hrr = HttpResponseRedirect("/book/id%d" % book_model.id) return hrr else: form = DocCreateForm() return render_response(request, "epub/add_doc_form.html", {'user': request.user, 'menu_on': True, 'form': form})
def add_book(request): context = dict() if request.method == "POST": if "url" in request.POST: url = request.POST["url"] context = parse_book_by_isbn(url) return render(request, "book/add.html", context) if "isbn" in request.POST: isbn = request.POST["isbn"] context = parse_book_by_isbn(isbn) book = Book() book.title = context["title"] book.publisher = context["publisher"] book.isbn = context["isbn"] book.url = context["url"] book.ispersonal = int(True) book.ownerid = request.user.id book.summary = context["summary"] book.price = context["price"] book.numraters = 0 book.averageRate = 3 book.created_date = datetime.datetime.now() book.updated_date = datetime.datetime.now() book.author = context["author"][0] book.authorinfo = context["author_intro"][0:4090] # print book.authorinfo book.catelog = context["catalog"][0:4090] book.pubdate = context["pubdate"] book.ispublic = int(True) book.imgurl = context["images"] book.city = Dper.objects.get(user_id=request.user.id).city book.bookcount = 1 book.status = 1 # Dper.objects.filter(id=request.user.id)[0].city book.save() # save tags of book for val in context["tags"]: tag = Tag() tag.value = val tag.createdate = datetime.datetime.now() tag.save() rel = Booktag() rel.tagid = tag.id rel.bookid = book.id rel.save() return redirect("/book/library", context) else: form = BookForm() context["form"] = form return render(request, "book/add.html", context)
def upd_all_book(book_parser): """更新所有小说信息""" #global g_books #bt = time.time() for l in book_parser.book_list: l['Alias'] = l['Name'] + '_' + l['Author'] l['Alias_Host'] = l['Alias'] + '_' + book_parser.host_name l['Alias_Author'] = l['Author'] + '_' + book_parser.host_name l['is_new_book'] = config.Yes l['is_new_bookinfo'] = config.Yes l['is_new_contentinfo'] = config.Yes l['is_new_author'] = config.Yes for b in config.g_books: if (l['Alias'].decode(config.SYS_ENCODING)==b['Alias']): l['book_id'] = b['id'] l['is_new_book'] = config.No break if (l['is_new_book']): for a in config.g_authors: if (l['Alias_Author'].decode(config.SYS_ENCODING)==a['Alias']): #print l['Author'].decode(config.SYS_ENCODING), a['Name'] l['author_id'] = a['id'] l['is_new_author'] = config.No break for bi in config.g_bookinfos: if (l['Alias_Host'].decode(config.SYS_ENCODING)==bi['Alias']): l['bookinfo_id'] = bi['id'] l['is_new_bookinfo'] = config.No break #if (l.has_key('bookinfo_id')) and (config.g_contentinfos.has_key(l['bookinfo_id'])): try: if (config.g_contentinfos[l['bookinfo_id']] == l['Content_Url']): l['is_new_contentinfo'] = config.No #else: #config.g_contentinfos[l['bookinfo_id']] = l['Content_Url'] except KeyError: pass #print "step 1 use time: %f" % (time.time()-bt) #bt = time.time() k = 0 for b in book_parser.book_list: if (book_parser.is_origin): if (b.has_key('is_new_book') and (b['is_new_book'])): if (b.has_key('is_new_author') and (b['is_new_author'])): author = Author() author.Name = b['Author'].decode(config.SYS_ENCODING) author.Alias = b['Alias_Author'].decode(config.SYS_ENCODING) author.save() b['author_id'] = author.id config.g_authors.append(model_to_dict(author)) book = Book() book.Name = b['Name'].decode(config.SYS_ENCODING) book.Alias = b['Alias'].decode(config.SYS_ENCODING) book.author_id = b['author_id'] book.save() config.g_books.append(model_to_dict(book)) b['book_id'] = book.id b['is_new_book'] = config.No b['is_new_author'] = config.No if (b.has_key('is_new_bookinfo') and b.has_key('is_new_book')): if ((b['is_new_bookinfo']) and (not b['is_new_book'])): bookinfo = BookInfo() bookinfo.book_id = b['book_id'] bookinfo.HostName = book_parser.host_name bookinfo.BookUrl = b['Book_Url'] bookinfo.Alias = b['Alias_Host'].decode(config.SYS_ENCODING) bookinfo.LastContent = b['Content'].decode(config.SYS_ENCODING) bookinfo.ContentUrl = b['Content_Url'] bookinfo.LastUpdated = time.time() bookinfo.save() config.g_bookinfos.append(model_to_dict(bookinfo)) b['bookinfo_id'] = bookinfo.id b['is_new_bookinfo'] = config.No """ else: bookinfo = BookInfo.objects.get(id=b['bookinfo_id']) bookinfo.LastContent = b['Content'].decode(config.SYS_ENCODING) bookinfo.ContentUrl = b['Content_Url'] bookinfo.LastUpdated = time.strftime('%Y-%m-%d %H:%M', time.localtime()) bookinfo.save() """ if (b.has_key('is_new_contentinfo') and b.has_key('is_new_book')): if ((b['is_new_contentinfo']) and (not b['is_new_book'])): k = k + 1 cinfo = ContentInfo() cinfo.bookinfo_id = b['bookinfo_id'] cinfo.LastContent = b['Content'].decode(config.SYS_ENCODING) cinfo.ContentUrl = b['Content_Url'] cinfo.LastUpdated = time.strftime('%Y-%m-%d %H:%M', time.localtime()) cinfo.save() config.g_contentinfos[b['bookinfo_id']] = b['Content_Url'] b['is_new_contentinfo'] = config.No
def edit_book_save(request): action = request.POST.get("action") book_id = request.POST.get("book_id") subject = request.POST.get("subject") summary = request.POST.get("content") open_yn = request.POST.get("open_yn") ccl_left = request.POST.get("ccl_left") ccl_right = request.POST.get("ccl_right") adv_yn = request.POST.get("adv_yn") adv_content = request.POST.get("adv_content") adv_mobile_content = request.POST.get("adv_mobile_content") book = Book.objects.get(id=book_id) if request.user not in book.user.all() and not request.user.is_superuser: request.session["error_message"] = u"수정권한이 없습니다" return redirect('/book/%s' % book.id) if action == "modify": form = BookEditForm(request.POST) if not form.is_valid(): request.session["error"] = form else: reversion_comments = [] if book.subject != subject: reversion_comments.append(u"제목") if book.summary != summary: reversion_comments.append(u"책요약") if book.open_yn != open_yn: reversion_comments.append(u"공개여부") if book.ccl_left != ccl_left or book.ccl_right != ccl_right: reversion_comments.append(u"저작권") book.subject = subject book.summary = summary book.open_yn = open_yn book.ccl_left = ccl_left book.ccl_right = ccl_right book.adv_yn = adv_yn book.adv_content = adv_content book.adv_mobile_content = adv_mobile_content book.modify_time = datetime.datetime.now() if 'image' in request.FILES: file_content = ContentFile(request.FILES['image'].read()) book.image.save(request.FILES['image'].name, file_content) reversion_comments.append(u"이미지") resize_image(book.image.path, width=100, height=130) if reversion_comments: reversion.set_comment(u"%s (이)가 변경되었습니다." % u", ".join(reversion_comments)) book.save() request.session["edit_message"] = u"책이 수정되었습니다" elif action == "add": book = Book(subject=subject, summary=summary, open_yn=open_yn, ccl_left=ccl_left, ccl_right=ccl_right, creator=request.user) book.save() book.user.add(request.user) page = Page(book=book, subject="FrontPage") page.save() if 'image' in request.FILES: file_content = ContentFile(request.FILES['image'].read()) book.image.save(request.FILES['image'].name, file_content) request.session["edit_message"] = u"책이 추가되었습니다" elif action == "delete": book.delete() # request.session["edit_book_message"] = u"책이 삭제되었습니다" # rearrange_page(page.book) cache_clear(book) if action == "delete": return redirect("/") else: return redirect("/edit/book/%s" % book.id)
def read_fb2(book_file): ''' extract information about book from fb2, adds book to data base ''' digits = "0123456789" link = book_file.link try: webFile = urllib2.urlopen(link) except: return filename = "downloads/" + link.split('/')[-1] localFile = open(filename, 'w') localFile.write(webFile.read()) webFile.close() localFile.close() if link.endswith('.zip'): # TODO file = zipfile.ZipFile(filename, "r") data = None for i in file.namelist(): data = file.read(i) file.close() else: file = open(filename, 'r') data = file.read() file.close() beaut_soup = bs.BeautifulSoup(data) title_info = beaut_soup.find('title-info') author_tag = title_info.find('author') if author_tag: author_string = author_tag.find('first-name').getText().lower() + " " middle_name = author_tag.find('middle-name') if middle_name: author_string += middle_name.getText().lower() + " " author_string += author_tag.find('last-name').getText().lower() else: os.remove(filename) return if not author_string: os.remove(filename) return ind = author_string.find(" trans by ") if ind != -1: author_string = author_string[:ind] ind = author_string.find(" translated ") if ind != -1: author_string = author_string[:ind] ind = author_string.find(" adapted ") if ind != -1: author_string = author_string[:ind] ind = author_string.find(" by ") if ind != -1: author_string = author_string[:ind] for c in digits: author_string = author_string.replace(c, '') author_string = author_string.title().strip() title_string = title_info.find('book-title').getText() if not title_string: os.remove(filename) return ind = title_string.find(" trans by ") if ind != -1: title_string = title_string[:ind] ind = title_string.find(" translated ") if ind != -1: title_string = title_string[:ind] ind = title_string.find(" adapted ") if ind != -1: title_string = title_string[:ind] ind = title_string.find(" by ") if ind != -1: title_string = title_string[:ind] lang_tag = title_info.find('lang') if lang_tag: lang_string = lang_tag.getText() if lang_string: try: language = Language.objects.get(short=lang_string) #TODO language except: try: language = Language.objects.get(short=lang_string[0:2]) #TODO language except: language = Language.objects.get(short="?") else: language = Language.objects.get(short="?") else: language = Language.objects.get(short="?") author = Author.objects.get_or_create(name=author_string)[0] book = author.book_set.filter(title=title_string.strip()) if book: book[0].book_file.add(book_file) else: book = Book(title=title_string, language=language) book.save() book.book_file.add(book_file) book.author.add(author) print 'Added book: ', "Title: ", title_string, " Author: ", author_string description_tag = title_info.find('annotation') if description_tag: description_string = description_tag.getText() if description_string: ann = Annotation.objects.get_or_create(name=description_string.strip(), book=book) tag_tags = title_info.findAll('genre') for tag_tag in tag_tags: if tag_tag: tag_string = tag_tag.getText() if tag_string: for c in digits: tag_string = tag_string.replace(c, '') tags = smart_split([tag_string], [',', '/', '_', '--']) for tag_name in tags: if len(tag_name) > 25: continue tag = Tag.objects.get_or_create(name=tag_name.title().strip()) book.tag.add(tag[0]) os.remove(filename)
def book_input_auto(): book_list = get_data('book_out.txt') from book.models import Book from book.models import Taxonomy for b in book_list: bs = None if b[6] != '': bs = Book.objects.filter(isbn=b[6]) if bs is None or not bs.exists(): bs = Book.objects.filter(name=b[0], version=b[7]) if not bs.exists(): try: book = Book() book.name = b[0] book.subtitle = b[1] if b[2] is None: book.author = '' else: book.author = b[2] if b[3] is None: book.press = '' else: book.press = b[3] book.price_ori = b[4] if b[5] is None or b[5] == 0: book.price_now = 0.4*b[4] else: book.price_now = b[5] book.isbn = b[6] book.version = b[7] book.publication_date = b[8] book.page_number = b[9] book.size = b[10] book.binding = b[11] if b[12] == 'zh': book.language = 'zh' else: book.language = 'en' if b[13] is None: book.translator = '' else: book.translator = b[13] book.status = 4 book.save() try: if b[14] is not None and b[14] != '': t = Taxonomy.objects.get(name=TAXONOMY_DICT[b[13]]) book.add_taxonomy(t) except Exception, e: print "Add taxonomy failed" print e print book_list.index(b) print b import pdb;pdb.set_trace() except Exception, e: print e print book_list.index(b) print b
def add_book(request): context = dict() if request.method == 'POST': if 'url' in request.POST: url = request.POST['url'] context = parse_book_by_url(url) return render(request, 'book/add.html', context) if 'bookid' in request.POST: bookid = request.POST['bookid'] context = parse_book_by_id(bookid) book = Book() book.title = context['title'] book.publisher = context['publisher'] book.isbn = context['isbn10'] if 'isbn10' in context else context['isbn13'] book.url = context['url'] book.ispersonal = int(True) book.ownerid = request.user.id book.summary = context['summary'] book.price = context['price'] book.numraters = 0 book.averageRate = 3 book.created_date = datetime.datetime.now() book.updated_date = datetime.datetime.now() book.author = context['author'][0] book.pubdate = context['pubdate'] book.ispublic = int(True) book.imgurl = context['images'] book.save() #save tags of book for val in context['tags']: tag = Tag() tag.value = val tag.createdate = datetime.datetime.now() tag.save() rel = Booktag() rel.tagid = tag.id rel.bookid = book.id rel.save() return redirect('/book/library', context) else: form = BookForm() context['form'] = form return render(request, 'book/add.html', context)