Пример #1
0
    def test_init_dict1(self):
        j = JsonDict(dict={'first': 'John',
                           'last': 'Doe',
                           'age': 1})
        self.assertEqual(j.first, 'John')
        self.assertEqual(j.last, 'Doe')
        self.assertEqual(j.age, 1)
        self.assertEqual(j.first, j['first'])

        j.first = 'Judy'
        self.assertEqual(j.first, 'Judy')
        self.assertEqual(j.last, 'Doe')
Пример #2
0
    def create(cls,
               section,
               table,
               title,
               width=6,
               cols=None,
               rows=1000,
               height=300):
        """Create a widget displaying data in a two dimensional table.

        :param int width: Width of the widget in columns (1-12, default 6)
        :param int height: Height of the widget in pixels (default 300)
        :param int rows: Number of rows to display (default 1000)
        :param list cols: List of columns by name to include.  If None,
            the default, include all data columns.


        """
        w = Widget(section=section,
                   title=title,
                   rows=rows,
                   width=width,
                   height=height,
                   module=__name__,
                   uiwidget=cls.__name__)
        w.compute_row_col()
        w.options = JsonDict(columns=cols)
        w.save()
        w.tables.add(table)
Пример #3
0
    def create(cls, section, table, title, width=6, rows=10, height=300):
        """Create a widget displaying data in a pie chart.

        :param int width: Width of the widget in columns (1-12, default 6)
        :param int height: Height of the widget in pixels (default 300)
        :param int rows: Number of rows to display (default 10)

        The labels are taken from the Table key column (the first key,
        if the table has multiple key columns defined).  The pie
        widget values are taken from the sort column.

        """
        w = Widget(section=section,
                   title=title,
                   rows=rows,
                   width=width,
                   height=height,
                   module=__name__,
                   uiwidget=cls.__name__)
        w.compute_row_col()
        keycols = [
            col.name for col in table.get_columns() if col.iskey is True
        ]

        if len(keycols) == 0:
            raise ValueError("Table %s does not have any key columns defined" %
                             str(table))

        if table.sortcols is None:
            raise ValueError("Table %s does not have a sort column defined" %
                             str(table))

        w.options = JsonDict(key=keycols[0], value=table.sortcols[0])
        w.save()
        w.tables.add(table)
Пример #4
0
    def test_getattr(self):
        j = JsonDict(first='John', last='Doe', age=1)
        v = getattr(j, 'foo', 42)
        self.assertEqual(v, 42)

        v = getattr(j, 'first', 42)
        self.assertEqual(v, 'John')
Пример #5
0
    def create(cls, section, table, title, width=6, height=300,
               keycols=None, valuecols=None, charttype='candlestick',
               stack_widget=False):
        """Create a widget displaying stock prices as a candle stick chart.

        :param int width: Width of the widget in columns (1-12, default 6)
        :param int height: Height of the widget in pixels (default 300)
        :param list keycols: List of key column names to use for x-axis labels
        :param list valuecols: List of data columns to graph
        :param str charttype: Type of chart, defaults to 'candlestick'.
        :param bool stack_widget: stack this widget below the previous one.

        The Y axis of this widget can't dynamically scale to different ranges.
        """
        w = Widget(section=section, title=title, width=width,
                   height=height, module=__name__, uiwidget=cls.__name__,
                   stack_widget=stack_widget)
        w.compute_row_col()
        if keycols is None:
            keycols = [col.name for col in table.get_columns()
                       if col.iskey is True]
        if len(keycols) == 0:
            raise ValueError("Table %s does not have any key columns defined" %
                             str(table))

        if valuecols is None:
            valuecols = [col.name for col in table.get_columns()
                         if col.iskey is False]
        w.options = JsonDict(dict={'keycols': keycols,
                                   'columns': valuecols,
                                   'axes': None,
                                   'charttype': charttype})
        w.save()
        w.tables.add(table)
