change Results API

This commit is contained in:
Christophe Benz 2010-05-07 19:35:05 +02:00
commit 40d5cc3e0e
6 changed files with 92 additions and 111 deletions

View file

@ -50,6 +50,7 @@ class Account(object):
def __repr__(self):
return u"<Account id='%s' label='%s'>" % (self.id, self.label)
class Operation(object):
def __init__(self):
self.date = None

View file

@ -20,44 +20,9 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
from weboob.capabilities.video import ICapVideoProvider
from weboob.tools.application import ConsoleApplication
from weboob.tools.application.results import BaseItem, FieldException, ObjectItem
class VideoItem(ObjectItem):
def format(self, select=[]):
if select:
return u'\t'.join(self.get(field) for field in select)
else:
lines = [
u'ID: %s' % self.obj.id,
u'title: %s'% self.obj.title,
u'duration: %s'% self.obj.formatted_duration,
u'URL: %s'% self.obj.url,
u'author: %s'% self.obj.author,
u'date: %s'% self.obj.date,
u'rating_max: %s'% self.obj.rating,
u'rating: %s'% self.obj.rating_max,
]
return u'\n'.join(lines)
class SearchResultItem(BaseItem):
def __init__(self, _id, title, duration):
self.id = _id
self.title = title
self.duration = duration
def get(self, name):
try:
return getattr(self, name)
except AttributeError:
raise FieldException(name)
def format(self, select=[]):
if select:
return u'\t'.join(unicode(self.get(field)) for field in select)
else:
return u'%s %s (%s)' % (self.id, self.title, self.duration)
__all__ = ['Videoob']
class Videoob(ConsoleApplication):
@ -79,11 +44,14 @@ class Videoob(ConsoleApplication):
for backend, video in self.weboob.do('get_video', id):
if video is None:
continue
print self.format(VideoItem(video))
s = self.format(video)
if s:
print s
@ConsoleApplication.command('Search videos')
def command_search(self, pattern=None):
print u'Search pattern: %s' % pattern if pattern else u'Last videos'
for backend, video in self.weboob.do(
'iter_search_results', pattern=pattern, nsfw=self.options.nsfw):
print self.format(SearchResultItem(video.id, title=video.title, duration=video.formatted_duration))
for backend, video in self.weboob.do('iter_search_results', pattern=pattern, nsfw=self.options.nsfw):
s = self.format(video)
if s:
print s

View file

@ -27,12 +27,17 @@ from functools import partial
from weboob.modules import BackendsConfig
from .base import BaseApplication
from .results import FieldException, ItemGroup
from .formatters import SimpleFormatter
from .results import Results
__all__ = ['ConsoleApplication']
formatters_classes = dict(
simple=SimpleFormatter,
)
class ConsoleApplication(BaseApplication):
SYNOPSIS = 'Usage: %prog [options (-h for help)] command [parameters...]'
@ -52,9 +57,13 @@ class ConsoleApplication(BaseApplication):
command = '%s %s' % (name, arguments)
self._parser.description += ' %-30s %s\n' % (command, doc_string)
self._parser.add_option('-f', '--formatter', default='simple', choices=formatters_classes.keys(),
help='select output formatter (%s)' % u','.join(formatters_classes.keys()))
self._parser.add_option('-s', '--select', help='select result item key(s) to display (comma-separated)')
def _handle_app_options(self):
self._formatter = formatters_classes[self.options.formatter]
if self.options.select:
self.selected_fields = self.options.select.split(',')
else:
@ -134,15 +143,13 @@ class ConsoleApplication(BaseApplication):
sys.stderr.write("Command '%s' takes %d arguments.\n" % (command, nb_min_args))
return 1
try:
command_result = func(*args)
except FieldException, e:
logging.error(e)
return 1
command_result = func(*args)
# Process result
if isinstance(command_result, ItemGroup):
print command_result.format(select=self.selected_fields)
if isinstance(command_result, Results):
s = self.format(command_result)
if s:
print s
return 0
elif isinstance(command_result, (str, unicode)):
print command_result
@ -185,7 +192,7 @@ class ConsoleApplication(BaseApplication):
return partial(f, doc_string=doc_string)
def format(self, result):
return result.format(select=self.selected_fields)
return self._formatter.format(result, selected_fields=self.selected_fields)
register_command = staticmethod(register_command)
command = staticmethod(command)

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
# Copyright(C) 2010 Christophe Benz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
from .simple import SimpleFormatter

View file

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
# Copyright(C) 2010 Christophe Benz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import logging
__all__ = ['SimpleFormatter']
class SimpleFormatter(object):
@classmethod
def format(cls, obj, selected_fields=None):
def iter_fields(obj):
import types
for attribute_name in dir(obj):
if attribute_name.startswith('_'):
continue
attribute = getattr(obj, attribute_name)
if not isinstance(attribute, types.MethodType):
yield attribute_name, attribute
if hasattr(obj, 'iter_fields'):
fields_iterator = obj.iter_fields()
else:
fields_iterator = iter_fields(obj)
d = dict((k, v) for k, v in fields_iterator)
if selected_fields is None:
return u'\n'.join(u'%s: %s' % (k, unicode(d[k])) for k in sorted(d)) + u'\n'
else:
return u'\t'.join(unicode(d[k]) for k in selected_fields if d[k] is not None)

View file

@ -16,15 +16,10 @@
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
__all__ = ['BaseItem', 'FieldException', 'FieldsItem', 'ItemGroup', 'ObjectItem']
__all__ = ['Results']
class FieldException(Exception):
def __init__(self, name):
Exception.__init__(self, 'Field "%s" does not exist.' % name)
class ItemGroup(object):
class Results(object):
def __init__(self, name=u'', header=None):
self.name = name
self._groups = []
@ -59,7 +54,7 @@ class ItemGroup(object):
def get_or_create_group(self, name, group_class=None):
if group_class is None:
group_class = ItemGroup
group_class = Results
group = self.get_group(name)
if group:
return group
@ -70,57 +65,3 @@ class ItemGroup(object):
def iter_groups(self):
return iter(self._groups)
def format(self, select=[]):
formatted = u''
if select:
formatted += u'\n'.join(item.format(select) for item in self.deep_iter_items())
else:
if self.header:
formatted += '%s\n' % self.header
formatted += u'\n'.join(item.format() for item in self.iter_items())
formatted += u'\n\n'.join(group.format() for group in self.iter_groups())
return formatted
class BaseItem(object):
def get(self, name):
raise NotImplementedError()
def format(self, select=[]):
raise NotImplementedError()
class FieldsItem(BaseItem):
def __init__(self, fields=[]):
self._fields = fields
def add_field(self, *args, **kwargs):
if args:
name, value = args
elif kwargs:
name, value = kwargs.items()[0]
self._fields.append((name, value))
def get(self, name):
try:
return [value for _name, value in self._fields if name.lower() == _name.lower()][0]
except IndexError:
raise FieldException(name)
def format(self, select=[]):
if select:
return [value for name, value in self._fields if name in select]
else:
return u'; '.join(u'%s: %s' % (name, value) for name, value in self._fields)
class ObjectItem(BaseItem):
def __init__(self, obj):
self.obj = obj
def get(self, name):
try:
return getattr(self.obj, name)
except AttributeError:
raise FieldException(name)