def get_book_details(isbn_no): try: isbn_no = isbn.clean_isbn(isbn_no) lookup_url = "https://www.googleapis.com/books/v1/volumes?" opts = {'q':'isbn:%s'%isbn_no} if hasattr(settings, "GOOGLE_API_KEY"): opts['key'] = settings.GOOGLE_API_KEY google_resp = urllib2.urlopen(lookup_url + urlencode(opts)) results = json.loads(google_resp.read()) google_resp.close() if int(results['totalItems']) > 0: info = {} # Choose the first item, regardless of anything else item = results['items'][0] vol = item['volumeInfo'] info['title'] = vol.get('title') authors = vol.get('authors') if len(authors) > 1: info['author'] = "%s and %s"%(", ".join(authors[:-1]), authors[-1]) else: info['author'] = authors[0] info['copyrightYear'] = vol.get('publishedDate').split("-")[0] info['publisher'] = vol.get('publisher') return info except Exception: return None
def sell_new(request, isbn_no): # If an exception is raised at this stage # it's not our responsibility to be nice. No well meaning # user will see an error page at this stage isbn_no = isbn.clean_isbn(isbn_no) if request.method == 'POST': book_form = SellNewBookForm(request.POST, prefix="book") copy_form = SellExistingBookForm(request.POST, prefix="copy") if book_form.is_valid() and copy_form.is_valid(): book = book_form.save(commit=False) book.isbn = isbn_no book.save() copy = copy_form.save(commit=False) copy.book = book copy.owner = request.user copy.pubDate = datetime.now() copy.save() messages.success(request, "Your copy of `%s` is now on sale."%\ book.title) return redirect('bookswap.views.book_details', book.id) else: info = utils.get_book_details(isbn_no) book_form = SellNewBookForm(prefix="book", initial=info) copy_form = SellExistingBookForm(prefix="copy") return render(request, "bookswap/sell_new.html", {'book_form':book_form, 'copy_form':copy_form, 'isbn_no':isbn_no})
def search_books(request): if request.method == "POST": if request.POST.get('action') == 'isbn_search': try: isbn_no = isbn.clean_isbn(request.POST.get("isbn","0")) return redirect(book_by_isbn, isbn_no=isbn_no) except ValueError: messages.error(request, "Please enter a valid ISBN number") return render(request, "bookswap/home.html", {'search_isbn':request.POST.get('isbn','')}) title = request.GET.get('title', '') author = request.GET.get('author', '') if title or author: books = Book.objects.filter( copy__soldTime=None, title__icontains=title, author__icontains=author)\ .annotate( num_copies=Count('copy', distinct=True), num_sub=Count('subscribers', distinct=True))\ .order_by('-num_copies', '-num_sub') results = utils.PaginatorN(books, request) return render(request, "bookswap/results.html", {"results":results.page_auto(), 'search_title':title, 'search_author':author}) else: return redirect(all_books)
def book_by_isbn(request, isbn_no): try: isbn_no = isbn.clean_isbn(isbn_no) books = Book.objects.filter(isbn=isbn_no) results = [(b, len(b.copy_set.all().filter(soldTime=None))) for b in books] results.sort(reverse=True, key=lambda x:x[1]) except ValueError: results = [] return render(request, "bookswap/book_isbn.html", {"results":results, 'search_isbn':isbn_no})
def sell_step_search(request): """This step helps identify the book the user is trying to sell""" if request.method == "POST": isbn_no = request.POST.get('isbn', '') try: isbn_no = isbn.clean_isbn(isbn_no) books = Book.objects.filter(isbn=isbn_no) results = [(b, b.copy_set.filter(soldTime=None).count()) \ for b in books] if results: results.sort(reverse=True, key=lambda x:x[1]) return render(request, "bookswap/sell_select_book.html", {'results':results, 'isbn_no':isbn_no}) else: return redirect('bookswap.views.sell_new', isbn_no) except ValueError: messages.error(request, "Invalid ISBN code") return render(request, "bookswap/sell_search.html")
def search_books(request): if request.method == "POST": if request.POST.get('action') == 'isbn_search': try: isbn_no = isbn.clean_isbn(request.POST.get("isbn","0")) return redirect(book_by_isbn, isbn_no=isbn_no) except ValueError: messages.error(request, "Please enter a valid ISBN number") title = request.GET.get('title', '') author = request.GET.get('author', '') if title or author: books = Book.objects.filter( title__contains=title, author__contains=author) results = [(b, len(b.copy_set.filter(soldTime=None))) for b in books] results.sort(reverse=True, key=lambda x:x[1]) return render(request, "bookswap/results.html", {"results":results}) else: return render(request, 'bookswap/search.html')
def subscribe_to_new(request, isbn_no): try: isbn_no = isbn.clean_isbn(isbn_no) if request.method == "POST": if request.POST.get('verify_book') == 'on': if "isbn_%s"%isbn_no in request.session: info = request.session["isbn_%s"%isbn_no] book = Book(isbn=isbn_no, title=info['title'], author=info['author'], copyrightYear=info['copyrightYear'], publisher=info['publisher'], thumbnail_url=info['thumbnail_url']) book.save() book.subscribers.add(request.user) messages.success(request, ("You've been subscribed "+\ "to %s by %s. You will be notified when a " +\ "copy of this book is available.")%(book.title, book.author)) return redirect(book_details, book_id=book.id) else: messages.error(request, "Sorry, there was an error " +\ "reading data. Please try again or inform "+\ "us about this problem.") else: messages.error(request, "Please verify that this is the book"+\ " you are looking for.") info = utils.get_book_details(isbn_no) request.session['isbn_%s'%isbn_no] = info if info and info['title']: return render(request, "bookswap/subscribe_new.html", {'info':info, 'isbn_no':isbn_no}) else: messages.info(request, "Sorry. We tried to find more "+\ "information about the book you requested, but were" +\ " not able to find any. If you " +\ "would like to be notified when this book is available" +\ " please inform us using the contact page above. " +\ "Please include all relevant book details, such as "+\ "ISBN number, title and author.") return redirect("home") except ValueError: messages.error(request, "Invalid ISBN number") return redirect('home')
def sell_step_search(request): """This step helps identify the book the user is trying to sell""" if request.method == "POST": isbn_no = request.POST.get('isbn', '') try: isbn_no = isbn.clean_isbn(isbn_no) books = Book.objects.filter(copy__soldTime=None, isbn=isbn_no)\ .annotate( num_copies=Count('copy', distinct=True), num_sub=Count('subscribers', distinct=True))\ .order_by('-num_copies', '-num_sub') if books: return render(request, "bookswap/sell_select_book.html", {'results':books, 'isbn_no':isbn_no}) else: return redirect('bookswap.views.sell_new', isbn_no) except ValueError: messages.error(request, "Invalid ISBN code") return render(request, "bookswap/sell_search.html")
def book_by_isbn(request, isbn_no): try: isbn_no = isbn.clean_isbn(isbn_no) books = Book.objects.filter(isbn=isbn_no)\ .annotate( num_copies=Count('copy', distinct=True), num_sub=Count('subscribers', distinct=True))\ .order_by('-num_copies', '-num_sub') except ValueError: books = [] if not books: messages.info(request, "The book you were looking for is currently " +\ "not on sale. We're now looking for more information so that you"+\ " can sign up to be notified when this book becomes available. "+\ "Other users will be able to see the number of subscribers for"+\ " each book, helping them decide which books "+\ "to sell.") return redirect(subscribe_to_new, isbn_no) results = utils.PaginatorN(books, request) return render(request, "bookswap/book_isbn.html", {"results":results.page_auto(), 'search_isbn':isbn_no})
def clean_isbn(self): try: return isbn.clean_isbn(self.cleaned_data['isbn']) except ValueError: raise forms.ValidationError('Invalid ISBN')