Skip to content

Plugin

GraphPlugin

Bases: SingletonPlugin

Graph plugin.

Source code in ckanext/graph/plugin.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
class GraphPlugin(SingletonPlugin):
    """
    Graph plugin.
    """

    implements(interfaces.IConfigurer)
    implements(interfaces.IResourceView, inherit=True)
    implements(datastore_interfaces.IDatastore, inherit=True)
    datastore_field_names = []

    ## IConfigurer
    def update_config(self, config):
        """
        Add our template directories to the list of available templates.

        :param config:
        """
        toolkit.add_template_directory(config, 'theme/templates')
        toolkit.add_resource('theme/assets', 'ckanext-graph')

    ## IResourceView
    def info(self):
        return {
            'name': 'graph',
            'title': 'Graph',
            'schema': {
                'show_date': [is_boolean],
                'date_field': [
                    ignore_empty,
                    is_date_castable,
                    in_list(self.datastore_field_names),
                ],
                'date_interval': [not_empty, in_list(DATE_INTERVALS)],
                'show_count': [is_boolean],
                'count_field': [ignore_empty, in_list(self.datastore_field_names)],
                'count_label': [],
            },
            'icon': 'bar-chart',
            'iframed': False,
            'filterable': True,
            'preview_enabled': False,
            'full_page_edit': False,
        }

    # IDatastore
    def datastore_search(self, context, data_dict, all_field_ids, query_dict):
        return query_dict

    def datastore_validate(self, context, data_dict, all_field_ids):
        return data_dict

    def view_template(self, context, data_dict):
        return 'graph/view.html'

    def form_template(self, context, data_dict):
        return 'graph/form.html'

    def can_view(self, data_dict):
        """
        Specify which resources can be viewed by this plugin.

        :param data_dict:
        """
        # Check that we have a datastore for this resource
        if data_dict['resource'].get('datastore_active'):
            return True
        return False

    def setup_template_variables(self, context, data_dict):
        """
        Setup variables available to templates.

        :param context:
        :param data_dict:
        """

        datastore_fields = utils.get_datastore_field_types()
        self.datastore_field_names = datastore_fields.keys()

        dropdown_options_count = [
            {'value': field_name, 'text': field_name}
            for field_name, field_type in datastore_fields.items()
        ]

        dropdown_options_date = [
            {'value': field_name, 'text': field_name}
            for field_name, field_type in datastore_fields.items()
            if field_type in TEMPORAL_FIELD_TYPES
            or 'date' in field_name.lower()
            or 'time' in field_name.lower()
        ]

        vars = {
            'count_field_options': [None]
            + sorted(dropdown_options_count, key=lambda x: x['text']),
            'date_field_options': [None]
            + sorted(dropdown_options_date, key=lambda x: x['text']),
            'date_interval_options': [
                {'value': interval, 'text': interval} for interval in DATE_INTERVALS
            ],
            'defaults': {},
            'graphs': [],
            'resource': data_dict['resource'],
        }

        if data_dict['resource_view'].get('show_count', None) and data_dict[
            'resource_view'
        ].get('count_field', None):
            count_field = data_dict['resource_view'].get('count_field')

            count_query = Query.new(count_field=count_field)

            records = count_query.run()

            if records:
                count_dict = {
                    'title': data_dict['resource_view'].get('count_label', None)
                    or count_field,
                    'data': [],
                    'options': {
                        'bars': {'show': True, 'barWidth': 0.6, 'align': 'center'},
                        'xaxis': {
                            'ticks': [],
                            'rotateTicks': 60,
                        },
                    },
                }

                for i, record in enumerate(records):
                    key, count = record
                    count_dict['data'].append([i, count])
                    count_dict['options']['xaxis']['ticks'].append([i, key.title()])

                vars['graphs'].append(count_dict)

        # Do we want a date statistics graph
        if (
            data_dict['resource_view'].get('show_date', False)
            and data_dict['resource_view'].get('date_field', None) is not None
        ):
            date_interval = data_dict['resource_view'].get('date_interval')
            date_field = data_dict['resource_view'].get('date_field')

            date_query = Query.new(date_field=date_field, date_interval=date_interval)

            records = date_query.run()

            if records:
                default_options = {
                    'grid': {'hoverable': True, 'clickable': True},
                    'xaxis': {'mode': 'time'},
                    'yaxis': {'tickDecimals': 0},
                }

                total_dict = {
                    'title': 'Total records',
                    'data': [],
                    'options': {
                        'series': {'lines': {'show': True}, 'points': {'show': True}},
                        '_date_interval': date_interval,
                    },
                }

                count_dict = {
                    'title': 'Per %s' % date_interval,
                    'data': [],
                    'options': {
                        'series': {
                            'bars': {'show': True, 'barWidth': 0.6, 'align': 'center'}
                        }
                    },
                }

                total_dict['options'].update(default_options)
                count_dict['options'].update(default_options)

                total = 0

                for record in records:
                    # Convert to string, and then parse as dates
                    # This works for all date and string fields
                    timestamp, count = record
                    total += count
                    total_dict['data'].append([timestamp, total])
                    count_dict['data'].append([timestamp, count])

                vars['graphs'].append(total_dict)
                vars['graphs'].append(count_dict)

        return vars

