-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathresponse.py
50 lines (40 loc) · 1.15 KB
/
response.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
import json
from typing import Any, Dict, List, Union
from django.db.models import QuerySet
from django.http.response import JsonResponse
from easy.renderer.json import EasyJSONEncoder
CODE_SUCCESS = 0
SUCCESS_MESSAGE = "success"
class BaseAPIResponse(JsonResponse):
"""
Base for all API responses
"""
def __init__(
self,
data: Union[Dict, str, bool, List[Any], QuerySet] = None,
code: int = None,
message: str = None,
**kwargs: Any
):
if code:
message = message or str(code)
else:
message = message or SUCCESS_MESSAGE
code = CODE_SUCCESS
_data: Union[Dict, str] = {
"code": code,
"message": message,
"data": data if data is not None else {},
}
super().__init__(data=_data, encoder=EasyJSONEncoder, **kwargs)
@property
def json_data(self) -> Any:
"""
Get json data
"""
return json.loads(self.content)
def update_content(self, data: Dict) -> None:
"""
Update content with new data
"""
self.content = json.dumps(data)