本文整理汇总了Python中models.Book类的典型用法代码示例。如果您正苦于以下问题:Python Book类的具体用法?Python Book怎么用?Python Book使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Book类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_default_creation
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"
)
示例2: post
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)
示例3: get
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)
示例4: post
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)
示例5: post
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)
示例6: test_book_can_borrow_reserved_book_if_only_reserver
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)
示例7: add_book
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)
示例8: content
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
示例9: books
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)
示例10: get
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
示例11: add
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")
示例12: addBook
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
示例13: test_book_can_reserve_new_book_once
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)
示例14: loaddir
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))
示例15: add_book
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})