can_view(data_dict)

Specify which resources can be viewed by this plugin.

Parameters:

Name Type Description Default
data_dict
required
Source code in ckanext/graph/plugin.py
83
84
85
86
87
88
89
90
91
92
def can_view(self, data_dict):
    """
    Specify which resources can be viewed by this plugin.

    :param data_dict:
    """
    # Check that we have a datastore for this resource
    if data_dict['resource'].get('datastore_active'):
        return True
    return False

setup_template_variables(context, data_dict)

Setup variables available to templates.

Parameters:

Name Type Description Default
context
required
data_dict
required
Source code in ckanext/graph/plugin.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def setup_template_variables(self, context, data_dict):
    """
    Setup variables available to templates.

    :param context:
    :param data_dict:
    """

    datastore_fields = utils.get_datastore_field_types()
    self.datastore_field_names = datastore_fields.keys()

    dropdown_options_count = [
        {'value': field_name, 'text': field_name}
        for field_name, field_type in datastore_fields.items()
    ]

    dropdown_options_date = [
        {'value': field_name, 'text': field_name}
        for field_name, field_type in datastore_fields.items()
        if field_type in TEMPORAL_FIELD_TYPES
        or 'date' in field_name.lower()
        or 'time' in field_name.lower()
    ]

    vars = {
        'count_field_options': [None]
        + sorted(dropdown_options_count, key=lambda x: x['text']),
        'date_field_options': [None]
        + sorted(dropdown_options_date, key=lambda x: x['text']),
        'date_interval_options': [
            {'value': interval, 'text': interval} for interval in DATE_INTERVALS
        ],
        'defaults': {},
        'graphs': [],
        'resource': data_dict['resource'],
    }

    if data_dict['resource_view'].get('show_count', None) and data_dict[
        'resource_view'
    ].get('count_field', None):
        count_field = data_dict['resource_view'].get('count_field')

        count_query = Query.new(count_field=count_field)

        records = count_query.run()

        if records:
            count_dict = {
                'title': data_dict['resource_view'].get('count_label', None)
                or count_field,
                'data': [],
                'options': {
                    'bars': {'show': True, 'barWidth': 0.6, 'align': 'center'},
                    'xaxis': {
                        'ticks': [],
                        'rotateTicks': 60,
                    },
                },
            }

            for i, record in enumerate(records):
                key, count = record
                count_dict['data'].append([i, count])
                count_dict['options']['xaxis']['ticks'].append([i, key.title()])

            vars['graphs'].append(count_dict)

    # Do we want a date statistics graph
    if (
        data_dict['resource_view'].get('show_date', False)
        and data_dict['resource_view'].get('date_field', None) is not None
    ):
        date_interval = data_dict['resource_view'].get('date_interval')
        date_field = data_dict['resource_view'].get('date_field')

        date_query = Query.new(date_field=date_field, date_interval=date_interval)

        records = date_query.run()

        if records:
            default_options = {
                'grid': {'hoverable': True, 'clickable': True},
                'xaxis': {'mode': 'time'},
                'yaxis': {'tickDecimals': 0},
            }

            total_dict = {
                'title': 'Total records',
                'data': [],
                'options': {
                    'series': {'lines': {'show': True}, 'points': {'show': True}},
                    '_date_interval': date_interval,
                },
            }

            count_dict = {
                'title': 'Per %s' % date_interval,
                'data': [],
                'options': {
                    'series': {
                        'bars': {'show': True, 'barWidth': 0.6, 'align': 'center'}
                    }
                },
            }

            total_dict['options'].update(default_options)
            count_dict['options'].update(default_options)

            total = 0

            for record in records:
                # Convert to string, and then parse as dates
                # This works for all date and string fields
                timestamp, count = record
                total += count
                total_dict['data'].append([timestamp, total])
                count_dict['data'].append([timestamp, count])

            vars['graphs'].append(total_dict)
            vars['graphs'].append(count_dict)

    return vars

update_config(config)

Add our template directories to the list of available templates.

Parameters:

Name Type Description Default
config
required
Source code in ckanext/graph/plugin.py
37
38
39
40
41
42
43
44
def update_config(self, config):
    """
    Add our template directories to the list of available templates.

    :param config:
    """
    toolkit.add_template_directory(config, 'theme/templates')
    toolkit.add_resource('theme/assets', 'ckanext-graph')