Login

Get typed dictionary from request GET or POST prameters (MergeDict)

Author:
pahaz
Posted:
February 1, 2013
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

Позволяет получить типизированный словарь из входных параметров.

Может быть использован, например, для дальнейшей передаче параметров в objects.filter(**rez).

 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
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
def get_typed_dictionary_from_request_dict(GET, skip_empty_lists=True, suppress_convert_exception=True):
    """
    Request GET variables to typed dictionary.

    types:
    __int -> int() or None
    __str -> unicode()  or None
    __bool -> bool()  or None
    __float -> float()  or None

    __type__list -> [type() if not suppress_convert_exception else None, ..]

    other -> skip

    ex:
    url?qwe__int__list=2&qwe__int__list=4 => {u'qwe': [2, 4]}
    url?qwe__int__list=2&qwe__str__list=4 => {u'qwe': [u'4', 2]}
    url?qwe__bool=2 => {u'qwe': True}
    url?qwe__bool=t => {u'qwe': True}
    url?qwe__bool=0 => {u'qwe': False}
    url?qwe__bool=f => {u'qwe': False}
    url?qwe__float=2.3 => {u'qwe': 2.3}
    """
    def to_bool(str):
        if str.isdigit():
            return bool(int(str))
        elif str.lower() in ['true', 't']:
            return True
        elif str.lower() in ['false', 'f']:
            return False

        return len(str) > 0

    rez = dict()
    for key in GET.keys():
        real_key = key
        is_list = key.endswith('__list')
        if is_list:
            key = key[:-6]

        __type = None
        if key.endswith('__int'):
            key = key[:-5]
            __type = int
        elif key.endswith('__str'):
            key = key[:-5]
            __type = unicode
        elif key.endswith('__bool'):
            key = key[:-6]
            __type = to_bool
        elif key.endswith('__float'):
            key = key[:-7]
            __type = float

        if __type and len(key):
            value = None
            if is_list:
                getlist = GET.getlist(real_key)
                value = []
                for x in getlist:
                    typed = None
                    try:
                        typed = __type(x)
                    except ValueError as e:
                        if not suppress_convert_exception:
                            raise e

                    value.append(typed)

                if len(value) == 0 and skip_empty_lists:
                    continue

            else:

                try:
                    value = __type(GET.get(real_key))
                except ValueError as e:
                    if not suppress_convert_exception:
                        raise e

            if is_list and key in rez:
                rez[key].extend(value)
            else:
                rez[key] = value

    return rez

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.