utils.py 5.96 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Copyright 2012 - 2013 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
import json
35
36
import csv
import functools
37
38
39
40
41
42
43
44
45
from datetime import datetime
from django.utils.timesince import timesince, timeuntil

from synnefo.util.text import uenc, udec


def parse_bool(value, strict=True):
    """Convert a string to boolen value.

46
    If strict is True, then ValueError will be raised, if the string can not be
47
48
49
50
51
52
53
54
55
    converted to boolean. Otherwise the string will be returned as is.

    """
    if value.lower() in ("yes", "true", "t", "1"):
        return True
    if value.lower() in ("no", "false", "f", "0"):
        return False

    if strict:
56
        raise ValueError("Cannot convert '%s' to boolean value" % value)
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
    else:
        return value


def format_bool(b):
    """Convert a boolean value to YES or NO."""
    return "YES" if b else "NO"


def format_date(d):
    if not d:
        return ""

    if d < datetime.now():
        return timesince(d) + " ago"
    else:
        return "in " + timeuntil(d)


def parse_filters(filter_by):
    """Parse a string into lookup parameters for QuerySet.filter(**kwargs).

    This functions converts a string of comma-separated key 'cond' val triples
    to two dictionaries, containing lookup parameters to be used for filter
    and exclude functions of QuerySet.

    e.g. filter_by="foo>=2, baz!=4" -> ({"foo__gte": "2"}, {"baz": "4"})

    """

    filter_dict = {}
    exclude_dict = {}

    filter_list = filter_by.split(",")

    def map_field_type(query):
        if "!=" in query:
            key, val = query.split("!=")
            exclude_dict[key] = parse_bool(val, strict=False)
            return

        OP_MAP = {
            ">=": "__gte",
            "=>": "__gte",
            ">":  "__gt",
            "<=": "__lte",
            "=<": "__lte",
            "<":  "__lt",
            "=":  "",
        }

        for op, new_op in OP_MAP.items():
            if op in query:
                key, val = query.split(op)
                filter_dict[key + new_op] = parse_bool(val, strict=False)
                return

    map(lambda x: map_field_type(x), filter_list)

    return (filter_dict, exclude_dict)


119
def pprint_table(out, table, headers=None, output_format='pretty',
120
                 separator=None, vertical=False, title=None):
121
122
123
124
125
126
127
128
129
130
    """Print a pretty, aligned string representation of table.

    Works by finding out the max width of each column and padding to data
    to this value.
    """

    assert(isinstance(table, (list, tuple))), "Invalid table type"
    if headers:
        assert(isinstance(headers, (list, tuple))), "Invalid headers type"

131
132
133
    sep = separator if separator else "  "

    def stringnify(obj):
134
135
136
137
138
        if isinstance(obj, (unicode, str)):
            return udec(obj)
        else:
            return str(obj)

139
140
    if headers:
        headers = map(stringnify, headers)
141
142
143
    table = [map(stringnify, row) for row in table]

    if output_format == "json":
144
        assert(headers is not None), "json output format requires headers"
145
146
147
148
        table = [dict(zip(headers, row)) for row in table]
        out.write(json.dumps(table, indent=4))
        out.write("\n")
    elif output_format == "csv":
149
        cw = csv.writer(out)
150
        if headers:
151
152
153
            table.insert(0, headers)
        table = map(functools.partial(map, uenc), table)
        cw.writerows(table)
154
    elif output_format == "pretty":
155
156
157
158
159
160
161
        if vertical:
            assert(len(table) == 1)
            row = table[0]
            max_key = max(map(len, headers))
            for row in table:
                for (k, v) in zip(headers, row):
                    k = uenc(k.ljust(max_key))
162
                    v = uenc(v)
163
164
165
166
167
168
169
                    out.write("%s: %s\n" % (k, v))
        else:
            # Find out the max width of each column
            columns = [headers] + table if headers else table
            widths = [max(map(len, col)) for col in zip(*(columns))]

            t_length = sum(widths) + len(sep) * (len(widths) - 1)
170
171
            if title is not None:
                out.write(title.center(t_length) + "\n")
172
173
            if headers:
                # pretty print the headers
Christos Stavrakakis's avatar
Christos Stavrakakis committed
174
                line = sep.join(uenc(v.rjust(w))
175
176
177
178
179
180
181
182
                                for v, w in zip(headers, widths))
                out.write(line + "\n")
                out.write("-" * t_length + "\n")

            # print the rest table
            for row in table:
                line = sep.join(uenc(v.rjust(w)) for v, w in zip(row, widths))
                out.write(line + "\n")
183
184
    else:
        raise ValueError("Unknown output format '%s'" % output_format)