Пример #6
0
    def create(cls,
               section,
               table,
               title,
               width=6,
               rows=10,
               height=300,
               keycols=None,
               valuecols=None,
               charttype='line',
               dynamic=False,
               stack_widget=False):
        """Create a widget displaying data as a chart.

        This class is typically not used directly, but via LineWidget
        or BarWidget subclasses

        :param int width: Width of the widget in columns (1-12, default 6)
        :param int height: Height of the widget in pixels (default 300)
        :param int rows: Number of rows to display (default 10)
        :param list keycols: List of key column names to use for x-axis labels
        :param list valuecols: List of data columns to graph
        :param str charttype: Type of chart, defaults to 'line'.  This may be
           any YUI3 'type'
        :param bool dynamic: columns will be added later from criteria if True
        :param bool stack_widget: stack this widget below the previous one.

        """
        w = Widget(section=section,
                   title=title,
                   rows=rows,
                   width=width,
                   height=height,
                   module=__name__,
                   uiwidget=cls.__name__,
                   stack_widget=stack_widget)
        w.compute_row_col()
        if keycols is None:
            keycols = [
                col.name for col in table.get_columns() if col.iskey is True
            ]
        if len(keycols) == 0:
            raise ValueError("Table %s does not have any key columns defined" %
                             str(table))

        if valuecols is None:
            valuecols = [
                col.name for col in table.get_columns() if col.iskey is False
            ]
        w.options = JsonDict(
            dict={
                'keycols': keycols,
                'columns': valuecols,
                'axes': None,
                'charttype': charttype,
                'dynamic': dynamic
            })
        w.save()
        w.tables.add(table)
Пример #7
0
    def create(cls,
               table,
               name,
               label=None,
               datatype=DATATYPE_FLOAT,
               units=UNITS_NONE,
               iskey=False,
               position=None,
               **kwargs):

        column_options = copy.deepcopy(cls.COLUMN_OPTIONS)

        keys = kwargs.keys()
        cp = dict((k, kwargs.pop(k)) for k in keys if k in column_options)
        column_options.update(**cp)

        if column_options:
            options = JsonDict(default=column_options)
        else:
            options = None

        keys = kwargs.keys()
        ckeys = [f.name for f in Column._meta.local_fields]
        col_kwargs = dict((k, kwargs.pop(k)) for k in keys if k in ckeys)

        if kwargs:
            raise AttributeError('Invalid keyword arguments: %s' % str(kwargs))

        ephemeral = col_kwargs.get('ephemeral', None)
        if len(
                Column.objects.filter(
                    table=table, name=name, ephemeral=ephemeral)) > 0:
            raise ValueError("Column %s already in use for table %s" %
                             (name, str(table)))

        datatype = check_field_choice(cls, 'datatype', datatype)
        units = check_field_choice(cls, 'units', units)

        c = Column(table=table,
                   name=name,
                   label=label,
                   datatype=datatype,
                   units=units,
                   iskey=iskey,
                   options=options,
                   **col_kwargs)

        try:
            c.save()
        except DatabaseError as e:
            if 'no such table' in str(e):
                msg = str(e) + ' -- did you forget class Meta: proxy=True?'
                raise DatabaseError(msg)
            raise

        c.position = position or c.id
        c.save()

        return c
