Completed
Push — master ( 15aed1...81ec71 )
by Chris
01:11
created

to_json()   A

Complexity

Conditions 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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