本文整理汇总了Python中applications.zcomx.modules.books.Book类的典型用法代码示例。如果您正苦于以下问题:Python Book类的具体用法?Python Book怎么用?Python Book使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Book类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test__get_reader
def test__get_reader(self):
router = Router(db, self._request, auth)
# No request.vars.reader, no book
self.assertEqual(router.get_reader(), None)
unreadable_statuses = [BOOK_STATUS_DRAFT, BOOK_STATUS_DISABLED]
readers = ['_reader_', 'slider', 'scroller']
router.book = self._book
for status in unreadable_statuses:
router.book = Book.from_updated(router.book, dict(status=status))
for reader in readers:
router.request.vars.reader = reader
self.assertEqual(router.get_reader(), 'draft')
self._book = Book.from_updated(
self._book, dict(status=BOOK_STATUS_ACTIVE))
router.book = None
router.request.vars.reader = '_reader_'
self.assertEqual(router.get_reader(), None)
router.book = self._book
self.assertEqual(router.get_reader(), 'slider')
del router.request.vars.reader
self.assertEqual(router.get_reader(), 'slider')
self._book = Book.from_updated(self._book, dict(reader='scroller'))
router.book = self._book
self.assertEqual(router.get_reader(), 'scroller')
self._book = Book.from_updated(self._book, dict(reader='slider'))
示例2: test__run
def test__run(self):
data = dict(
release_date=datetime.date.today(),
complete_in_progress=True,
)
self._book = Book.from_updated(self._book, data)
releaser = UnreleaseBook(self._book, self._creator)
jobs = releaser.run(job_options=self._job_options)
self.assertEqual(jobs, [])
self.assertEqual(releaser.needs_requeue, False)
book = Book.from_id(self._book.id) # reload
self.assertEqual(book.release_date, None)
self.assertEqual(book.complete_in_progress, False)
tests = [
# (post_id, expect)
('', None),
('_fake_post_id_', '_fake_post_id_'),
(IN_PROGRESS, None),
]
for t in tests:
data = dict(
tumblr_post_id=t[0],
twitter_post_id=t[0],
)
self._book = Book.from_updated(self._book, data)
releaser = UnreleaseBook(self._book, self._creator)
jobs = releaser.run(job_options=self._job_options)
self.assertEqual(jobs, [])
book = Book.from_id(self._book.id) # reload
self.assertEqual(book.tumblr_post_id, t[1])
self.assertEqual(book.twitter_post_id, t[1])
示例3: test__book_post_upload_session
def test__book_post_upload_session(self):
# No book_id, return fail message
self.assertWebTest(
'/login/book_post_upload_session',
match_page_key='',
match_strings=[
'"status": "error"',
'"msg": "Reorder service unavailable"',
],
)
# Invalid book_id, return fail message
self.assertWebTest(
'/login/book_post_upload_session/{bid}'.format(bid=999999),
match_page_key='',
match_strings=[
'"status": "error"',
'"msg": "Reorder service unavailable"',
],
)
# Valid book_id, no book pages returns success
# Protect existing book_page records so they don't get deleted.
def set_book_page_book_ids(from_book_id, to_book_id):
from_book = Book.from_id(from_book_id)
for page in from_book.pages():
BookPage.from_updated(page, dict(book_id=to_book_id))
temp_book = self.add(Book, dict(name='Temp Book'))
set_book_page_book_ids(self._book.id, temp_book.id)
self._book.update_record(status=BOOK_STATUS_DRAFT)
db.commit()
self.assertWebTest(
'/login/book_post_upload_session/{bid}'.format(bid=self._book.id),
match_page_key='/login/book_post_upload_session',
)
# book has no pages, so it should status should be set accordingly
book = Book.from_id(self._book.id)
self.assertEqual(book.status, BOOK_STATUS_DRAFT)
# Valid
set_book_page_book_ids(temp_book.id, self._book.id)
book_page_ids = [x.id for x in self._book.pages()]
bp_ids = ['book_page_ids[]={pid}'.format(pid=x) for x in book_page_ids]
self.assertWebTest(
'/login/book_post_upload_session/{bid}?{bpid}'.format(
bid=self._book.id,
bpid='&'.join(bp_ids),
),
match_page_key='/login/book_post_upload_session',
)
# book has pages, so it should status should be set accordingly
book = Book.from_id(self._book.id)
self.assertEqual(book.status, BOOK_STATUS_ACTIVE)
示例4: test__download
def test__download(self):
downloader = CBZDownloader()
self.assertTrue(downloader)
env = globals()
request = env['request']
def test_http(args, expect):
request.args = List(args)
try:
downloader.download(request, db)
except HTTP as http:
self.assertEqual(http.status, expect['status'])
if expect['status'] == 200:
self.assertEqual(
http.headers['Content-Type'],
'application/x-cbz'
)
self.assertEqual(
http.headers['Content-Disposition'],
'attachment; filename="{f}"'.format(
f=expect['filename'])
)
self.assertEqual(
http.headers['Content-Length'],
expect['size']
)
# Find a book with a cbz.
creator = Creator.by_email(web.username)
query = (db.book.creator_id == creator.id) & \
(db.book.cbz != None)
book = Book.from_query(query)
if not book:
self.fail('Book by creator {c} with cbz not found.'.format(
c=creator.email))
test_http(
[book.id],
dict(
status=200,
filename=os.path.basename(book.cbz),
size=os.stat(book.cbz).st_size,
)
)
# Test invalids
invalid_record_id = -1
test_http([invalid_record_id], dict(status=404))
# Find a book without a cbz.
book = Book.from_key(dict(cbz=None))
if book:
test_http([book.id], dict(status=404))
示例5: test__applies
def test__applies(self):
book = Book(dict(
complete_in_progress=False
))
barrier = CompleteInProgressBarrier(book)
self.assertFalse(barrier.applies())
book.update(complete_in_progress=True)
barrier = CompleteInProgressBarrier(book)
self.assertTrue(barrier.applies())
示例6: setUpClass
def setUpClass(cls):
# C0103: *Invalid name "%%s" (should match %%s)*
# pylint: disable=C0103
# Get the data the tests will use.
cls._creator = Creator.by_email(web.username)
cls._book = Book.from_key(dict(creator_id=cls._creator.id))
cls._server_ip = web.server_ip()
示例7: setUpClass
def setUpClass(cls):
# C0103: *Invalid name "%%s" (should match %%s)*
# pylint: disable=C0103
# Get the data the tests will use.
email = web.username
query = (db.auth_user.email == email)
cls._user = db(query).select(limitby=(0, 1)).first()
if not cls._user:
msg = 'No user with email: {e}'.format(e=email)
print msg
raise SyntaxError(msg)
query = db.creator.auth_user_id == cls._user.id
cls._creator = Creator.from_query(query)
if not cls._creator:
msg = 'No creator with email: {e}'.format(e=email)
print msg
raise SyntaxError(msg)
cls._creator_as_dict = cls._creator.as_dict()
query = (db.book.creator_id == cls._creator.id) & \
(db.book.name_for_url == 'TestDoNotDelete-001')
cls._book = Book.from_query(query)
cls._book_page = get_page(cls._book, page_no='first')
id_max = db.optimize_img_log.id.max()
cls._max_optimize_img_log_id = \
db(db.optimize_img_log).select(id_max)[0][id_max]
cls._test_data_dir = os.path.join(request.folder, 'private/test/data/')
示例8: do_test_random
def do_test_random(request_vars):
"""Run test."""
self._request.vars = request_vars
router = Router(db, self._request, auth)
router.page_not_found()
self.assertTrue('urls' in router.view_dict)
self.assertTrue('suggestions' in router.view_dict['urls'])
labels = [
x['label'] for x in router.view_dict['urls']['suggestions']]
self.assertEqual(
labels,
['Cartoonist page:', 'Book page:', 'Read:']
)
self.assertEqual(
router.view_dict['urls']['invalid'],
'http://www.domain.com/path/to/page'
)
self.assertEqual(router.view, 'errors/page_not_found.html')
book_url = router.view_dict['urls']['suggestions'][1]['url']
# http://127.0.0.1:8000/FirstLast/MyBook
unused_scheme, _, unused_url, creator_for_url, book_for_url = \
book_url.split('/')
got = Creator.from_key(dict(
name_for_url=urllib.unquote(creator_for_url)))
self.assertTrue(got)
got = Book.from_key(dict(
name_for_url=urllib.unquote(book_for_url)))
self.assertTrue(got)
self.assertTrue(got.release_date is not None)
示例9: download
def download(
self, request, db, chunk_size=DEFAULT_CHUNK_SIZE, attachment=True,
download_filename=None):
"""
Adapted from Response.download.
request.args(0): integer, id of book record.
"""
current.session.forget(current.response)
if not request.args:
raise HTTP(404)
try:
book = Book.from_id(request.args(0))
except LookupError:
raise HTTP(404)
filename = book.cbz
if not filename or not os.path.exists(filename):
raise HTTP(404)
stream = os.path.abspath(filename)
headers = self.headers
headers['Content-Type'] = contenttype(filename)
if download_filename is None:
download_filename = os.path.basename(filename)
if attachment:
fmt = 'attachment; filename="%s"'
headers['Content-Disposition'] = \
fmt % download_filename.replace('"', '\"')
return self.stream(stream, chunk_size=chunk_size, request=request)
示例10: modal
def modal():
"""Contributions input controller for modal view.
request.vars.book_id: id of book, optional
request.vars.creator_id: id of creator, optional
if request.vars.book_id is provided, a contribution to a book is presumed.
if request.vars.creator_id is provided, a contribution to a creator is
presumed.
if neither request.vars.book_id nor request.vars.creator_id are provided
a contribution to zco.mx is presumed.
request.vars.book_id takes precendence over request.vars.creator_id.
"""
book = None
creator = None
if request.vars.book_id:
book = Book.from_id(request.vars.book_id)
creator = Creator.from_id(book.creator_id)
elif request.vars.creator_id:
creator = Creator.from_id(request.vars.creator_id)
if not creator:
raise LookupError(
'Creator not found, id %s', request.vars.creator_id)
return dict(
book=book,
creator=creator,
)
示例11: create_book_page
def create_book_page(db, book_id, image_filename):
"""Add the file to the book pages.
Args:
book_id: integer, id of book record the files belong to
image_filename: /path/to/name of image file
"""
try:
stored_filename = store(db.book_page.image, image_filename)
except IOError as err:
LOG.error('IOError: %s', str(err))
return
book = Book.from_id(book_id)
try:
last_page = get_page(book, page_no='last')
except LookupError:
last_page = None
page_no = last_page.page_no + 1 if last_page else 1
data = dict(
book_id=book_id,
page_no=page_no,
image=stored_filename,
)
book_page = BookPage.from_add(data)
return book_page.id
示例12: log_completed
def log_completed():
"""Create activity_log records for books set as completed. """
query = (db.book.release_date != None)
ids = [x.id for x in db(query).select(db.book.id)]
for book_id in ids:
book = Book.from_id(book_id)
# Check if log exists
query = (db.activity_log.action == 'completed') & \
(db.activity_log.book_id == book.id)
count = db(query).count()
if not count:
LOG.debug('Logging completed: %s', book.name)
try:
first_page = get_page(book, page_no='first')
except LookupError:
LOG.error('First page not found: %s', book.name)
continue
db.activity_log.insert(
book_id=book.id,
book_page_ids=[first_page.id],
action='completed',
time_stamp=datetime.datetime.combine(
book.release_date, datetime.datetime.max.time())
)
db.commit()
示例13: main
def main():
"""Main processing."""
usage = '%prog [options]'
parser = OptionParser(usage=usage, version=VERSION)
parser.add_option(
'--man',
action='store_true', dest='man', default=False,
help='Display manual page-like help and exit.',
)
parser.add_option(
'-v', '--verbose',
action='store_true', dest='verbose', default=False,
help='Print messages to stdout.',
)
parser.add_option(
'--vv',
action='store_true', dest='vv', default=False,
help='More verbose.',
)
(options, unused_args) = parser.parse_args()
if options.man:
man_page()
quit(0)
set_cli_logging(LOG, options.verbose, options.vv)
LOG.info('Started.')
ids = [x.id for x in db(db.book).select(db.book.id)]
for book_id in ids:
book = Book.from_id(book_id)
meta = BookPublicationMetadata.from_book(book)
try:
publication_year = meta.publication_year()
except ValueError:
continue # This is expected if the metadata is not set.
if book.publication_year == publication_year:
continue
LOG.debug('Updating: %s to %s', book.name, publication_year)
book = Book.from_updated(book, dict(publication_year=publication_year))
LOG.info('Done.')
示例14: set_page_added_on
def set_page_added_on(book_id):
"""Set the book.page_added_on value
Args:
book_id: integer, id of book
"""
book = Book.from_id(book_id)
LOG.debug('Checking book: %s', book.name)
max_created_on = db.book_page.created_on.max()
query = (db.book_page.book_id == book.id)
rows = db(query).select(max_created_on)
if not rows:
return
page_added_on = rows[0][max_created_on]
if page_added_on:
LOG.debug('Updating book: %s %s', book.name, page_added_on)
book = Book.from_updated(book, dict(page_added_on=page_added_on))
示例15: book_name_rep
def book_name_rep(value, row):
"""db.book.name.represent."""
# unused-argument (W0613): *Unused argument %%r*
# pylint: disable=W0613
book = Book.from_id(row.book.id)
return A(
formatted_name(book, include_publication_year=False),
_href=book_url(book, extension=False)
)