From 40d5cc3e0e0884211731c2336d4fabcb07bfbf39 Mon Sep 17 00:00:00 2001 From: Christophe Benz Date: Fri, 7 May 2010 19:35:05 +0200 Subject: [PATCH] change Results API --- weboob/capabilities/bank.py | 1 + weboob/frontends/videoob/application.py | 48 +++----------- weboob/tools/application/console.py | 25 ++++--- .../tools/application/formatters/__init__.py | 18 +++++ weboob/tools/application/formatters/simple.py | 46 +++++++++++++ weboob/tools/application/results.py | 65 +------------------ 6 files changed, 92 insertions(+), 111 deletions(-) create mode 100644 weboob/tools/application/formatters/__init__.py create mode 100644 weboob/tools/application/formatters/simple.py diff --git a/weboob/capabilities/bank.py b/weboob/capabilities/bank.py index cf14ddf8..2d9326b1 100644 --- a/weboob/capabilities/bank.py +++ b/weboob/capabilities/bank.py @@ -50,6 +50,7 @@ class Account(object): def __repr__(self): return u"" % (self.id, self.label) + class Operation(object): def __init__(self): self.date = None diff --git a/weboob/frontends/videoob/application.py b/weboob/frontends/videoob/application.py index e563170a..3bb7da91 100644 --- a/weboob/frontends/videoob/application.py +++ b/weboob/frontends/videoob/application.py @@ -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 diff --git a/weboob/tools/application/console.py b/weboob/tools/application/console.py index e9f8dd6d..d019974e 100644 --- a/weboob/tools/application/console.py +++ b/weboob/tools/application/console.py @@ -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) diff --git a/weboob/tools/application/formatters/__init__.py b/weboob/tools/application/formatters/__init__.py new file mode 100644 index 00000000..0007ceea --- /dev/null +++ b/weboob/tools/application/formatters/__init__.py @@ -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 diff --git a/weboob/tools/application/formatters/simple.py b/weboob/tools/application/formatters/simple.py new file mode 100644 index 00000000..58346879 --- /dev/null +++ b/weboob/tools/application/formatters/simple.py @@ -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) diff --git a/weboob/tools/application/results.py b/weboob/tools/application/results.py index 6e0fffd1..95afc228 100644 --- a/weboob/tools/application/results.py +++ b/weboob/tools/application/results.py @@ -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)