Passed
Push — master ( b1c88b...544271 )
by Chris
01:05
created

sql2dict()   A

Complexity

Conditions 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 3
dl 0
loc 13
rs 9.4285
1
"""Standard filters."""
2
3
from string import ascii_lowercase
4
5
6
def title(word, capitalize=False):
7
    """Convert a string to a title format, where the words are capitalized.
8
9
    Args:
10
        word (string): The string to format.
11
12
    Returns:
13
        word (string): The formatted word.
14
    """
15
    def _capitalize(w):
16
        return '{0}{1}'.format(w[0].upper(), w[1:])
17
18
    if word is None:
19
        return ''
20
    words = word.split(' ')
21
    for i, word in enumerate(words):
22
        if i == 0 or capitalize:
23
            words[i] = _capitalize(word)
24
    return ' '.join(words)
25
26
27
def firstof(seq):
28
    """Return the first item that is truthy in a sequence.
29
30
    Equivalent to Djangos' firstof.
31
32
    Args:
33
        seq (list): A list of values.
34
35
    Returns:
36
        value (mixed): The output, depending on the truthiness of the input.
37
    """
38
    if not any(seq):
39
        return ''
40
    if all(seq):
41
        return seq[0]
42
    while seq:
43
        item = seq.pop(0)
44
        if item:
45
            return item
46
    return ''
47
48
49
def questionize_label(word):
50
    """Convert a word to a true/false style question format.
51
52
    If a user follows the convention of using `is_something`, or
53
    `has_something`, for a boolean value, the *property* text will
54
    automatically be converted into a more human-readable
55
    format, e.g. 'Something?' for is_ and Has Something? for has_.
56
57
    Args:
58
        word (string): The string to format.
59
60
    Returns:
61
        word (string): The formatted word.
62
    """
63
    if word is None:
64
        return ''
65
    if word.startswith('is_'):
66
        return '{0}?'.format(word[3:])
67
    elif word.startswith('has_'):
68
        return '{0}?'.format(word[4:])
69
    return word
70
71
72
def add(lst, arg):
73
    """Add an item to a list.
74
75
    Equivalent to Djangos' add.
76
77
    Args:
78
        lst (list): A list.
79
        arg (mixed): Any value to append to the list.
80
81
    Returns:
82
        list: The updated list.
83
    """
84
    lst.append(arg)
85
    return lst
86
87
88
def cut(val, removals):
89
    """Remove some value from a string.
90
91
    Similar to Djangos' cut, but accepts N arguments to remove, in turn.
92
93
    Args:
94
        val (str): A string.
95
        removals (list): Alist of values to remove in turn, from the value.
96
97
    Returns:
98
        str: The updated string.
99
    """
100
    def _cut(val, tocut):
101
        return val.replace(tocut, '')
102
    for r in removals:
103
        val = _cut(val, r)
104
    return val
105
106
107
def addslashes(val):
108
    """Add slashes before all single quotes in a given string.
109
110
    Equivalent to Djangos' addslashes.
111
112
    Args:
113
        val (str): A string.
114
115
    Returns:
116
        str: The updated string.
117
    """
118
    return val.replace("'", "\\'")
119
120
121
def default(val, default):
122
    """Default to a given value if another given value is falsy.
123
124
    Equivalent to Djangos' default.
125
126
    Args:
127
        val (mixed): A mixed value that is truthy or falsy.
128
        default (mixed): A default replacement value.
129
130
    Returns:
131
        mixed: The default given value, or the original value.
132
    """
133
    return default if not val else val
134
135
136
def default_if_none(val, default):
137
    """Default to a given value if another given value is None.
138
139
    Equivalent to Djangos' default_if_none.
140
141
    Args:
142
        val (mixed): A mixed value that may or may not be None.
143
        default (mixed): A default replacement value.
144
145
    Returns:
146
        mixed: The default given value, or the original value.
147
    """
148
    return default if val is None else val
149
150
151
def get_digit(val, index):
152
    """Return the digit of a value specified by an index.
153
154
    Equivalent to Djangos' get_digit.
155
156
    Args
157
        val (int): An integer.
158
        index (int): The index to check against.
159
160
    Returns:
161
        int: The original integer if index is invalid, otherwise the digit
162
        at the specified index.
163
    """
164
    digits = reversed(list(str(val)))
165
    for k, digit in enumerate(digits):
166
        if k + 1 == int(index):
167
            return int(digit)
168
    return val
169
170
171
def length_is(val, length):
172
    """Return True if the length of a given value matches a given length.
173
174
    Equivalent to Djangos' length_is.
175
176
    Args:
177
        val (mixed): A value to check the length of.
178
        length (int): The length to check.
179
180
    Returns:
181
        bool: The value of checking the length against length.
182
    """
183
    return len(val) == length
184
185
186
def is_url(val):
187
    """Return true if a value is a url string, otherwise false.
188
189
    Args:
190
        val (mixed): The value to check.
191
192
    Returns:
193
        bool: True if the value is an http string, False if not.
194
    """
195
    if isinstance(val, (str, unicode)):
196
        return val.startswith('http://') or val.startswith('https://')
