-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsend.py
71 lines (50 loc) · 1.7 KB
/
jsend.py
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
__author__ = 'zirony'
import json
# Support Python 2/3 unicode
try:
strtype = unicode
except:
strtype = bytes
class DictEx(dict):
def stringify(self):
return json.dumps(self)
def success(data={}):
if not isinstance(data, dict):
raise ValueError('data must be the dict type')
return DictEx({'status': 'success', 'data': data})
def fail(data={}):
if not isinstance(data, dict):
raise ValueError('data must be the dict type')
return DictEx({'status': 'fail', 'data': data})
def error(message='', code=None, data=None):
ret = {}
if (not isinstance(message, str)) and (not isinstance(message, strtype)):
raise ValueError('message must be the str type')
if code:
if not isinstance(code, int):
raise ValueError('code must be the int type')
ret['code'] = code
if data:
if not isinstance(data, dict):
raise ValueError('data must be the dict type')
ret['data'] = data
ret['status'] = 'error'
ret['message'] = message
return DictEx(ret)
def loads(jsend_string):
if not jsend_string:
raise ValueError('invalid jsend string is given')
try:
json_data = json.loads(jsend_string)
except (TypeError, ValueError):
raise ValueError('failed to parse json string')
if ('status' not in json_data or
json_data['status'] not in ('success', 'fail', 'error')):
raise ValueError('not in valid jsend type')
return DictEx(json_data)
def is_success(jsend_msg):
return jsend_msg['status'] == 'success'
def is_fail(jsend_msg):
return jsend_msg['status'] == 'fail'
def is_error(jsend_msg):
return jsend_msg['status'] == 'error'