示例#1
0
 def get(self):
     
     # Get all the displayable books
     books_query = Book.query(ancestor=ROOT_BOOK_KEY)  
     # Get the books currently in the cart
     cart_query = []
     
     # check for a person and filter the books
     if self.person:
         books_query = books_query.filter(ndb.OR(Book.cart_key == None, Book.cart_key == self.person.key))
         cart_query = self.person.get_cart()
     else:
         # remove all the books that are in someone's cart
         books_query = books_query.filter(Book.cart_key == None)    
     books_query = books_query.order(-Book.last_touch_date_time)
     
     # Get additional details needed to populate lists
     dept_query = Department.query(ancestor=ROOT_DEPT_KEY).order(Department.abbrev)
     book_conditions = Book.get_conditions()
     
     self.values.update({"books_query": books_query,
                         "cart_query" : cart_query,
                         "dept_query": dept_query, 
                         "book_conditions": book_conditions})        
     self.render(**self.values)
示例#2
0
def books():
    book_edit_form_errors = None
    book_edit_forms = []
    # generate book edit forms
    for book in Book.query.all():
        book_edit_form = BookEditForm()
        writers = Writer.query.all()
        book_edit_form.writers.data = [writer.id for writer in book.writers]
        book_edit_form.title.data = book.title
        book_edit_form.id.data = book.id
        book_edit_forms.append(book_edit_form)

    if request.method == 'GET':
        book_add_form = BookAddForm()
    else:
        if request.form['btn'] == 'Edit':
            book_add_form = BookAddForm()
            book_edit_form_errors = BookEditForm(request.form)
            if book_edit_form_errors.validate():
                writers = Writer.query.filter(Writer.id.in_(book_edit_form_errors.writers.data)).all()
                book = Book.query.filter(Book.id == book_edit_form_errors.id.data).first()
                book.edit(title=book_edit_form_errors.title.data, writers=writers)
                return redirect(url_for('books'))
        else:
            book_add_form = BookAddForm(request.form)
            if book_add_form.validate():
                writer_ids = [writer.id for writer in book_add_form.writers.data]
                writers = Writer.query.filter(Writer.id.in_(writer_ids)).all()
                Book.add(title=book_add_form.title.data, writers=writers)
                return redirect(url_for('books'))
    return render_template('books.html', book_add_form=book_add_form,
        book_edit_forms=book_edit_forms, book_edit_form_errors=book_edit_form_errors)
示例#3
0
 def post(self, arg):
   book = Book(title     = self.request.get('title', None), 
               pages     = self.get_int_param('pages'),
               locations = self.get_int_param('locations'),
               page      = self.request.get('page', "Page"))
   book.put()
   self.redirect('/admin/books/%s/' % book.slug)
