本文整理汇总了Python中books.models.Book类的典型用法代码示例。如果您正苦于以下问题:Python Book类的具体用法?Python Book怎么用?Python Book使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Book类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _handle_json
def _handle_json(self, jsonpath):
"""
Store books from a file in JSON format.
"""
jsonfile = open(jsonpath)
data_list = json.loads(jsonfile.read())
for d in data_list:
# Get a Django File from the given path:
f = open(d['book_path'])
d['book_file'] = File(f)
del d['book_path']
if d.has_key('cover_path'):
f_cover = open(d['cover_path'])
d['cover_img'] = File(f_cover)
del d['cover_path']
if d.has_key('a_status'):
d['a_status'] = Status.objects.get(status = d['a_status'])
tags = d['tags']
del d['tags']
book = Book(**d)
book.save() # must save item to generate Book.id before creating tags
[book.tags.add(tag) for tag in tags]
book.save() # save again after tags are generated
示例2: create_post
def create_post(**message):
"""
Arguments:
- `**message`:
"""
body = message['plain']
email = message['from']
subject = message['subject']
MailPost(body=body,email=email).save()
try:
user = getUser(email)
if parseSubject(subject,'add'):
try:
pairs = pairBody(body)
title = parsePairForKey(pairs,'book')
friend_loan = parsePairForKey(pairs,'friend')
book = Book(user=user,title=title,friend_loan=friend_loan)
book.save()
sendBook(book,user)
except Exception as e1:
sendError(email,e1)
if parseSubject(subject,'report'):
try:
user = getUser(email)
sendReport(user)
except Exception as e2:
sendError(email,e2)
except Exception as e3:
sendError(email,e3)
示例3: addB
def addB(request):
errors = []
authors = Author.objects.all()
if request.method == 'POST':
if not request.POST.get('ISBN',''):
errors.append('请填写书籍ISBN。')
if not request.POST.get('Title',''):
errors.append('请填写书籍标题。')
if not request.POST.get('Author',''):
errors.append('请填写书籍作者。')
if not request.POST.get('Publisher',''):
errors.append('请填写书籍出版社。')
if not request.POST.get('PublishDate',''):
errors.append('请填写书籍出版日期。')
if not request.POST.get('Price',''):
errors.append('请填写书籍价格。')
if not errors:
post = request.POST
name = post['Author']
temp = Author.objects.get(Name=name)
book = Book(ISBN=post['ISBN'],
Title=post['Title'],
Publisher=post['Publisher'],
PublishDate=post['PublishDate'],
Price=post['Price'],
Author=temp,)
book.save()
return render_to_response('edit_success.html',locals())
return render_to_response('addB.html',locals())
示例4: _handle_json
def _handle_json(self, jsonpath):
"""
Store books from a file in JSON format.
"""
jsonfile = open(jsonpath)
data_list = json.loads(jsonfile.read())
for d in data_list:
# Get a Django File from the given path:
f = open(d['book_path'])
d['book_file'] = File(f)
del d['book_path']
if d.has_key('cover_path'):
f_cover = open(d['cover_path'])
d['cover_img'] = File(f_cover)
del d['cover_path']
if d.has_key('a_status'):
d['a_status'] = Status.objects.get(status = d['a_status'])
tags = d['tags']
del d['tags']
book = Book(**d)
try:
book.save() # must save item to generate Book.id before creating tags
[book.tags.add(tag) for tag in tags]
book.save() # save again after tags are generated
except IntegrityError as e:
if str(e) == "column file_sha256sum is not unique":
print "The book (", d['book_file'], ") was not saved because the file already exsists in the database."
else:
raise CommandError('Error adding file %s: %s' % (d['book_file'], sys.exc_info()[1]))
示例5: handle
def handle(self, *args, **options):
# self.stdout.write(options['filepath'])
with open(options["filepath"], "rt") as f:
reader = csv.reader(f)
next(reader)
for row in reader:
bookObject = Book(
listTitle=row[0],
title=row[3],
source=row[1],
isbn=row[2],
author=row[4],
illustrator=row[5],
publisher=row[6],
year=2015,
pages=0,
readingLevel=row[9],
gradeLevel=row[10],
nameOfReader=row[11],
gender=row[12],
genderExpression=row[13],
age=0,
ethnicity=row[15],
disability=row[16],
sexualOrientation=row[17],
education=row[18],
income=0,
religion=row[20],
geography=row[21],
familyStatus=row[22],
notesByReader=row[23],
)
bookObject.save()
示例6: AdminBookViewTests
class AdminBookViewTests(TestCase):
def setUp(self):
self.bookData = {'isbn': '85-359-0277-5', 'title': 'title', 'price': '10', 'author': 'author',
'image': 'test.jpg'}
# We put user_id 2 as this would be the identifier of admin returned by TDA
self.user = User(user_id=2, name='admin')
self.user.save()
self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author',
image='test.jpg')
self.book2.save()
def test_create_new_book_return_201(self):
resp = self.client.post('/ebucxop/books/', data=self.bookData,
HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin')))
self.assertEqual(resp.status_code, 201)
self.assertEquals('85-359-0277-5', resp.data['isbn'])
def test_update_existing_book_return_200(self):
resp = self.client.post('/ebucxop/books/0-306-40615-2/', data={'title': 'titleUpdated'},
HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin')))
self.assertEqual(resp.status_code, 200)
self.assertEquals('titleUpdated', resp.data['title'])
def test_create_new_book_without_credentials_return_403(self):
resp = self.client.post('/ebucxop/books/', data=self.bookData,
HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
self.assertEqual(resp.status_code, 403)
示例7: _handle_json
def _handle_json(self, collection):
"""
Store books from a file in JSON format.
"""
jsonpath = os.path.join(collection,'books.json')
jsonfile = open(jsonpath)
#data_list = json.loads(jsonfile.read())
txt=jsonfile.read()
jsonfile.close()
data_list = eval(txt)
log = open('log','w')
print 'items',len(data_list)
for d in data_list:
# Get a Django File from the given path:
pth = os.path.join(collection,d['book_file'])
if os.path.exists(pth):
if len(d['book_file'])>0:
lng = d['dc_language']
subprocess.call('cp '+ pth + ' ' + '/library/media/'+lng,shell=True)
book = Book(**d)
else:
print >> log, 'book_file not found',str(d)
continue
else:
print >> log, 'path not found', pth
continue
book.save()
log.close()
示例8: setUp
def setUp(self):
self.book = Book(isbn='0-306-40615-2', title='title', price=10, author='author',
image='test.jpg')
self.book.save()
self.book2 = Book(isbn='85-359-0277-5', title='title2', price=10, author='author2',
image='test.jpg')
self.book2.save()
示例9: process_books_summary
def process_books_summary(self, session, user, book_list):
seller_book_list = []
amounts = {}
for book in book_list:
amount = book['amount']
del book['amount']
dbbook = Book(owner=user, accepted=False, sold=False)
if 'pk' in book:
dbbook.book_type_id = book['pk']
seller_book_list.append(book['pk'])
amounts[book['pk']] = amount
else:
book['isbn'] = re.sub(r'[^\dX]+', '', book['isbn'].upper())
book['price'] = Decimal(book['price'])
if book['publication_year'] == "":
book['publication_year'] = 1970
book_type = BookType(**book)
book_type.save()
dbbook.book_type = book_type
seller_book_list.append(book_type.pk)
amounts[book_type.pk] = amount
dbbook_list = []
for i in range(0, amount):
dbbook.pk = None
dbbook_list.append(dbbook)
Book.objects.bulk_create(dbbook_list)
session['seller_books'] = (seller_book_list, amounts)
return True, None
示例10: add
def add(request):
if request.POST and request.POST['name']:
form = Book(request.POST)
if form.is_valid():
form.save()
else:
return render_to_response('book/add_book.html')
示例11: BookRateSerializerTests
class BookRateSerializerTests(TestCase):
def setUp(self):
bookModel = {'isbn': '0-306-40615-2', 'title': 'title', 'price': 10, 'author': 'author',
'image': 'test.jpg'}
# Adding serializer extra fields that not required in model
self.book = Book(**bookModel)
self.user = User(user_id='3', name='test')
self.book.save()
self.user.save()
self.expectedRateData = {'user_id': self.user.pk, 'rating': 4}
self.fullRateData = {'book_id': self.book, 'user_id': self.user, 'rating': 4}
# Adding serializer extra fields that not required in model
self.rate = Rate(**self.fullRateData)
def test_retrieve_rate_should_work(self):
"""
We check that serialization an existing model is working
"""
serializer = BookRateSerializer(self.rate)
# Check we have a correct dictionary serialized with python datatypes
# book_id is excluded from serialization
self.assertEquals(serializer.data, self.expectedRateData)
def test_create_valid_rate_should_work(self):
"""
We check deserialization process of a dictionary where we get a valid object model with validations succeded
"""
serializer = RateSerializer(data={'rating': 4, 'user_id': self.user.pk, 'book_id': self.book.pk})
# Check validations works
self.assertEquals(serializer.is_valid(), True)
# Check object created is what we expect
self.assertEquals(serializer.object, self.rate)
self.assertEquals(serializer.data['rating'], 4)
示例12: RateViewTests
class RateViewTests(TestCase):
def setUp(self):
self.book = Book(isbn='85-359-0277-5', title='title', price=10, author='author',
image='test.jpg')
self.book.save()
self.user = User(user_id=1, name='test')
self.user.save()
self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author',
image='test.jpg')
self.book2.save()
rate = Rate(rating=1, book_id=self.book2, user_id=self.user)
rate.save()
def test_put_new_rate_should_return_201(self):
"""
When non existing rate, new one is added
"""
resp = self.client.put('/ebucxop/books/85-359-0277-5/ratings/me?format=json', {'rating': 3},
HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
response_content = json.loads(resp.content)
self.assertEqual(resp.status_code, 201)
self.assertEquals('3', response_content['rating'])
def test_put_existing_rate_should_return_200(self):
"""
When existing rate, old rate is updated and 200 returned
"""
resp = self.client.put('/ebucxop/books/0-306-40615-2/ratings/me?format=json', {'rating': u'3'},
HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame')))
self.assertEqual(resp.status_code, 200)
response_content = json.loads(resp.content)
# Ensure that 1 is changed to 3
self.assertEquals('3', response_content['rating'])
示例13: _handle_csv
def _handle_csv(self, csvpath):
"""
Store books from a file in CSV format.
WARN: does not handle tags
"""
csvfile = open(csvpath)
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
# TODO: Figure out if this is a valid CSV file
status_published = Status.objects.get(status="Published")
for row in reader:
path = row[0]
title = row[1]
author = row[2]
summary = row[3]
if os.path.exists(path):
f = open(path)
book = Book(
book_file=File(f), a_title=title, a_author=author, a_summary=summary, a_status=status_published
)
try:
book.save()
except:
print "EXCEPTION SAVING FILE '%s': %s" % (path, sys.exc_info()[0])
else:
print "FILE NOT FOUND '%s'" % path
示例14: addbook
def addbook(require):
if require.POST:
post=request.POST
a=Author(AuthorID=post['AID'],Name=post['AN'],Age=post['AA'],Country=post['AC'])
a.save()
b=Book(ISBN=post['BI'],Price=post['BP'],Publishdate=post['BPD'],Publisher=post['BPE'],Title=post['BT'],AuthorID=a)
b.save()
return HttpResponseRedirect("/home/")
示例15: searchbooks
def searchbooks():
booklist = {}
searchterm = request.args.get('value')
attr = request.args.get('refineSearch')
if attr == "all":
attr = None
if searchterm is None:
searchterm = ""
else:
searchterm = searchterm.lstrip()
if searchterm is None or searchterm == "":
pass
else:
cur_user = current_user()
logging.info(cur_user)
if not cur_user.is_authenticated():
#Assume no books in library or network, return results only
booklist = Book.search_books_by_attribute(searchterm,attr)
for book in booklist:
booklist[book] = booklist[book].to_dict()
#Assume not in booklist or networkbooklist
booklist[book]["inLibrary"] = "False"
booklist[book]["inNetwork"] = "False"
else:
user = current_user()
#Create a dictionary of the user's books
mybooklist = {}
for copy in user.get_library():
mybooklist[copy.OLKey] = copy
#Create a dictionary of the books in my network
networkbooklist = {}
string = ""
for connection in user.get_connections():
u = UserAccount.getuser(connection.id())
for copy in u.get_library():
networkbooklist[copy.OLKey] = copy
booklist = Book.search_books_by_attribute(searchterm,attr)
for book in booklist:
booklist[book] = booklist[book].to_dict()
booklist[book]["escapedtitle"] = re.escape(booklist[book]["title"])
if booklist[book]['OLKey'] in mybooklist:
booklist[book]["inLibrary"] = "True"
else:
booklist[book]["inLibrary"] = "False"
if booklist[book]['OLKey'] in networkbooklist:
booklist[book]["inNetwork"] = "True"
else:
booklist[book]["inNetwork"] = "False"
return render_response('searchbooks.html', books=booklist, search=searchterm, attribute=attr)