本文整理汇总了Python中models.Book类的典型用法代码示例。如果您正苦于以下问题:Python Book类的具体用法?Python Book怎么用?Python Book使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Book类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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"
)
开发者ID:arnav,项目名称:django,代码行数:34,代码来源:tests.py
示例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)
开发者ID:mrchucho,项目名称:infinite-summer,代码行数:7,代码来源:main.py
示例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)
开发者ID:fanghuang,项目名称:Booksharepoint,代码行数:25,代码来源:main_handlers.py
示例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)
开发者ID:raymondzeng,项目名称:bookexchange,代码行数:32,代码来源:app.py
示例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)
开发者ID:garethr,项目名称:appengine-books,代码行数:30,代码来源:main.py
示例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)
开发者ID:owenphelps,项目名称:library,代码行数:7,代码来源:model_tests.py
示例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)
开发者ID:jingyihiter,项目名称:lab3-R1-R7-,代码行数:32,代码来源:views.py
示例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
开发者ID:amumu,项目名称:wyzq,代码行数:25,代码来源:app.py
示例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)
开发者ID:yaroslav-dudar,项目名称:prom-ua-test-task,代码行数:32,代码来源:views.py
示例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
开发者ID:eugeneai,项目名称:ZCA,代码行数:35,代码来源:catalog.py
示例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")
开发者ID:clllyw,项目名称:lab4,代码行数:32,代码来源:views.py
示例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
开发者ID:mangalambigai,项目名称:sblibrary,代码行数:32,代码来源:sblibrary.py
示例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)
开发者ID:owenphelps,项目名称:library,代码行数:7,代码来源:model_tests.py
示例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))
开发者ID:becomingGuru,项目名称:django-gitcms,代码行数:26,代码来源:load.py
示例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})
开发者ID:stafary,项目名称:lab4,代码行数:26,代码来源:views.py
示例16: test_book_can_reserve_new_book_with_more_than_one_user
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])
开发者ID:owenphelps,项目名称:library,代码行数:8,代码来源:model_tests.py
示例17: insert_action
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))
"""
开发者ID:DengZuoheng,项目名称:lib.eic.su,代码行数:57,代码来源:actions.py
示例18: book_return
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()
开发者ID:eugeneai,项目名称:ZCA,代码行数:10,代码来源:vc.py
示例19: save
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('/')
开发者ID:epkatz,项目名称:nechama,代码行数:10,代码来源:views.py
示例20: on_add_clicked
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))
开发者ID:eugeneai,项目名称:ZCA,代码行数:10,代码来源:vc.py
注:本文中的models.Book类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论