本文整理汇总了Python中books.models.Book.save方法的典型用法代码示例。如果您正苦于以下问题:Python Book.save方法的具体用法?Python Book.save怎么用?Python Book.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类books.models.Book
的用法示例。
在下文中一共展示了Book.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: addB
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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())
示例2: _handle_json
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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()
示例3: handle
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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()
示例4: BookTest
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
class BookTest(TestCase):
def setUp(self):
self.author1 = AuthorFactory(name="Author 1")
self.author2 = AuthorFactory(name="Author 2")
self.book = Book(title="MyBook")
self.book.save()
self.book.authors.add(self.author1.pk, self.author2.pk)
def tearDown(self):
self.author1.delete()
self.author2.delete()
self.book.delete()
def test_can_list_authors(self):
self.assertEqual("Author 1, Author 2", self.book.list_authors())
def test_string_method(self):
self.assertEqual("MyBook by Author 1, Author 2", self.book.__str__())
def test_custom_save_method(self):
self.assertIsNone(self.book.date_reviewed)
self.book.review = "My Review"
self.book.save()
self.assertIsNotNone(self.book.date_reviewed)
示例5: BookTest
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
class BookTest(TestCase):
# Django requires an explicit setup() when running tests in PTVS
@classmethod
def setUpClass(cls):
django.setup()
super(BookTest, cls).setUpClass()
# setUp will run before each test
def setUp(self):
self.author1 = AuthorFactory(name="Author 1")
self.author2 = AuthorFactory(name="Author 2")
self.book = Book(title="MyBook")
self.book.save()
self.book.authors.add(self.author1.pk, self.author2.pk)
# tearDown will run after each test
def tearDown(self):
self.author1.delete()
self.author2.delete()
self.book.delete()
# UNIT TESTS
def test_can_list_authors(self):
self.assertEqual("Author 1, Author 2", self.book.list_authors())
def test_string_method(self):
self.assertEqual("MyBook by Author 1, Author 2", self.book.__str__())
def test_custom_save_method(self):
self.assertIsNone(self.book.date_reviewed)
self.book.review = "My review"
self.book.save()
self.assertIsNotNone(self.book.date_reviewed)
示例6: add
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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')
示例7: AdminBookViewTests
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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)
示例8: RateViewTests
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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'])
示例9: BookRateSerializerTests
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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)
示例10: _handle_json
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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]))
示例11: append
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
def append(request):
errors = []
if 'isbn' in request.GET:
ISBN = request.GET['isbn']
try:
book = Book.objects.get(isbn=ISBN)
except Book.DoesNotExist:
name = request.GET['name']
try:
Au = Author.objects.get(name=name)
except Author.DoesNotExist:
#作者不存在则添加作者
title = request.GET['title']
publisher = request.GET['publisher']
publishDate = request.GET['publishDate']
price = request.GET['price']
p1 = Book(isbn=ISBN, title=title, authorid_id=1, publisher=publisher,
publishDate=str(publishDate), price=price )
p1.save()
return render_to_response('appauthor.html',{'book_id': ISBN})
else:
authorid = Au.authorid
title = request.GET['title']
publisher = request.GET['publisher']
publishDate = request.GET['publishDate']
price = request.GET['price']
p1 = Book(isbn=ISBN, title=title, authorid_id=authorid, publisher=publisher,
publishDate=publishDate, price=price )
p1.save()
return render_to_response('appendsuccess.html')
else:
errors.append('输入的ISBN已经存在')
render_to_response('append.html', {'errors': errors})
return render_to_response('append.html',{'errors': errors})
示例12: create_post
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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)
示例13: _handle_csv
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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: _handle_json
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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
示例15: addbook
# 需要导入模块: from books.models import Book [as 别名]
# 或者: from books.models.Book import save [as 别名]
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/")