Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1from builtins import str 

2import io 

3import datetime 

4import decimal 

5from decimal import Decimal 

6from pyramid.renderers import JSON 

7from pyramid.response import Response 

8 

9 

10class renderer_json(JSON): 

11 """ 

12 *The json renderer - can return content to browser or a file to download* 

13 """ 

14 

15 def __init__(self, info): 

16 JSON.__init__(self, indent=4, sort_keys=True, separators=(',', ': ')) 

17 

18 def __call__(self, info, system): 

19 _render = JSON.__call__(self, info) 

20 

21 data = False 

22 if isinstance(info, list): 

23 data = True 

24 info = {"data": info} 

25 

26 # if table if empty 

27 if len(info): 

28 tableColumnNames = list(info.keys()) 

29 

30 self.add_adapter(datetime.datetime, self.datetime_adapter) 

31 self.add_adapter(decimal.Decimal, self.decimal_adapter) 

32 

33 for c in tableColumnNames: 

34 if (isinstance(info[c], float) or isinstance(info[c], int) or isinstance(info[c], Decimal)) and not isinstance(info[c], bool): 

35 info[c] = float("%0.4f" % info[c]) 

36 elif isinstance(info[c], datetime.datetime): 

37 thisDate = str(info[c])[:10] 

38 info[c] = "%(thisDate)s" % locals() 

39 

40 # setup the file if "download" is true 

41 request = system.get('request') 

42 response = request.response 

43 if "filename" in request.params: 

44 now = datetime.datetime.now() 

45 now = now.strftime("%Y%m%dt%H%M%S") 

46 filename = request.params["filename"].replace(" ", "_") 

47 filename = """%(filename)s_%(now)s""" % locals() 

48 response.content_type = 'text/json' 

49 response.content_disposition = "attachment; filename=%(filename)s.json" % locals( 

50 ) 

51 if data: 

52 info = info["data"] 

53 return _render(info, system) 

54 

55 def datetime_adapter(self, obj, request): 

56 return obj.isoformat() 

57 

58 def decimal_adapter(self, obj, request): 

59 return float(obj)