示例#4
0
文件: views.py 项目: stafary/lab4
def add_book(request):
    if request.method =="POST":
        form = newBook(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            try:
                author =  Author.objects.get(Name = cd["Author"])
            except:
                request.session["ISBN"] = cd["ISBN"]
                request.session["Title"] = cd["Title"]
                request.session["Publisher"] = cd["Publisher"]
                request.session["PublishDate"] = (str)(cd["PublishDate"])
                request.session["Price"] = (str)(cd["Price"])
                return HttpResponseRedirect("/add_author/?author=%s"%cd["Author"])  
            b = Book(ISBN = cd["ISBN"],
                     Title = cd["Title"],
                     AuthorID = author,
                     Publisher = cd["Publisher"],
                     PublishDate = cd["PublishDate"],
                     Price = cd["Price"]
                     )
            b.save()
            return HttpResponseRedirect("/success/")
    else:
        form = newBook()
    return render_to_response("add_book.html",{"form":form})
示例#5
0
def add_book(request):
    """ 添加书籍"""
    if request.POST:
        post = request.POST
        flag = 0
        name_Set = post["authorname"]
        author_name =Author.objects.filter(name = name_Set)
        if(len(author_name) == 0):
            flag = 0
            book_count = Book.objects.all().count()
            book_sum=Context({"Book_count":book_count, "flag":flag})
            return render_to_response("addbook.html",book_sum)
        else:
            author_id =Author.objects.get(name = name_Set)
            new_book = Book(
                ISBN=post['ISBN'],
                Title = post['Title'],
                Publisher=post['Publisher'],
                PublishDate = post['PublishDate'],
                Price = post['Price'],
                Authorname = post['authorname'],
                Authorid = author_id)
            new_book.save()
            flag = -flag
            book_count = Book.objects.all().count()
            book_sum=Context({"Book_count":book_count,"flag":flag})
            return render_to_response("addbook.html",book_sum)   
    else:
        flag = 0
        book_count = Book.objects.all().count()
        book_sum=Context({"Book_count":book_count,"flag":flag})
        return render_to_response("addbook.html",book_sum)
示例#6
0
文件: views.py 项目: clllyw/lab4
def add(request):
    if request.POST:
        post = request.POST
        if (
            post["ISBN"]
            and post["Title"]
            and post["AuthorID"]
            and post["Publisher"]
            and post["PublishDate"]
            and post["Price"]
        ):
            post = request.POST
            new_book = Book(
                ISBN=post["ISBN"],
                Title=post["Title"],
                AuthorID=post["AuthorID"],
                Publisher=post["Publisher"],
                PublishDate=post["PublishDate"],
                Price=post["Price"],
            )
            new_book.save()

        #
        #        new_author = Author(
        #        AuthorID = post["AuthorID"],
        #        Name = post["Name"],
        #        Age = post["Age"],
        #        Country = post["Country"])
        #        new_author.save()
        else:
            return HttpResponse("Please full all information.")
    return render_to_response("add.html")
示例#7
0
def loaddir(directory, clear=False):
    if clear:
        Book.objects.all().delete()

    queue = os.listdir(directory)
    while queue:
        next = queue.pop()
        if next[0] == '.': continue
        if next in ('categories', 'template'): continue
        next = path.join(directory, next)
        if path.isdir(next):
            queue.extend([
                path.join(next,f) for f in os.listdir(next)
                ])
            continue

        filecontent = file(next).read()
        header, content = filecontent.split('\n---\n')
        header = yaml.load(header)
        content = preprocess_rst_content(content)
        review_date = parsedate(header['review_date'])
        review_date = time.strftime('%Y-%m-%d', review_date)
        B = Book(slug=header['slug'], title=header['title'], booktitle=header['booktitle'], author=header['author'], content=content, review_date=review_date)
        B.save()
        for c in header.get('tags','').split():
            B.tags.add(tag_for(c))
示例#8
0
    def addBook(self, request):
        """create a book."""
        self._ensureAdmin()
        b_key = ndb.Key(Book, request.sbId.upper())
        if b_key.get():
            raise endpoints.ConflictException(
                'Another book with same id already exists: %s' % request.sbId)

        email = endpoints.get_current_user().email()

        book = Book (key = b_key,
            title = request.title.lower(),
            author = request.author,
            sbId = request.sbId.upper(),
            language = request.language,
            volume = request.volume,
            isbn = request.isbn,
            price = request.price,
            notes = request.notes,
            suggestedGrade = request.suggestedGrade,
            category = request.category,
            publisher = request.publisher,
            mediaType = request.mediaType,
            editionYear = request.editionYear,
            donor = request.donor,
            comments = request.comments,
            reference = request.reference,
            createdBy = email,
            createdDate = date.today()
            )
        book.put()
        return request
示例#9
0
def test_book_can_reserve_new_book_once():
    book = Book('TITLE', 'DESCRIPTION', 'ISBN')
    book.reserve('RESERVER')

    book.reserve('RESERVER')
    assert_equals(len(book.reservations), 1)
    assert_in('RESERVER', book.reservations)
示例#10
0
def test_book_can_borrow_reserved_book_if_only_reserver():
    book = Book('TITLE', 'DESCRIPTION', 'ISBN')
    book.reserve('RESERVER')

    book.check_out('RESERVER')

    assert_equals(len(book.reservations), 0)
示例#11
0
文件: catalog.py 项目: eugeneai/ZCA
 def get(self):
     db = getUtility(IRelationalDatabase)
     cr = db.cursor()
     barcode = self.book.barcode
     if barcode:
         cr.execute("""SELECT
                         id,
                         barcode,
                         author,
                         title
                       FROM books
                       WHERE barcode = ?""",
                    (barcode,))
     else:
         cr.execute("""SELECT
                         id,
                         barcode,
                         author,
                         title
                       FROM books""")
     rst = cr.fetchall()
     cr.close()
     books = []
     for record in rst:
         id = record['id']
         barcode = record['barcode']
         author = record['author']
         title = record['title']
         book = Book()
         book.id = id
         book.barcode = barcode
         book.author = author
         book.title = title
         books.append(book)
     return books
示例#12
0
文件: tests.py 项目: arnav/django
    def test_default_creation(self):
        "Objects created on the default database don't leak onto other databases"
        # Create a book on the default database using create()
        Book.objects.create(title="Pro Django",
                            published=datetime.date(2008, 12, 16))

        # Create a book on the default database using a save
        dive = Book()
        dive.title="Dive into Python"
        dive.published = datetime.date(2009, 5, 4)
        dive.save()

        # Check that book exists on the default database, but not on other database
        try:
            Book.objects.get(title="Pro Django")
            Book.objects.using('default').get(title="Pro Django")
        except Book.DoesNotExist:
            self.fail('"Dive Into Python" should exist on default database')

        self.assertRaises(Book.DoesNotExist,
            Book.objects.using('other').get,
            title="Pro Django"
        )

        try:
            Book.objects.get(title="Dive into Python")
            Book.objects.using('default').get(title="Dive into Python")
        except Book.DoesNotExist:
            self.fail('"Dive into Python" should exist on default database')

        self.assertRaises(Book.DoesNotExist,
            Book.objects.using('other').get,
            title="Dive into Python"
        )
示例#13
0
文件: app.py 项目: amumu/wyzq
def content(bid, cid):
    book = Book.get(bid)
    chapter = Chapter.get(cid, bid)
    if not (book and chapter):
        abort(404)

    # NOTE read/set cookies for recent reading
    recent_reading = request.cookies.get('recent_reading')
    rec_book_chapters = []
    if recent_reading:
        for bid_cid in recent_reading.split('|'):
            _bid, _cid = [int(id) for id in bid_cid.split(':', 1)]
            if not _bid == bid:
                if Book.get(_bid) and Chapter.get(_cid, _bid):
                    rec_book_chapters.append(
                        (Book.get(_bid), Chapter.get(_cid, _bid))
                    )
    rec_book_chapters.insert(0, (book, chapter))
    rec_book_chapters = rec_book_chapters[:10]

    resp = make_response(render_template('content.html', **locals()))
    recent_reading_str = '|'.join(['%s:%s' % (book.id, chapter.id)
                         for book, chapter in rec_book_chapters])
    resp.set_cookie('recent_reading', recent_reading_str)
    return resp
示例#14
0
 def post(self):
     "Creates a new book record from a json representation"
     
     # check we have the correct authentication ket
     auth = self.request.get("auth")
     if auth != settings.AUTH:
         return self.error(401)
     
     # get the request body
     json = self.request.body
     # convert the JSON to a Python object
     representation = simplejson.loads(json)
     # create a datastore object from the JSON
     book = Book(
         title = representation['title'],
         ident = representation['ident'],
         author = representation['author'],
         image = representation['image'],
         notes = representation['notes'],
         url = representation['url']
     )
     logging.info('Add new book request')
     try:
         # save the object to the datastore
         book.put()
         # send an email about the new book
         _email_new_book(book)
     except:
         logging.error("Error occured creating new book via POST")
         self.error(500)
示例#15
0
def post():
    form = PostForm()
    if request.method == 'GET':
        if request.args.get('isbn'):
            form.isbn.data = request.args.get('isbn')
    if form.validate_on_submit():
        isbn = form.isbn.data.strip().replace('-','').replace(' ','')
        price = form.price.data
        if price == '':
            price = None
        cond = form.condition.data
        comments = form.comments.data
        courses = form.courses.data.strip().replace(' ','').upper()
        if len(courses) > 9:
            courses = ''
        if not Book.query.get(isbn):
            info = get_amazon_info(isbn)
            image = get_amazon_image(isbn)
            b = Book(isbn=isbn, title=info['title'], author=info['author'], amazon_url=info['url'], image=image, courses=[courses])
            add_commit(db, b)
        else:
            b = Book.query.get(isbn)
            old_courses = list(b.courses)
            old_courses.append(courses)
            b.courses = list(set(old_courses))
            db.session.commit()
        p = Post(uid=current_user.id, timestamp=datetime.utcnow(), isbn=isbn, price=price,condition=cond,comments=comments)
        add_commit(db, p)
        email_subbers(p)
        return redirect(url_for('book',isbn=isbn))
    return render_template('post.html',
                           post_form = form)
示例#16
0
def test_book_can_reserve_new_book_with_more_than_one_user():
    book = Book('TITLE', 'DESCRIPTION', 'ISBN')
    book.reserve('RESERVER')
    book.reserve('ANOTHER RESERVER')

    assert_equals(len(book.reservations), 2)
    assert_equals('RESERVER', book.reservations[0])
    assert_equals('ANOTHER RESERVER', book.reservations[1])
示例#17
0
def insert_action(request):
    #try:

    inputed_isbn = request.POST['br-input-isbn']
    inputed_bcover = request.POST['br-input-bcover']
    inputed_bname = request.POST['br-input-bname']
    inputed_author = request.POST['br-input-author']
    inputed_translator = request.POST['br-input-translator']
    inputed_publisher = request.POST['br-input-publisher']
    inputed_byear = request.POST['br-input-byear']
    inputed_pagination = request.POST['br-input-pagination']
    inputed_price = request.POST['br-input-price']
    inputed_insertednum = request.POST['br-input-insertednum']

    try:
        book=Book.objects.get(isbn=inputed_isbn)

        book.bname=B(inputed_bname)
        book.author=B(inputed_author)
        book.translator=B(inputed_translator)
        book.byear=B(inputed_byear)
        book.pagination=int(inputed_pagination)
        book.price=float(inputed_price)
        # TODO : 封面应该下载到本地储存或SAE storage
        book.bcover=B(inputed_bcover)
        book.publisher=B(inputed_publisher)
        book.totalnum=book.totalnum+int(inputed_insertednum)
        book.available=book.available+int(inputed_insertednum)

        book.save()

        return HttpResponseRedirect("/success/insert")

    except Book.DoesNotExist:
        book=Book(
            isbn=B(inputed_isbn),
            bname=B(inputed_bname),
            author=B(inputed_author),
            translator=B(inputed_translator),
            byear=B(inputed_byear),
            pagination = 0,
            price=float(inputed_price),
            # TODO : 封面应该下载到本地储存或SAE storage
            bcover=B(inputed_bcover),
            publisher=B(inputed_publisher),
            totalnum=int(inputed_insertednum),
            available=int(inputed_insertednum),
            )
        if(inputed_pagination!=''):
            book.pagination=int(inputed_pagination)

        book.save()
        return HttpResponseRedirect("/success/insert")
    except Book.MultipleObjectsReturned as e: #isbn不唯一
        #TODO:其实这里新建一条记录可能比较好
        raise Exception(Book.STATIC_BOOKS_WITH_SAME_ISBN+unicode(e))
    """
示例#18
0
文件: vc.py 项目: eugeneai/ZCA
 def on_add_clicked(self, *args):
     barcode = self.ui.barcode.get_text()
     author = self.ui.author.get_text()
     title = self.ui.title.get_text()
     book = Book()
     book.barcode = barcode
     book.author = author
     book.title = title
     self.add(book)
     self.ui.list_store.append((book, barcode, author, title))
示例#19
0
文件: vc.py 项目: eugeneai/ZCA
    def book_return(self, book_barcode):
        book = Book()
        book.number = book_barcode
        bookdboperation = getAdapter(book, IDbOperation)
        book = bookdboperation.get()[0]

        circulation = Circulation()
        circulation.book = book
        circulationdboperation = getAdapter(circulation, IDbOperation)
        circulationdboperation.delete()
示例#20
0
文件: views.py 项目: epkatz/nechama
def save(request):
    form = BookForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        new_book = Book(isbn=cd['isbn'],
                        title=cd['title'],
                        author=cd['author'],
                        cover=cd['cover'])
    new_book.save()
    return HttpResponseRedirect('/')
示例#21
0
文件: views.py 项目: bilunyk/elibrary
 def dispatch_request(self):
     form = BookForm()
     form.authors.query = Author.query.all()
     if request.method == "POST":
         if form.validate_on_submit():
             obj = Book()
             form.populate_obj(obj)
             obj.save()
             return redirect("/books/")
     return render_template("book_add.html", form=form)
示例#22
0
文件: tests.py 项目: Giftovus/django
    def test_concurrent_delete(self):
        "Deletes on concurrent transactions don't collide and lock the database. Regression for #9479"

        # Create some dummy data
        b1 = Book(id=1, pagecount=100)
        b2 = Book(id=2, pagecount=200)
        b3 = Book(id=3, pagecount=300)
        b1.save()
        b2.save()
        b3.save()

        transaction.commit()

        self.assertEqual(3, Book.objects.count())

        # Delete something using connection 2.
        cursor2 = self.conn2.cursor()
        cursor2.execute('DELETE from delete_regress_book WHERE id=1')
        self.conn2._commit()

        # Now perform a queryset delete that covers the object
        # deleted in connection 2. This causes an infinite loop
        # under MySQL InnoDB unless we keep track of already
        # deleted objects.
        Book.objects.filter(pagecount__lt=250).delete()
        transaction.commit()
        self.assertEqual(1, Book.objects.count())
        transaction.commit()
示例#23
0
文件: views.py 项目: frauca/samples
def edit_book(request):
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            book = Book(title=cd['title'])
            book.put()
            return   HttpResponseRedirect('/search/?q=all')
    else:
        form = BookForm()
        logger.error ("here i am")
    return render_to_response('book_edit.html', {'form': form})
 def test_book_autodelete(self):
     note1 = Note(text='text')
     note1.save()
     note2 = Note(text='text')
     note2.save()
     book = Book(title='title')
     book.save()
     book.notes.add(*[note1, note2])
     note1.delete()
     self.assertTrue(Book.objects.all())
     note2.delete()
     self.assertFalse(Book.objects.all())
示例#25
0
文件: app.py 项目: gordio/prom_test
def books_add():
    form = BookForm(request.form)

    if request.method == "POST" and form.validate():
        new_book = Book(title=form.data.get('title'))
        new_book.authors = form.data.get('authors')
        db.session.add(new_book)
        db.session.commit()
        flash("Book added")
        return redirect(url_for('books_view_all'))

    return render_template('books/add.html', **locals())
示例#26
0
    def put(self, ident):
        "Update an existing book or create a new one"

        # check we have the correct authentication ket
        auth = self.request.get("auth")
        if auth != settings.AUTH:
            return self.error(401)

        # get the JSON from the request
        json = self.request.body
        # convert the JSON to a Python object 
        representation = simplejson.loads(json)
        # set the properties
        title = representation['title']
        ident = representation['ident']
        author = representation['author']
        image = representation['image']
        notes = representation['notes']
        url = representation['url']
        
        try:
            # retrieve the book based on its ident value
            book = Book.all().filter('ident =', ident)[0]
            book.title = title
            book.ident = ident
            book.author = author
            book.image = image
            book.notes = notes
            book.url = url
        except IndexError:
            # if we don't find a book then create one
            book = Book(
                title = title,
                ident = ident,
                author = author,
                image = image,
                notes = notes,
                url = url
            )
        logging.info("Update request for %s (%s)" % (title, ident))
        # save the object to the datastore
        try:
            # save the object to the datastore
            book.put()
            # send an email about the new book
            _email_new_book(book)            
            # we'e updated so we need to clear the cache
            memcache.delete("ws_books")
        except:
            logging.error("Error occured creating/updating \
                book %s (%s) via PUT") % (title, ident)
            self.error(500)
示例#27
0
 def test_books_with_content_returns_200(self):  
     self.assertEquals(0, Book.all().count())
     book = Book(
         title = "test",
         ident = "1",
         author = "author",
         notes = "",
         image = "http://example.com/image.gif",
         url = "http://example.com"
     )    
     book.put()   
     response = self.app.get('/books', expect_errors=True)        
     self.assertEquals("200 OK", response.status)
示例#28
0
def submit(request):
    if request.POST:    
        post = request.POST
        p=Author.objects.get(AuthorID =post["authorid"])
        new_book = Book(
            Title = post["title"],
            ISBN = post["isbn"],
            Publisher = post["pub"],
            PublishDate = post["date"],
            Price = post["price"],
            Authors=p)
        new_book.save()
        return  HttpResponseRedirect('/home/') 
示例#29
0
def new_book(request):
     t = get_template('feedback.html')
     try:

        author = Author.objects.get(name = request.GET['author'])
        date = request.GET['year']+'-'+request.GET['month']+'-'+request.GET['day']
        book = Book(title=request.GET['title'], author_id = author, publisher=request.GET['publisher'],
                    publish_date=date, price=request.GET['price'])
        book.save()
        html = t.render(Context({'text':'操作成功'}))
     except:
         html = t.render(Context({'text':'操作失败'}))
     return HttpResponse(html)
示例#30
0
def donate(request):
    authenticated = False
    donated = False
    user_admin = False
    if request.user.is_superuser and request.user.is_staff:
        user_admin = True
    if request.user.is_authenticated():
        authenticated = True

    donations = Donate.objects.values()
    form = DonateForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        smth = True
        for donation in donations:
            if 'accept' + str(donation['id_donate']) in request.POST:
                book = Book(ISBN=donation['ISBN'],
                            title=donation['title'],
                            author=donation['author'],
                            genre=donation['genre'],
                            image=donation['image']
                            )
                book.save()
                Donate.objects.filter(id_donate=donation['id_donate']).delete()
                email_user(user=request.user,
                           subject='donate book',
                           message='Your book donation for' + donation.title + ' has been accepted')
                smth = False
                break
            if 'reject' + str(donation['id_donate']) in request.POST:
                Donate.objects.filter(id_donate=donation['id_donate']).delete()
                smth = False
                email_user(user=request.user,
                           subject='donate book',
                           message='Your book donation for' + donation.title + ' has been declined')
                break
        if smth and form.is_valid():
            donation = form.save(commit=False)
            donation.user = request.user
            donation.image = form.cleaned_data['simage']
            donation.save()
            donated = True
            email_user(user=request.user,
                       subject='donate book',
                       message='Request for donating ' + donation.title + " received")
    donations = Donate.objects.values()

    return render_to_response("book_donate.html", context_instance=RequestContext(request,
                                                                                  {'authenticated': authenticated,
                                                                                   'user_admin': user_admin,
                                                                                   'donations': donations, 'form': form,
                                                                                   'donated': donated}))
示例#31
0
def create_books():
	book = load_json('books.json')
	for oneBook in book:
		#print(oneBook['title'])
		if Book.query.get(oneBook['google_id']) is None:
			isbn = oneBook.get('isbn')
			title = oneBook.get('title')
			try:
				sub = oneBook['subtitle']
			except KeyError:
				sub = None
			id = oneBook.get('google_id')
			date_pub = oneBook.get('publication_date')
			if date_pub:
				try:
					date_pub = datetime.date(datetime.strptime(oneBook.get('publication_date'),"%Y-%m-%d"))
				except:
					date_pub = None
			image_url = oneBook['image_url'] 	
			description = oneBook.get('description')
			#we cant import a list into our db
			for pub in oneBook['publishers']:
				publisher = pub['name']
				create_publishers(pub)
			#we cant import a list into our db
			for aut in oneBook['authors']:
				author = aut['name']
				create_authors(aut)

			newBook = Book(isbn = isbn,id = id,title = title,subtitle = sub,date_pub = date_pub,author = author,publisher = publisher,description = description,img_url = image_url)
		
			db.session.add(newBook)
			db.session.commit()
示例#32
0
def get_all_shelves(reader_id, shelf_name):
    books_in_shelf = Shelf.read_by_reader_and_name(shelf_name, reader_id)

    books = []
    for book in books_in_shelf:
        books.append(Book.read_by_id(book['id_book']))
    return jsonify(books), 200
示例#33
0
    def queryCheckouts(self, request):
        """get checkout records"""
        self._ensureAdmin()
        q = Book.query(Book.checkedOut == True)

        if request.overDue == True:
            q = q.filter(Book.dueDate < date.today())
        elif request.sbId:
            q = q.filter(
                ndb.AND(Book.sbId >= request.sbId.upper(),
                        Book.sbId < request.sbId.upper() + 'Z'))
            q = q.order(Book.sbId)
        elif request.name:
            q = q.filter(
                ndb.AND(Book.title >= request.name.lower(),
                        Book.title < request.name.lower() + 'z'))
            q = q.order(Book.title)

        curs = Cursor(urlsafe=request.cursor)

        books, nextcurs, more = q.fetch_page(PAGE_SIZE, start_cursor=curs)

        nextcursor = None
        if more and nextcurs:
            nextcursor = nextcurs.urlsafe()

        return CheckoutForms(items = [self._copyCheckoutToForm(checkout) \
            for checkout in books], cursor = nextcursor)
示例#34
0
def add_book():
    book_data = request.get_json()['book']

    val = 0
    result = check_book(book_data, val)
    if (result == 1):
        return "<h1>please enter valid data</h1>"

    title = book_data['title']
    author = book_data['author']
    publisher = book_data['publisher']
    isbn = book_data['isbn']
    url = book_data['url']

    try:
        book = Book(title=title,
                    author=author,
                    publisher=publisher,
                    isbn=isbn,
                    url=url)
        db.session.add(book)
        db.session.commit()
        res = {
            'id': book.id,
            'title': book.title,
            'author': book.author,
            'publisher': book.publisher,
            'isbn': book.isbn,
            'url': book.url
        }
        return jsonify(res)
    except Exception as e:
        return (str(e))
示例#35
0
def loadBooks():
    publisher_id = 1
    book_id = 1
    authorList_id = 1

    for i in range(len(df)):

        book_id = book_id
        book_title = df['title'][i]
        book_description = df['description'][i]
        book_isbn = df['isbn'][i]
        book_publisher_date = df['publication_date'][i]
        book_google_id = df['google_id'][i]
        book_image_url = df['image_url'][i]
        book_publisherID = publisher_id

        publishers = db.session.query(Publisher).all()
        for publisher in publishers:
            if df['publishers'][i][0]['name'] == publisher.name:
                book_publisherID = publisher.id
                #print(book_publisherID)

        newBook = Book(id=book_id,
                       title=book_title,
                       description=book_description,
                       isbn=book_isbn,
                       publisher_date=book_publisher_date,
                       google_id=book_google_id,
                       image_url=book_image_url,
                       publisherID=book_publisherID)

        db.session.add(newBook)
        db.session.commit()

        book_id += 1
示例#36
0
    def queryBooks(self, request):
        """Return books based on query."""
        self._ensureAdmin()
        q = Book.query()
        #TODO: get projection, not all columns
        if request.sbId:
            q = q.filter(
                ndb.AND(Book.sbId >= request.sbId.upper(),
                        Book.sbId < request.sbId.upper() + 'Z'))
            q = q.order(Book.sbId)
        elif request.name:
            q = q.filter(
                ndb.AND(Book.title >= request.name.lower(),
                        Book.title < request.name.lower() + 'z'))
            q = q.order(Book.title)

        curs = Cursor(urlsafe=request.cursor)

        books, nextcurs, more = q.fetch_page(PAGE_SIZE, start_cursor=curs)

        nextcursor = None
        if more and nextcurs:
            nextcursor = nextcurs.urlsafe()

        return BookForms(items = [self._copyBookToForm(book) \
            for book in books], cursor = nextcursor)
示例#37
0
    def create_book():
        body = request.get_json()

        new_title = body.get(
            'title', None
        )  # get title from the body, if nothing in title, set its value to None
        new_author = body.get(
            'author', None
        )  # get author from the body, if nothing in author, set its value to None
        new_rating = body.get(
            'rating', None
        )  # get rating from the body, if no rating, then set its value to None (initially)
        search = body.get('search', None)

        try:
            if search:  # if there's search term
                selection = Book.query.order_by(Book.id).filter(
                    Book.title.ilike('%{}%'.format(
                        search)))  # search book title with case insensitive
                current_books = paginate_books(
                    request, selection)  # paginate the search results

                return jsonify({
                    'success': True,
                    'books': current_books,
                    'total_books': len(selection.all())
                })

            else:
                book = Book(title=new_title,
                            author=new_author,
                            rating=new_rating)
                book.insert()

                selection = Book.query.order_by(Book.id).all()
                current_books = paginate_books(request, selection)

                return jsonify({
                    'success': True,
                    'created': book.id,
                    'books': current_books,
                    'total_books': len(Book.query.all())
                })

        except:  #unprocessable
            abort(422)
示例#38
0
def get_item_info():
    rows = Book.query.all()
    book_list = []
    for row in rows:
        book_list.append(Book.as_dict(row))
    item_info_dict = reader.get_item_full_info(book_list)

    return item_info_dict
示例#39
0
文件: main.py 项目: Ysajid/api
def api_collection_book_chapters(collection_name, bookNumber):
    """
        swagger_from_file: specs/collection_book_chapters.yaml
    """
    book_id = Book.get_id_from_number(bookNumber)
    return Chapter.query.filter_by(collection=collection_name,
                                   arabicBookID=book_id).order_by(
                                       Chapter.babID)
示例#40
0
def show_item_info():
    rows = Book.query.all()
    book_list = []
    for row in rows[:1000]:
        book_list.append(Book.as_dict(row))
    item_info_dict = reader.get_item_full_info(book_list)

    return json.dumps(item_info_dict)
示例#41
0
def create_books():
    b = Book(u'Война и мир')
    a = Author(u'Толстой')
    b.authors.append(a)
    db.session.add(b)

    b1 = Book(u'Финансист')
    b2 = Book(u'Титан')
    a = Author(u'Теодор Драйзер')
    b1.authors.append(a)
    b2.authors.append(a)
    db.session.add_all([b1, b2])

    b = Book(u'Dive into Python')
    a = Author(u'Марк Пилгрим')
    b.authors.append(a)
    db.session.add(b)
示例#42
0
def get_book_by_isbn(isbn):
    rows = _get_books_from_db('books.isbn', isbn, False)
    if rows.rowcount > 0:
        book = Book()
        _populate_book_data(book, next(rows))
        _populate_book_reviews(book)
        return book
    return None
def _add_book(**kwargs):
    try:
        book = Book(**kwargs)
        db.session.add(book)
        db.session.commit()
        return jsonify(message="Book added. book id={}".format(book.id))
    except Exception as e:
        return jsonify(errors=str(e)), HTTPStatus.BAD_REQUEST
示例#44
0
    def new_book():
        body = request.get_json()
        book = Book(body.get('title'), body.get('author'),
                    int(body.get('rating')))
        book.insert()
        book = Book.query.order_by('id').all
        formatted_books = [book.format() for book in Book]
        page = request.args.get('page', 1, type=int)
        start = (page - 1) * 8
        end = start + 8

        return jsonify({
            'success': True,
            'Created': Book.id,
            'books': formatted_books[start:end],
            'total_books': len(formatted_books)
        })
示例#45
0
 def test_book_update_via_service_put(self):
     self.assertEquals(0, Book.all().count())
     book = Book(title="test",
                 ident="1",
                 author="author",
                 notes="",
                 image="http://example.com/image.gif",
                 url="http://example.com")
     book.put()
     self.assertEquals(1, Book.all().count())
     json = """{
         "ident": "1", 
         "title": "test update",
         "author": "author",
         "notes": "",
         "image": "http://example.com/image.gif",
         "url": "http://example.com"
     }"""
     response = self.app.put('/books/1', params=json, expect_errors=True)
     self.assertEquals(1, Book.all().count())
     response = self.app.get('/books/1', expect_errors=True)
     self.assertEquals("200 OK", response.status)
     try:
         json = response.json
     except AttributeError:
         assert (False)
     self.assertEqual(json['ident'], "1")
     self.assertEqual(json['title'], "test update")
示例#46
0
 def list_chapters(self):
     course = Course(self.api_client.client, self.args.course)
     book = Book(course, self.args.book)
     print_list(
         [
             "{}. {}".format(str(float(c["rank"])).rstrip("0").rstrip("."), c["title"])
             for c in Chapter.list(course, book)
         ]
     )
示例#47
0
def bulk_add_books(books_to_add):
    """Add a large amount of books to database in one request.

    :param books_to_add: list of dicts with keys: title, author, category and description
    """
    for book in books_to_add:
        new_book = Book(**book)
        db.session.add(new_book)
    db.session.commit()
示例#48
0
def import_books():
    with open("books.csv") as f:
        csvreader = csv.reader(f)
        next(csvreader)
        for isbn, title, author, year in csvreader:
            book = Book(isbn=isbn, title=title, author=author, year=year)
            db.session.add(book)
            print(f'Added book. title: {title}')
        db.session.commit()
示例#49
0
文件: index.py 项目: Kol2ja/web2
def delat(genre_id):
    # Вывод всей информации о жанре информация для авторизованного пользователя
    # если пользователь не авторизован, кидаем его на страницу входа
    if 'username' not in session:
        return redirect('/login')
    # если не админ, то его на главную страницу
    if session['username'] != 'admin':
        return redirect(url_for('index'))
    # иначе выдаем информацию
    books = Book(db.get_connection()).get_by_genre(genre_id)
    for i in books:
        Book(db.get_connection()).delete(i[2])
    genre_Book(db.get_connection()).delete(genre_id)
    genres = genre_Book(db.get_connection()).get_all()
    return render_template('genre_admin.html',
                           username=session['username'],
                           title='Просмотр жанров',
                           genres=genres)
示例#50
0
 def create_book(self,
                 title="test_title",
                 google_books_id="1",
                 authors="test_authors"):
     book = Book(title=title,
                 google_books_id=google_books_id,
                 authors=authors)
     self.add_to_database(book)
     return book
 def get(self, book_id, page_id):
     book = Book(book_id)
     page = Page(page_id, book)
     paras = [
         ParaSerializer(Paragraph(id=paraId, in_page=page,
                                  in_book=book)).data
         for paraId in page.paras
     ]
     return jsonify(data=paras)
示例#52
0
def books_create():
    try:
        book = Book(title=request.form.get('title'))
        db.session.add(book)
        db.session.commit()
    except Exception as e:
        app.logger.error('Failed to add book')
        app.logger.error(e)
    return redirect('/books')
示例#53
0
async def vote_by_criterias( c: types.CallbackQuery , state: FSMContext ) :
	print( f'user @{c.from_user.username} wants to vote by criteria' )

	async with state.proxy() as data :
		book = Book.objects( id=data[ 'book_id' ] ).first()

		await add_to_temp(
				await new_book_or_review( get_user( c.from_user.id ) , c , book , need_to_add=False , actions=False ) ,
				data )
示例#54
0
def run():
    for bt, st in spider.get_tags():
        if not Tag.objects(btag=bt[0]).all():
            for t in st:
                tag = Tag(stag=t, btag=bt[0])
                tag.save()

    for t in Tag.objects.all():  # 查询小标签出来,逐个下载
        for page, url_list in spider.get_all_list_page(t.stag):  # 获取所有翻页
            for book_url in url_list:  # 遍历列表页
                detail = spider.get_book_detail(book_url)
                detail = spider.clean_detail(detail)  # 清洗数据
                detail["small_tag"] = t.stag
                detail["big_tag"] = t.btag
                book = Book(**detail)
                book.save()
            break
        break
示例#55
0
文件: import.py 项目: jbozas/project1
def readFile():
    v = []
    f = open("./storage/books.csv")
    isbns = []
    reader = csv.reader(f)
    for isbn, title, author, year in reader:
        book = Book(isbn=isbn, title=title, author=author, year=year)
        v.append(book)
        isbns.append(book.isbn)
示例#56
0
    def delete_book(book_id):

        try:
            book = Book.query.filter(Book.id == book_id).one_or_none()
            if book is None:
                abort(404)
            book.delete()

            return jsonify({
                'success': True,
                'deleted': book_id,
                'books': paginate(request),
                'total_books': Book.count()
            })
        except:
            abort(404)
        finally:
            Book.db_close()
示例#57
0
文件: index.py 项目: Kol2ja/web2
def rating(book_id):
    # Запрос книг, продающихся в определенном жанре
    form = SearchgenreForm()
    form.genre_id.choices = [(0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4'),
                             (5, '5')]
    if form.validate_on_submit():
        #
        if form.genre_id.data != '0':
            Book(db.get_connection()).sred(book_id, form.genre_id.data)
        # редирект на главную страницу
        books = Book(db.get_connection()).get_all()
        return render_template('book_user.html',
                               username=session['username'],
                               title='Просмотр базы',
                               books=books)
    return render_template("search_genre.html",
                           title='Подбор по цене',
                           form=form)
示例#58
0
def add():
    data = request.get_json()
    author = data['author']
    title = data['title']
    read = data['read']
    book = Book(author=author, title=title, read=read)
    db.session.add(book)
    db.session.commit()
    return jsonify(data)
示例#59
0
def create_book():
    print("FORM DATA:", dict(request.form))

    new_book = Book(title=request.form["book_title"],
                    author_id=request.form["author_name"])
    db.session.add(new_book)
    db.session.commit()

    return jsonify({"message": "BOOK CREATED OK", "book": dict(request.form)})
示例#60
0
def main():
    path = Path()
    menu = Menu()
    menu.instructions()
    while True:
        # menu.de_entrada()
        try:
            excel_filename = input("Ingresa el nombre del archivo de excel: ")
            excel_exists = path.check_existence(excel_filename)
            if excel_exists:

                # File found notification for the user.
                menu.file_found()

                # Tras haber verificado que el archivo existe, se crea el path para cargar el libro con openpyxl.
                excel_file_path = path.book_path(excel_filename)

                # Book settings
                book = Book(excel_file_path)
                book_headers = book.get_headers()
                book_rows = book.get_list_of_rows()

                app_name = input(
                    "Ingresa el nombre del app de tu proyecto Django: ")
                model_name = input("Ingresa el nombre del modelo de tu app: ")

                fx = Fixture(
                    app=app_name,
                    model=model_name,
                    headers=book_headers,
                    list_of_fields=book_rows,
                )
                fx.create_objects()
                fx.create_json_file(path.json_dir)

                menu.task_completed()
                break
            else:
                menu.file_not_found()

        except ValueError:
            print("Ingresa el nombre del archivo.")
            print("")
            pass