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

1#!/usr/bin/env python 

2# encoding: utf-8 

3""" 

4*The model get for the `models_transients_akas_get.py` resource* 

5 

6:Author: 

7 David Young 

8""" 

9from builtins import str 

10from builtins import zip 

11from future import standard_library 

12standard_library.install_aliases() 

13from builtins import object 

14import sys 

15import os 

16import khufu 

17import collections 

18import urllib.request 

19import urllib.parse 

20import urllib.error 

21import re 

22from dryxPyramid.models.models_base import base_model 

23 

24 

25class models_transients_akas_get(base_model): 

26 """ 

27 *The worker class for the models_transients_akas_get module* 

28 

29 **Key Arguments** 

30 

31 - ``log`` -- logger 

32 - ``request`` -- the pyramid request 

33 - ``elementId`` -- the specific element id requests (or False) 

34 

35 

36 **Usage** 

37 

38 ```python 

39 usage code 

40 ``` 

41 

42 ```eval_rst 

43 .. todo:: 

44 

45 - add usage info 

46 - create a sublime snippet for usage 

47 - add a tutorial about ``models_transients_akas_get`` to documentation 

48 - create a blog post about what ``models_transients_akas_get`` does 

49 ``` 

50 """ 

51 

52 def __init__(self, log, request, elementId=False, search=False): 

53 super().__init__(log, request, elementId, search) 

54 self.resourceName = "stats" 

55 self._set_default_parameters() 

56 

57 log.debug( 

58 "instansiating a new 'models_transients_akas_get' object") 

59 

60 # Initial Actions 

61 

62 return None 

63 

64 def get(self): 

65 """ 

66 *execute the get method on the models_transients_akas_get object* 

67 

68 **Return** 

69 

70 - ``responseContent`` -- the reponse to send to the browser 

71 

72 """ 

73 self.log.debug('starting the ``get`` method') 

74 

75 elementId = self.elementId 

76 where = self.sql["where"] 

77 limit = self.sql["limit"] 

78 

79 if elementId: 

80 sqlWhere = where + " and transientBucketId in (%(elementId)s)" % locals( 

81 ) 

82 else: 

83 sqlWhere = "" 

84 

85 sqlQuery = """ 

86 select transientBucketId, GROUP_CONCAT(name) as akas from marshall_transient_akas %(sqlWhere)s group by transientBucketId %(limit)s 

87 """ % locals() 

88 tmp = self.request.db.execute(sqlQuery).fetchall() 

89 

90 theseIds = [] 

91 theseIds[:] = [str(t["transientBucketId"]) for t in tmp] 

92 theseIds = (",").join(theseIds) 

93 sqlWhere = where + \ 

94 " and transientBucketId in (-99, %(theseIds)s)" % locals() 

95 

96 if len(theseIds): 

97 sqlQuery = """ 

98 select transientBucketId, name, url from marshall_transient_akas %(sqlWhere)s and hidden = 0 order by transientBucketId, master desc 

99 """ % locals() 

100 rows = self.request.db.execute(sqlQuery).fetchall() 

101 else: 

102 rows = [] 

103 

104 if not self.qs["format"] or self.qs["format"].lower() != "json": 

105 objectAkas = [] 

106 objectAkas[:] = [dict(list(zip(list(row.keys()), row))) 

107 for row in rows] 

108 responseContent = objectAkas 

109 

110 else: 

111 responseContent = self.convert_to_nested_data_structure( 

112 listOfDict=rows, 

113 primaryKey="transientBucketId", 

114 resourceName="akas", 

115 resourceKeys=["name", "url"]) 

116 

117 self.log.debug('completed the ``get`` method') 

118 return responseContent 

119 

120 def convert_to_nested_data_structure( 

121 self, 

122 listOfDict, 

123 primaryKey, 

124 resourceName, 

125 resourceKeys): 

126 """*given a flat list of dictionaries, converts and returns the content in a nested structure better suited for json rendering* 

127 

128 **Key Arguments** 

129 

130 - ``listOfDict`` -- the list of dictionaries (generally returned from a database query) 

131 - ``primaryKey`` -- the primary key in the result sets by which to group json results by 

132 - ``resourceName`` -- the name of the subresource belong to be collected together 

133 - ``resourceKeys`` -- the name of the keys to be grouped together under the subresource 

134 

135 

136 **Usage** 

137 

138 Here's an example usage of this method: 

139 

140 ```python 

141 responseContent = self.convert_to_nested_data_structure( 

142 listOfDict=rows, 

143 primaryKey="transientBucketId", 

144 resourceName="akas", 

145 resourceKeys=["name", "url"] 

146 ) 

147 ``` 

148 """ 

149 self.log.debug( 

150 'starting the ``convert_to_nested_data_structure`` method') 

151 

152 import collections 

153 orderResults = collections.OrderedDict() 

154 

155 seen = [] 

156 responseBuilder = {} 

157 

158 # CHECK FOR NULL CONTENT 

159 if not len(listOfDict): 

160 return [] 

161 

162 # GET THE ROOT LEVEL KEYS 

163 uniqueKeys = [primaryKey] 

164 for k in list(listOfDict[0].keys()): 

165 if k not in resourceKeys: 

166 uniqueKeys.append(k) 

167 

168 # BUILD THE NESTED STRUCTURE 

169 for row in listOfDict: 

170 pk = str(row[primaryKey]) 

171 

172 # HAVE WE SEEN THE PRIMARYKEY YET? 

173 if pk not in seen: 

174 seen.append(pk) 

175 responseBuilder[pk] = { 

176 primaryKey: row[primaryKey]} 

177 for u in uniqueKeys: 

178 responseBuilder[pk][u] = row[u] 

179 

180 responseBuilder[pk][resourceName] = [] 

181 

182 # APPEND THE RESOURCES 

183 subresource = {} 

184 for k, v in dict(row).items(): 

185 if k in resourceKeys: 

186 subresource[k] = v 

187 if len(subresource): 

188 responseBuilder[pk][resourceName].append(subresource) 

189 

190 # SORT THE NESTED STRUCTURE 

191 sortList = [primaryKey] + sorted(uniqueKeys) + [resourceName] 

192 for name, aDict in list(responseBuilder.items()): 

193 for k in sortList: 

194 orderResults[k] = aDict[k] 

195 responseBuilder[name] = orderResults 

196 

197 responseContent = list(responseBuilder.values()) 

198 

199 self.log.debug( 

200 'completed the ``convert_to_nested_data_structure`` method') 

201 return responseContent 

202 

203 # use the tab-trigger below for new method 

204 # xt-class-method