示例#1
0
def get_user_book(email, isbn):
    bdao = BookDao()

    try:
        book = bdao.get_user_book(Book("", "", isbn, "", email))
    except RecordNotFoundException:
        response.status = 404
        return f"Book with isbn {isbn} not found."

    response.status = 200
    return book.to_json()
示例#2
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)
示例#3
0
def add_book():
    name = request.args.get('name')
    author = request.args.get('author')
    published = request.args.get('published')
    try:
        book = Book(name=name, author=author, published=published)
        db.session.add(book)
        db.session.commit()
        return "Book added. book id={}".format(book.id)
    except Exception as e:
        return (str(e))
示例#4
0
 def post(self):
     args = self.parser.parse_args()
     db.session.add(
         Book(category_id=args.category_id,
              title=args.title,
              thumbnail_url=args.thumbnail_url,
              stock=args.stock,
              product_description=args.product_description,
              upc=args.upc))
     db.session.commit()
     return {'title': args.title}
示例#5
0
文件: import.py 项目: jbozas/project1
def main():
    f = open("./storage/books.csv")
    reader = csv.reader(f)

    for isbn, title, author, year in reader:
        book = Book(isbn=isbn, title=title, author=author, year=year)
        db.session.add(book)
        print(f"Added book number {isbn} with title {title} .")
    print("There is no more books.")
    db.session.commit()
    print("Proccess successful.")
示例#6
0
    def test_book_3(self):
        s = Book(isbn='37', title = 'How to be bad', google_id = "22", datePublished = "2017-11-12", description = "Wrost book of all time.", image="https://cdn.business2community.com/wp-content/uploads/2016/03/Vd3MJo.jpg")
        testSession.add(s)
        testSession.commit()


        r = testSession.query(Book).filter_by(isbn = '37').one()
        self.assertEqual(str(r.isbn), '37')

        testSession.query(Book).filter_by(isbn = '37').delete()
        testSession.commit()
示例#7
0
 def get_random_object(self, route):
     try:
         url = self.api_root + route
         response = requests.get(url)
         # a jeson dictionary
         json_dict = response.json()
         # map to python object
         return Book(**json_dict)
     except:
         print('...Something went wrong')
     return None
示例#8
0
    def test_book_1(self):
        s = Book(isbn='20', title = 'C++', google_id = "45", datePublished = "2015-12-08", description = "It is a impressive book.", image="http://upload.wikimedia.org/wikipedia/en/thumb/6/6f/Pottermore.png/225px-Pottermore.png")
        testSession.add(s)
        testSession.commit()


        r = testSession.query(Book).filter_by(isbn = '20').one()
        self.assertEqual(str(r.isbn), '20')

        testSession.query(Book).filter_by(isbn = '20').delete()
        testSession.commit()
示例#9
0
    def test_books(self):
        book = Book(title="title", author="author", category="category", description="description",quantity=5)
        db.session.add(book)
        db.session.commit()

        # this works
        assert book in db.session

        self.client.get("/api/v1/resources/books/")
        # this raises an AssertionError
        assert book in db.session
示例#10
0
文件: app.py 项目: Supasolja/try999_2
def add_book():
    title = request.json['title']
    author = request.json['author']
    pages = request.json['pages']
    price = request.json['price']

    new_book = Book(title, author, pages, price)

    db.session.add(new_book)
    db.session.commit()

    return jsonify(new_book)
示例#11
0
    def create_book(jwt):
        new_book_name = request.json.get('book_name')
        new_book_issue = request.json.get('book_issue')

        if new_book_name is None or new_book_issue is None:
            abort(400)
        try:
            book = Book(book_name=new_book_name, book_issue=new_book_issue)
            book.insert()
            return jsonify({'success': True, 'book': book.id})
        except BaseException:
            abort(422)
示例#12
0
    def test_book_model_2(self):
        """Test querying the database by attribute using simple keywords"""

        with app.test_request_context():
            data1 = Book("title1", "genre1", "year1", "isbn1", "$1.00",
                         "pic.jpg")
            data2 = Book("title2", "genre2", "year2", "isbn2", "$2.00",
                         "pic2.jpg")

            db.session.add(data1)
            db.session.commit()
            db.session.add(data2)
            db.session.commit()

            book = db.session.query(Book).filter_by(year="year2").first()
            self.assertEqual(book.author, "author2")

            db.session.delete(data1)
            db.session.commit()
            db.session.delete(data2)
            db.session.commit()
示例#13
0
    def test_min_book(self):
        s = Book(id="hi", title="try", author="1", publisher="2")

        db.session.add(s)
        db.session.commit()

        r = Book.query.get("hi")
        self.assertEqual(r.id, "hi")
        self.assertEqual(r.isbn, None)

        db.session.query(Book).filter_by(id="hi").delete()
        db.session.commit()
示例#14
0
def test_get_unexistent_book():
    """
    Tests the GET /users/<email>/books/<isbn> endpoint with unexistent book.
    """
    book = Book("The Truth About Chuck Norris", "Ian Spector, Angelo Vildasol",
                "1592403441", "29th 2007", "*****@*****.**")
    try:
        delete_user_book(book)
    except:
        pass
    http_return = get_user_book(book)
    assert http_return.status_code == 404
