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

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

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

#!/usr/bin/env python3 

# system modules 

import logging 

import http.client 

import urllib 

import json 

import contextlib 

 

# internal modules 

from patatmo import utils 

from patatmo.api import responsetypes 

from patatmo.api.variables import * 

from patatmo.api.errors import * 

 

 

class ApiRequest(object): 

""" Class for api requests 

""" 

 

def __init__(self, server, url, payload={}): 

""" class constructor 

Args: 

server (str): the server domain 

url (str): the url relative to the server 

payload [Optional(dict)]: the payload 

""" 

self.server = server 

self.url = url 

self.payload = payload 

 

################## 

### Properties ### 

################## 

@property 

def logger(self): 

""" the logging.Logger used for logging. 

Defaults to logging.getLogger(__name__). 

""" 

try: # try to return the internal property 

return self._logger 

except AttributeError: # didn't work 

return logging.getLogger(__name__) # return default logger 

 

@logger.setter 

def logger(self, logger): # pragma: no cover 

assert isinstance(logger, logging.Logger), \ 

"logger property has to be a logging.Logger" 

self._logger = logger 

 

@property 

def api_connection(self): 

""" The http.client.HTTPSConnection used for server communication. 

You may set this, otherwise a new instance is created automatically on 

first use. 

""" 

try: # try to return the internal attribute 

return self._api_connection 

except AttributeError: # didn't work 

# set it to new instance 

self._api_connection = http.client.HTTPSConnection( 

NETATMO_API_SERVER) 

# return internal attribute 

return self._api_connection 

 

@api_connection.setter 

def api_connection(self, newconn): # pragma: no cover 

if not isinstance(newconn, http.client.HTTPSConnection): 

self.logger.debug( 

"authentication property needs to be of " 

"class HTTPSConnection. Using empty instance instead " 

"of {}.".format(newauth)) 

self._api_connection = http.client.HTTPSConnection( 

NETATMO_API_SERVER) 

else: 

self._api_connection = newconn 

 

@property 

def server(self): 

""" the api server domain 

""" 

try: 

return self._server 

except AttributeError: 

return "" # pragma: no cover 

 

@server.setter 

def server(self, newserver): 

self._server = str(newserver) 

 

@property 

def url(self): 

""" the url relative to the server for this api request 

""" 

try: 

return self._url 

except AttributeError: 

return "" # pragma: no cover 

 

@url.setter 

def url(self, newurl): 

self._url = str(newurl) 

 

@property 

def payload(self): 

""" the payload to send to the api 

""" 

try: 

return self._payload 

except AttributeError: 

return {} # pragma: no cover 

 

@payload.setter 

def payload(self, newpayload): 

try: 

assert isinstance(newpayload, dict) 

json.dumps(newpayload) 

urllib.parse.urlencode(newpayload) 

except (TypeError, AssertionError): # pragma: no cover 

raise InvalidPayloadError("payload has to be a simple dict") 

self._payload = newpayload 

 

@property 

def payload_urlencoded(self): 

""" [read only] return the urlencoded payload (UTF-8) 

""" 

return urllib.parse.urlencode(self.payload, encoding="UTF-8") 

 

@property 

def response(self): 

""" the api response to this request. Instance of ApiResponse or 

derivates. Issues the request if necessary. You should not set this 

property. 

""" 

try: 

return self._response 

except AttributeError: 

self.issue() # issue the request 

return self._response # now return 

 

@response.setter 

def response(self, newresponse): 

try: 

assert issubclass(newresponse.__class__, responsetypes.ApiResponse) 

except (AssertionError, AttributeError): # pragma: no cover 

raise TypeError("response property has to be instance of " 

"ApiResponse or derivates.") 

self._response = newresponse 

 

######################## 

### context managers ### 

######################## 

@contextlib.contextmanager 

def connection_to_api(self): 

self.connect_to_api() 

try: 

yield 

finally: 

self.close_api_connection() 

 

############### 

### methods ### 

############### 

def connect_to_api(self): 

""" Connect to the api server 

""" 

self.logger.debug("connecting to api server...") 

self.api_connection.connect() # connect to server 

self.logger.debug("connected to api server.") 

 

def close_api_connection(self): 

""" Disconnect from the api server 

""" 

self.logger.debug("closing connection to api server...") 

self.api_connection.close() # close the connection 

self.logger.debug("connection to api server closed") 

 

def post_request(self): 

""" Issue a POST request to the api server on the given url with the 

specified payload. 

Returns: 

response (dict): JSON decoded response data 

""" 

with self.connection_to_api(): # connect to api 