Пример #8
0
    def create(cls,
               section,
               table,
               title,
               width=6,
               height=300,
               stacked=False,
               cols=None,
               altaxis=None,
               bar=False,
               stack_widget=False):
        """Create a widget displaying time-series data in a line or bar chart

        :param int width: Width of the widget in columns (1-12, default 6)
        :param int height: Height of the widget in pixels (default 300)
        :param bool stacked: If True, show multiple series as stacked
        :param list cols: List of columns by name to graph.  If None,
            the default, graph all data columns.
        :param list altaxis: List of columns to graph using the
            alternate Y-axis
        :param bool bar: If True, show time series in a bar chart.
        :param bool stack_widget: stack this widget below the previous one.

        As an example, the following will graph four columns of data::

            section.add_widget(yui3.TimeSeriesWidget, 'Bytes and Packets',
                               stacked=True, width=12, height=450,
                               cols=['bytes', 'rtxbytes',
                                     'packets', 'rtxpackets'],
                               altaxis=['packets', rtxpackets'])

        The columns 'bytes' and 'rtxbytes' will be graphed against the left
        Y-axis, 'packets' and 'rtxpackets' on the right (alternate) Y-axis.

        """

        w = Widget(section=section,
                   title=title,
                   width=width,
                   height=height,
                   module=__name__,
                   uiwidget=cls.__name__,
                   stack_widget=stack_widget)
        w.compute_row_col()
        timecols = [
            col.name for col in table.get_columns()
            if col.istime() or col.isdate()
        ]
        if len(timecols) == 0:
            raise ValueError("Table %s must have a datatype 'time' column for "
                             "a timeseries widget" % str(table))

        w.options = JsonDict(columns=cols,
                             altaxis=altaxis,
                             stacked=stacked,
                             bar=bar)
        w.save()
        w.tables.add(table)
Пример #9
0
    def test_init_dict2(self):
        j = JsonDict(dict={'name': {'first': 'John',
                                    'last': 'Doe'},
                           'age': 1})
        self.assertEqual(j.name.first, 'John')
        self.assertEqual(j.name.last, 'Doe')
        self.assertEqual(j.age, 1)
        self.assertEqual(j.name, {'first': 'John', 'last': 'Doe'})

        j.name.first = 'Joe'
        j.name.last = 'Blow'
        self.assertEqual(j.name, {'first': 'Joe', 'last': 'Blow'})
        self.assertEqual(j.age, 1)
Пример #10
0
    def create(cls, *args, **kwargs):
        options = kwargs.pop('options', None)
        table = kwargs.pop('table', None)

        w = Widget(*args, **kwargs)
        w.compute_row_col()

        if options:
            w.options = JsonDict(options)

        w.save()

        if table:
            w.tables.add(table)

        return w
Пример #11
0
    def test_bad_key(self):
        def try_foo(obj):
            return obj['foo']

        j = JsonDict(first='John', last='Doe', age=1)
        self.assertRaises(KeyError, try_foo, j)
Пример #12
0
    def test_bad_attr(self):
        def try_foo(obj):
            return obj.foo

        j = JsonDict(first='John', last='Doe', age=1)
        self.assertRaises(AttributeError, try_foo, j)
Пример #13
0
 def test_init_kw2(self):
     j = JsonDict(name__first='John', name__last='Doe', age=1)
     self.assertEqual(j.name.first, 'John')
     self.assertEqual(j.name.last, 'Doe')
     self.assertEqual(j.age, 1)
Пример #14
0
 def test_init_kw1(self):
     j = JsonDict(first='John', last='Doe', age=1)
     self.assertEqual(j.first, 'John')
     self.assertEqual(j.last, 'Doe')
     self.assertEqual(j.age, 1)