示例#15
0
def insertBook():
    book = Book(title='Harry Potter',
                reserved=False,
                dateRent=datetime(2020, 10, 13))
    book.save()
    book1 = Book(title='Game of thrones',
                 reserved=False,
                 dateRent=datetime(2020, 10, 11))
    book1.save()
    book2 = Book(title='Rangers',
                 reserved=False,
                 dateRent=datetime(2020, 10, 12))
    book2.save()
    book3 = Book(title='Lord of the rings',
                 reserved=False,
                 dateRent=datetime(2020, 9, 11))
    book3.save()
    book4 = Book(title='Treasure island',
                 reserved=False,
                 dateRent=datetime(2020, 10, 5))
    book4.save()
示例#16
0
 def test_book_deletion(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())
     book.delete()
     self.assertEquals(0, Book.all().count())
示例#17
0
 def test_add_book_1(self):
     written_by = "Haruki Murakami"
     kafka_on_the_shore = Book(title="Kafka on the Shore",
                               isbn="1400079276")
     author = self.session.query(Author).filter_by(name=written_by).first()
     author.wrotes = [kafka_on_the_shore]
     self.session.commit()
     # test
     test = self.session.query(Author).filter_by(name=written_by).first()
     book = test.wrotes[0]
     self.assertEqual(book.title, "Kafka on the Shore")
     self.assertEqual(book.written_by[0].name, "Haruki Murakami")
示例#18
0
文件: create_db.py 项目: arr3385/book
def create_books():
    book = load_json('books.json')

    for oneBook in book['Books']:
        title = oneBook['title']
        id = oneBook['id']

        newBook = Book(title=title, id=id)
        # After I create the book, I can then add it to my session.
        session.add(newBook)
        # commit the session to my DB.
        session.commit()
示例#19
0
def populate_books(n=30, authors=None, tags=None):
    return [
        Book(isbn=g.code.isbn(),
             authors=authors if authors else [],
             title=' '.join(g.text.title().split(' ')[:5]),
             original_title=' '.join(g.text.title().split(' ')[:5]),
             publisher=g.business.company(),
             pub_date=g.datetime.datetime().date(),
             language=g.person.language(),
             tags=tags if tags else [],
             description=g.text.sentence()) for _ in range(n)
    ]
示例#20
0
def create_book():
    if request.method == 'GET':
        form = BookForm()
    else:  # POST
        form = BookForm(request.form)
        if form.validate():
            book = Book('')
            form.populate_obj(book)
            db.session.add(book)
            db.session.commit()
            return redirect(url_for('edit_books'))
    return render_template('books_edit_page.html', form=form)
示例#21
0
 def test_book_views_return_correct_mime_type(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())
     response = self.app.get('/books/%s' % book.ident, expect_errors=True)
     self.assertEquals(response.content_type, "application/json")
示例#22
0
def create_book():
  data = request.get_json()
  name = data['name']
  author = data['author']
  published = data['published']
  try:
    book = Book(name=name, author=author, published=published)
    db.session.add(book)
    db.session.commit()
    return "Book name={} added successfully".format(book.name)
  except Exception as e:
    return (str(e))
示例#23
0
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())
示例#24
0
def insert_book():
    book = Book(title=request.json['title'],
                first_author=request.json['first_author'],
                second_author=request.json['second_author'],
                publisher=request.json['publisher'],
                year_of_publication=request.json['year_of_publication'],
                author_id1=request.json['author_id1'],
                author_id2=request.json['author_id2'],
                publisher_id=request.json['publisher_id'])
    db.session.add(book)
    db.session.commit()
    return make_response(jsonify(response='OK'), 200)
示例#25
0
def addbook():
    form = AddFormBook()
    if form.validate_on_submit():
        if Book.query.filter_by(bookname=form.name.data).first():
            flash(u'Эта книга уже есть в библиотеке')
            return redirect(url_for("addbook"))
        book = Book(bookname=form.name.data)
        dbs.session.add(book)
        dbs.session.commit()
        flash(u'Книга:%s была добавлена в библиотеку' % book.bookname)
        return redirect(url_for("addbook"))
    return render_template('addbook.html', form=form, user=current_user)
示例#26
0
 def test_sending_email(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())
     # TODO: needs assertion
     _email_new_book(book)
示例#27
0
    def _addBook(self, request):
        try:
            data = {field.name: getattr(request, field.name) for field in request.all_fields()}
            data['key'] = ndb.Key(Book, data['title'])
            del data['websafeKey']

            r = Book(**data).put()

            return copyToForm(BookForm(), r.get())

        except Exception, e:
            raise endpoints.BadRequestException(e.message)
示例#28
0
    def test_max_book(self):
        s = Book(isbn = str("a" * 30),id = str("a" * 20), title = str("a"*100),subtitle = str("a"*100), \
        date_pub = datetime(1000,5,5),author = str("a"*100),publisher = str("a"*100),description = None)

        db.session.add(s)
        db.session.commit()

        r = Book.query.get(str("a" * 20))
        self.assertEqual(r.id, str("a" * 20))

        db.session.query(Book).filter_by(id='aaaaaaaaaaaaaaaaaaaa').delete()
        db.session.commit()
示例#29
0
    def create_book():
        try:
            title = request.get_json()['title']
            author = request.get_json()['author']
            rating = request.get_json()['rating']

            book = Book(title=title, author=author, rating=rating)
            book.insert()

            return jsonify({"success": True, "created": book.id})
        except:
            abort(422)
def resync_database(data):
    rows = []
    for row in data:
        rows.append(
            Book(row["title"], row["topic"], row["count"], row["cost"],
                 row["id"]))
    try:
        db.session.query(Book).delete()
        db.session.bulk_save_objects(rows)
        db.session.commit()
    except:
        logging.error(f"Failed to resync the database.")