From a6fbcbaec7027809e9456dd13b3dc3b027377851 Mon Sep 17 00:00:00 2001 From: Laurent Bachelier Date: Sat, 9 Mar 2013 12:25:22 +0100 Subject: [PATCH] Reconcile the two previous commits (json/to_dict) Also fix some to_dict move things that were incomplete. And some PEP8 fixes. closes #1060 closes #1061 --- weboob/capabilities/base.py | 20 +++++++++++++++---- .../application/formatters/iformatter.py | 17 ++++++++++++---- weboob/tools/application/formatters/json.py | 19 ++++++++++-------- 3 files changed, 40 insertions(+), 16 deletions(-) diff --git a/weboob/capabilities/base.py b/weboob/capabilities/base.py index e4bb1d53..d05a4661 100644 --- a/weboob/capabilities/base.py +++ b/weboob/capabilities/base.py @@ -62,7 +62,8 @@ class FieldNotFound(Exception): """ def __init__(self, obj, field): Exception.__init__(self, - u'Field "%s" not found for object %s' % (field, obj)) + u'Field "%s" not found for object %s' % (field, obj)) + class ConversionWarning(UserWarning): """ @@ -71,12 +72,14 @@ class ConversionWarning(UserWarning): """ pass + class AttributeCreationWarning(UserWarning): """ A non-field attribute has been created with a name not prefixed with a _. """ + class NotAvailableMeta(type): def __str__(self): return unicode(self).decode('utf-8') @@ -158,6 +161,7 @@ class Field(object): """ return value + class IntField(Field): """ A field which accepts only :class:`int` and :class:`long` types. @@ -168,6 +172,7 @@ class IntField(Field): def convert(self, value): return int(value) + class DecimalField(Field): """ A field which accepts only :class:`decimal` type. @@ -180,6 +185,7 @@ class DecimalField(Field): return value return Decimal(value) + class FloatField(Field): """ A field which accepts only :class:`float` type. @@ -190,6 +196,7 @@ class FloatField(Field): def convert(self, value): return float(value) + class StringField(Field): """ A field which accepts only :class:`unicode` strings. @@ -200,6 +207,7 @@ class StringField(Field): def convert(self, value): return to_unicode(value) + class BytesField(Field): """ A field which accepts only :class:`str` strings. @@ -212,6 +220,7 @@ class BytesField(Field): value = value.encode('utf-8') return str(value) + class DateField(Field): """ A field which accepts only :class:`datetime.date` and :class:`datetime.datetime` types. @@ -219,6 +228,7 @@ class DateField(Field): def __init__(self, doc, **kwargs): Field.__init__(self, doc, datetime.date, datetime.datetime, **kwargs) + class TimeField(Field): """ A field which accepts only :class:`datetime.time` and :class:`datetime.time` types. @@ -226,6 +236,7 @@ class TimeField(Field): def __init__(self, doc, **kwargs): Field.__init__(self, doc, datetime.time, datetime.datetime, **kwargs) + class DeltaField(Field): """ A field which accepts only :class:`datetime.timedelta` type. @@ -233,6 +244,7 @@ class DeltaField(Field): def __init__(self, doc, **kwargs): Field.__init__(self, doc, datetime.timedelta, **kwargs) + class _CapBaseObjectMeta(type): def __new__(cls, name, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in attrs.items() if isinstance(obj, Field)] @@ -254,6 +266,7 @@ class _CapBaseObjectMeta(type): new_class.__doc__ += '\n:var %s: %s' % (name, doc) return new_class + class CapBaseObject(object): """ This is the base class for a capability object. @@ -370,7 +383,8 @@ class CapBaseObject(object): # If the value was converted if nvalue is not value: warnings.warn('Value %s was converted from %s to %s' % - (name, type(value), type(nvalue)), ConversionWarning, stacklevel=2) + (name, type(value), type(nvalue)), + ConversionWarning, stacklevel=2) value = nvalue except Exception: # error during conversion, it will probably not @@ -399,5 +413,3 @@ class CapBaseObject(object): fields_iterator = self.iter_fields() return OrderedDict(iter_decorate(fields_iterator)) - - diff --git a/weboob/tools/application/formatters/iformatter.py b/weboob/tools/application/formatters/iformatter.py index c44dd7ab..f83c9352 100644 --- a/weboob/tools/application/formatters/iformatter.py +++ b/weboob/tools/application/formatters/iformatter.py @@ -27,13 +27,16 @@ if sys.platform == 'win32': import WConio try: - import tty, termios + import tty + import termios except ImportError: PROMPT = '--Press return to continue--' + def readch(): # NOQA return sys.stdin.readline() else: PROMPT = '--Press a key to continue--' + def readch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) @@ -49,6 +52,7 @@ else: from weboob.capabilities.base import CapBaseObject from weboob.tools.application.console import ConsoleApplication +from weboob.tools.ordereddict import OrderedDict __all__ = ['IFormatter', 'MandatoryFieldsNotFound'] @@ -90,7 +94,9 @@ class IFormatter(object): if sys.platform == 'win32': self.termrows = WConio.gettextinfo()[8] else: - self.termrows = int(subprocess.Popen('stty size', shell=True, stdout=subprocess.PIPE).communicate()[0].split()[0]) + self.termrows = int( + subprocess.Popen('stty size', shell=True, stdout=subprocess.PIPE).communicate()[0].split()[0] + ) def output(self, formatted): if self.outfile != sys.stdout: @@ -143,7 +149,10 @@ class IFormatter(object): formatted = self.format_obj(obj, alias) else: - obj = self.to_dict(obj) + try: + return OrderedDict(obj) + except ValueError: + raise TypeError('Please give a CapBaseObject or a dict') if selected_fields is not None and not '*' in selected_fields: obj = obj.copy() @@ -184,7 +193,7 @@ class IFormatter(object): """ return NotImplementedError() - + class PrettyFormatter(IFormatter): def format_obj(self, obj, alias): title = self.get_title(obj) diff --git a/weboob/tools/application/formatters/json.py b/weboob/tools/application/formatters/json.py index f7354a89..e40869e0 100644 --- a/weboob/tools/application/formatters/json.py +++ b/weboob/tools/application/formatters/json.py @@ -18,22 +18,25 @@ # along with weboob. If not, see . -from .iformatter import IFormatter from weboob.tools.json import json + +from .iformatter import IFormatter + __all__ = ['JsonFormatter'] + class Encoder(json.JSONEncoder): - "generic weboob objects encoder" + "generic weboob object encoder" + def default(self, obj): - try : + try: return json.JSONEncoder.default(self, obj) except TypeError: - i = IFormatter() - try : - dico = i.to_dict(obj) - except TypeError: + try: + dct = obj.to_dict() + except AttributeError: return str(obj) - for z in dico: + for z in dct: return z