コード例 #1
0
ファイル: views.py プロジェクト: CClerville/LitHub
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})
コード例 #2
0
ファイル: views.py プロジェクト: umangv/LitHub
def maintenance(request):
    if not request.user.is_superuser:
        return render(request, "bookswap/maint_goaway.html")
    if request.method == "POST":
        results = {}
        gbook_info = utils.get_book_details("9780099572831")
        results["gbook"] = gbook_info.has_key("title")
        gbook_img = gbook_info.get("thumbnail_url", " ")
        try:
            email = EmailMessage(subject="LitHub Maintenance", body="Yup, you"
                    " got it", to=[request.user.email])
            email.send()
            results["email"] = True
        except:
            results["email"] = False
        results["fb_at"] = request.session.has_key("fb_at")
        copy = request.user.copy_set.filter(soldTime=None)[0]
        results["fb_og"] = utils.opengraph_list_book(request, copy)
        # Count number of successes
        successes = results.values().count(True)
        # Convert True/False to "success"/"failure"
        results_class = dict([(k,("success" if v else "failure"))
            for k,v in results.items()])
        return render(request, "bookswap/maint_results.html",
                {"results":results_class, "gbook_img": gbook_img, "successes":
                    successes})
    return render(request, "bookswap/maint_confirm.html")
コード例 #3
0
ファイル: admin.py プロジェクト: umangv/LitHub
 def update_thumbnail(self, request, queryset):
     from utils import get_book_details
     for b in queryset:
         info = get_book_details(b.isbn)
         if info:
             b.thumbnail_url = info['thumbnail_url']
         b.save()
     self.message_user(request, "%s rows updated"%queryset.count())
コード例 #4
0
ファイル: views.py プロジェクト: umangv/LitHub
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')
コード例 #5
0
def main():
    args = get_args()

    books_dir = os.path.join(args.dest_folder, "books")
    images_dir = os.path.join(args.dest_folder, "images")
    json_filepath = args.json_path or os.path.join(
        args.dest_folder,
        "books.json",
    )

    links = get_links_from_pages(args.start_page, args.end_page)
    description = []

    if not links:
        logging.warning("No files to download :(")
        return None
    else:
        logging.info(f"Going to download {len(links)} files...")

    for id, link in enumerate(links):
        try:
            html = get_text_from_url(link, allow_redirects=True)
            if not html:
                raise EmptyHTMLError("Book Page html is empty")
            details = get_book_details(html, link)
            if not details:
                raise EmptyDetailsError("Details is empty")

            if not args.skip_imgs:
                image_filename = get_name_from_url(details["img_url"])
                path = os.path.normcase(
                    os.path.abspath(os.path.join(images_dir, image_filename)))

                details["img_src"] = path
                download_image(from_=details["img_url"], to=details["img_src"])

            if args.skip_txt:
                continue
            book_filename = f"{id}.{details['title']}.txt"
            path = os.path.normcase(
                os.path.abspath(os.path.join(books_dir, book_filename)))
            details["book_path"] = path
            txt_id = get_id_from_book_url(link)
            if not txt_id:
                continue
            download_txt(
                from_=BASE_TXT_URL,
                to=details["book_path"],
                urlparams={"id": txt_id},
            )

            logging.info(f"File '{book_filename}' has been saved")

            description.append(details)

        except (
                HTTPError,
                ParseError,
                ConnectionError,
                FileExistsError,
                EmptyBookError,
                EmptyImageError,
                EmptyHTMLError,
                URLParseError,
        ) as e:
            logging.error(e)

    make_description({"books": description}, json_filepath)
    logging.info(f"Files are downloaded, description in {json_filepath}")