197
    return False
198
199
200
def ljust(string, amt):
201
    """Left-align the value by the amount specified.
202
203
    Equivalent to Djangos' ljust.
204
205
    Args:
206
        string (str): The string to adjust.
207
        amt (int): The amount of space to adjust by.
208
209
    Returns:
210
        str: The padded string.
211
    """
212
    return string.ljust(amt)
213
214
215
def rjust(string, amt):
216
    """Right-align the value by the amount specified.
217
218
    Equivalent to Djangos' rjust.
219
220
    Args:
221
        string (str): The string to adjust.
222
        amt (int): The amount of space to adjust by.
223
224
    Returns:
225
        str: The padded string.
226
    """
227
    return string.rjust(amt)
228
229
230
def make_list(val, coerce_numbers=True):
231
    """Make a list from a given value.
232
233
    Roughly equivalent to Djangos' make_list, with some enhancements.
234
235
    Args:
236
        val (mixed): The value to convert.
237
        coerce_numbers (bool, optional): Whether or not string number
238
            should be coerced back to their original values.
239
240
    Returns:
241
        mixed: If dict is given, return d.items(). If list is given, return it.
242
            If integers given, return a list of digits.
243
            Otherwise, return a list of characters.
244
    """
245
    if isinstance(val, dict):
246
        return val.items()
247
    if isinstance(val, list):
248
        return val
249
    vals = list(str(val))
250
    if coerce_numbers and isinstance(val, str):
251
        lst = []
252
        for v in vals:
253
            try:
254
                lst.append(int(v))
255
            except ValueError:
256
                lst.append(v)
257
        return lst
258
    return vals
259
260
261
def phone2numeric(phoneword):
262
    """Convert a phoneword string into the translated number equivalent.
263
264
    Roughly equivalent to Djangos' phone2numeric.
265
266
    Args:
267
        phoneword (str): The phoneword string.
268
269
    Returns:
270
        str: The converted string digits.
271
    """
272
    two, three = ['a', 'b', 'c'], ['d', 'e', 'f']
273
    four, five = ['g', 'h', 'i'], ['j', 'k', 'l']
274
    six, seven = ['m', 'n', 'o'], ['p', 'q', 'r', 's']
275
    eight, nine = ['t', 'u', 'v'], ['w', 'x', 'y', 'z']
276
    newdigits = ''
277
    for digit in list(phoneword.lower()):
278
        if digit in two:
279
            newdigits += '2'
280
        elif digit in three:
281
            newdigits += '3'
282
        elif digit in four:
283
            newdigits += '4'
284
        elif digit in five:
285
            newdigits += '5'
286
        elif digit in six:
287
            newdigits += '6'
288
        elif digit in seven:
289
            newdigits += '7'
290
        elif digit in eight:
291
            newdigits += '8'
292
        elif digit in nine:
293
            newdigits += '9'
294
        else:
295
            newdigits += digit
296
    return newdigits
297
298
299
def pagetitle(string, remove_first=False, divider=' > '):
300
    """Convert a string of characters to page-title format.
301
302
    Args:
303
        string (str): The string to conert.
304
        remove_first (bool, optional): Remove the first instance of the
305
            delimiter of the newly formed title.
306
307
    Returns:
308
        str: The converted string.
309
    """
310
    _title = divider.join(string.split('/'))
311
    if remove_first:
312
        _title = _title.replace(divider, '', 1)
313
    return _title
314
315
316
def slugify(string):
317
    """Convert a string of characters to URL slug format.
318
319
    All characters replacing all characters with hyphens if invalid.
320
    Roughly equivalent to Djangos' slugify.
321
322
    Args:
323
        string (str): The string to slugify.
324
325
    Returns:
326
        str: The slugified string.
327
    """
328
    slug = ''
329
    accepted = ['-', '_'] + list(ascii_lowercase) + list('01234567890')
330
    end = len(string) - 1
331
    for k, char in enumerate(string.lower().strip()):
332
        if char not in accepted:
333
            # Forget about the last char if it would get replaced.
334
            if k < end:
335
                slug += '-'
336
        else:
337
            slug += char
338
    return slug
339
340
341
def greet(name, greeting='Hello'):
342
    """Add a greeting to a given name.
343
344
    Args:
345
        name (str): The name to greet.
346
        greeting (str, optional): An optional greeting override.
347
348
    Returns:
349
        str: The updated greeting string.
350
    """
351
    return '{0}, {1}!'.format(greeting, name)
352
353
354
def islist(item):
355
    """Check if an is item is a list - not just a sequence.
356
357
    Args:
358
        item (mixed): The item to check as a list.
359
360
    Returns:
361
        result (bool): True if the item is a list, False if not.
362
363
    """
364
    return isinstance(item, list)
365
366
367
def sql2dict(queryset):
368
    """Return a SQL alchemy style query result into a list of dicts.
369
370
    Args:
371
        queryset (object): The SQL alchemy result.
372
373
    Returns:
374
        result (list): The converted query set.
375
376
    """
377
    if queryset is None:
378
        return []
379
    return [record.__dict__ for record in queryset]
380