Пример #15
0
    def create(cls, name, **kwargs):
        """Create a table.

        :param str name: Unique identifier for this table

        Standard keyword arguments:

        :param int rows: set maximum number of rows to save after
            sorting (defaults to -1, no maximum)

        :param bool resample: if True, timeseries data returned by the
            data source will be resampled to ``criteria.resample_resolution``
            or ``criteria.resolution``

        :param dict field_map: a dictionary mapping fields by keyword
            to either a new keyword or to a map of field values to
            customize for the given field

                field_map = {'qos': 'qos_1'}

            or

                field_map = {'qos': { 'keyword': 'qos_1',
                                      'label': 'QoS 1',
                                      'default': 'AF' } }

            This is used to remap fields defined by standard tables
            to allow the same table to be used multiple times in the
            same report but with different criteria via different
            keywords.

        Additional table and field options keyword arguments may
        be provided that are unique to the specific data source
        table being instantiatied:

        ``table_options``

            These options define subclass-specific options that allow
            customization of a table instance. Table options are *not*
            visible to users running reports via the UI.  Option
            values are provided at table creation and are considered
            static for the life of this table instance.

        ``field_options``

            Most tables are designed to take input from the user via table
            fields.  The user fills in values for each table field and the set
            of input becomes the report *criteria*.

            Field options allow the report writer to customize the aspects of
            table fields such as the initial value of a form field or the list
            of choices in a drop-down selection field.

        """
        name = slugify(unicode(name))

        # process subclass assigned options
        table_options = copy.deepcopy(cls.TABLE_OPTIONS)
        field_options = copy.deepcopy(cls.FIELD_OPTIONS)

        if hasattr(cls, '_ANALYSIS_TABLE_OPTIONS'):
            table_options.update(cls._ANALYSIS_TABLE_OPTIONS)
            field_options.update(cls._ANALYSIS_FIELD_OPTIONS)

        keys = kwargs.keys()

        # The field_map mapping is stored in table_options for reference
        # later when building criteria for this table
        table_options['field_map'] = {}
        to = dict((k, kwargs.pop(k)) for k in keys if k in table_options)
        table_options.update(**to)

        fo = dict((k, kwargs.pop(k)) for k in keys if k in field_options)
        field_options.update(**fo)

        table_options = cls.process_options(table_options)

        if table_options:
            options = JsonDict(default=table_options)
        else:
            options = None

        # process normal model kwargs
        keys = kwargs.keys()
        tkeys = [f.name for f in Table._meta.local_fields]
        table_kwargs = dict((k, kwargs.pop(k)) for k in keys if k in tkeys)

        if kwargs:
            raise AttributeError('Invalid keyword arguments: %s' % str(kwargs))

        # Table property '_query_class' may be either a string name
        # or an actual class reference.  Convert to string name for storage
        queryclassname = cls._query_class
        if inspect.isclass(queryclassname):
            queryclassname = queryclassname.__name__

        sourcefile = table_kwargs.get('sourcefile',
                                      get_sourcefile(get_module_name()))
        namespace = table_kwargs.get('namespace', get_namespace(sourcefile))

        if len(
                Table.objects.filter(name=name,
                                     namespace=namespace,
                                     sourcefile=sourcefile)) > 0:
            msg = ("Table '%s' already exists in namespace '%s' "
                   "(sourcefile '%s')") % (name, namespace, sourcefile)
            raise ValueError(msg)

        table_kwargs['namespace'] = namespace
        table_kwargs['sourcefile'] = sourcefile

        logger.debug('Creating table %s' % name)
        t = cls(name=name,
                module=cls.__module__,
                queryclassname=queryclassname,
                options=options,
                **table_kwargs)
        try:
            t.save()
        except DatabaseError as e:
            if 'no such table' in str(e):
                msg = str(e) + ' -- did you forget class Meta: proxy=True?'
                raise DatabaseError(msg)
            raise

        # post process table *instance* now that its been initialized
        t.post_process_table(field_options)

        # if field_map has been specified, go through attached fields and
        # change them accordingly
        for keyword, mapped in (t.options.field_map or {}).iteritems():
            try:
                field = t.fields.get(keyword=keyword)
                if isinstance(mapped, basestring):
                    field.keyword = mapped
                else:
                    for k, v in mapped.iteritems():
                        if not hasattr(field, k):
                            raise AttributeError(
                                "Invalid attribute for field '%s': %s" %
                                (field.keyword, k))
                        setattr(field, k, v)

                field.save()
            except ObjectDoesNotExist:
                raise AttributeError('field_map references invalid field: %s' %
                                     keyword)

        return t