self.logger.debug("issuing post request to {u} on server {s} with " 

"payload {p}".format(s=self.server, u=self.url, 

p=self.payload_urlencoded)) 

# POST request to oauth/token 

self.api_connection.request( 

method="POST", # a POST request 

url=self.url, # to this relative url 

body=self.payload_urlencoded, # with this payload 

headers=PLAIN_URLENCODED_HEADERS # and this header 

) 

 

# evaluate output 

response = self.api_connection.getresponse() # get the responsse 

data = response.read().decode() # read and decode 

data_json = json.loads(data) # load the JSON 

 

self.logger.debug("api responeded: {}".format(data_json)) 

 

return data_json # return the json data 

 

def issue(self): # pragma: no cover 

""" Issue a POST request to the api server on the given url with the 

specified payload and set the 'response' property to an ApiResponse 

object. Subclasses may override this class to use specific derivates 

of ApiResponse. 

""" 

# post the request 

res_data = self.post_request() 

# pack the response into an ApiResponse object 

response = responsetypes.ApiResponse( 

response=res_data, request=self) 

# set the response property 

self.response = response 

 

def __repr__(self): # pragma: no cover 

""" python representation of this object 

""" 

# self.logger.debug("__repr__ called") 

reprstring = ( 

"{classname}(\n" 

"server = {server},\n" 

"url = {url},\n" 

"payload = {payload},\n" 

")").format( 

classname="{module}.{name}".format( 

name=self.__class__.__name__, 

module=self.__class__.__module__), 

server=self.server.__repr__(), 

url=self.url.__repr__(), 

payload=self.payload.__repr__(), 

) 

return reprstring 

 

 

class TokenRequest(ApiRequest): 

""" base class for token requests 

""" 

 

def __init__(self, payload={}): 

""" class constructor 

Args: 

payload [Optional(dict)]: the payload 

""" 

super().__init__( 

server=NETATMO_API_SERVER, 

url=NETATMO_API_TOKEN_URL, 

payload=payload 

) 

 

def issue(self): 

""" Issue a POST request to the api server on the Oauth2 endpoint 

with the specified payload and set the 'response' property to an 

TokenResponse object. 

""" 

# post the request 

res_data = self.post_request() 

# pack the response into an ApiResponse object 

response = responsetypes.TokenResponse(response=res_data, 

request=self) 

# set the response property 

self.response = response 

 

 

class GetpublicdataRequest(ApiRequest): 

""" class for Getpublicdata requests 

""" 

 

def __init__(self, payload={}): 

""" class constructor 

Args: 

payload [Optional(dict)]: the payload 

""" 

super().__init__( 

server=NETATMO_API_SERVER, 

url=NETATMO_API_GETPUBLICDATA_URL, 

payload=payload 

) 

 

def issue(self): 

""" Issue a POST request to the api server on the Getpublicdata endpoint 

with the specified payload and set the 'response' property to an 

GetpublicdataResponse object. 

""" 

# post the request 

res_data = self.post_request() 

# pack the response into an ApiResponse object 

response = responsetypes.GetpublicdataResponse(response=res_data, 

request=self) 

# set the response property 

self.response = response 

 

 

class GetmeasureRequest(ApiRequest): 

""" class for Getmeasure requests 

""" 

 

def __init__(self, payload={}): 

""" class constructor 

Args: 

payload [Optional(dict)]: the payload 

""" 

super().__init__( 

server=NETATMO_API_SERVER, 

url=NETATMO_API_GETMEASURE_URL, 

payload=payload 

) 

 

def issue(self): 

""" Issue a POST request to the api server on the Getmeasure endpoint 

with the specified payload and set the 'response' property to an 

GetmeasureResponse object. 

""" 

# post the request 

res_data = self.post_request() 

# pack the response into an ApiResponse object 

response = responsetypes.GetmeasureResponse(response=res_data, 

request=self) 

# set the response property 

self.response = response 

 

 

class GetstationsdataRequest(ApiRequest): 

""" class for Getstationsdata requests 

""" 

 

def __init__(self, payload={}): 

""" class constructor 

Args: 

payload [Optional(dict)]: the payload 

""" 

super().__init__( 

server=NETATMO_API_SERVER, 

url=NETATMO_API_GETSTATIONSDATA_URL, 

payload=payload 

) 

 

def issue(self): 

""" Issue a POST request to the api server on the Getstationsdata 

endpoint with the specified payload and set the 'response' property to 

an GetstationsdataResponse object. 

""" 

# post the request 

res_data = self.post_request() 

# pack the response into an ApiResponse object 

response = responsetypes.GetstationsdataResponse(response=res_data, 

request=self) 

# set the response property 

self.response = response