1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
# |
3
|
|
|
# Copyright (c) 2016 dotzero <[email protected]> |
4
|
|
|
# |
5
|
|
|
# Permission is hereby granted, free of charge, to any person obtaining a copy |
6
|
|
|
# of this software and associated documentation files (the "Software"), to deal |
7
|
|
|
# in the Software without restriction, including without limitation the rights |
8
|
|
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
9
|
|
|
# copies of the Software, and to permit persons to whom the Software is |
10
|
|
|
# furnished to do so, subject to the following conditions: |
11
|
|
|
# |
12
|
|
|
# The above copyright notice and this permission notice shall be included |
13
|
|
|
# in all copies or substantial portions of the Software. |
14
|
|
|
# |
15
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
16
|
|
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
17
|
|
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
18
|
|
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
19
|
|
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
20
|
|
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
21
|
|
|
# SOFTWARE. |
22
|
1 |
|
"""This module contains a object that represents a BaseResource.""" |
23
|
|
|
|
24
|
1 |
|
import sys |
25
|
1 |
|
import json |
26
|
1 |
|
import logging |
27
|
1 |
|
from habrahabr.errors import ApiHandlerError |
28
|
|
|
|
29
|
1 |
|
try: |
30
|
|
|
# python3 |
31
|
1 |
|
from urllib.request import build_opener, Request, HTTPHandler |
32
|
|
|
from urllib.error import HTTPError |
33
|
|
|
from urllib.parse import urlencode |
34
|
|
|
except ImportError: # pragma: no cover |
35
|
|
|
# python2 |
36
|
|
|
from urllib2 import build_opener, Request, HTTPHandler, HTTPError |
37
|
|
|
from urllib import urlencode |
38
|
|
|
|
39
|
1 |
|
log = logging.getLogger(__name__) |
40
|
|
|
|
41
|
1 |
|
POST_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8' |
42
|
|
|
|
43
|
|
|
|
44
|
1 |
|
class BaseResource(object): |
45
|
|
|
"""Базовый ресурс.""" |
46
|
|
|
|
47
|
1 |
|
def __init__(self, auth=None): |
48
|
|
|
"""Конструктор BaseResource. |
49
|
|
|
|
50
|
|
|
:param auth: Экземпляр класса Auth. |
51
|
|
|
:rtype: object |
52
|
|
|
""" |
53
|
1 |
|
if auth is None: |
54
|
|
|
raise ApiHandlerError('Auth handler is not defined') |
55
|
|
|
|
56
|
1 |
|
self._auth = auth |
57
|
|
|
|
58
|
1 |
|
def _request(self, url, method='GET', data=None): |
59
|
1 |
|
url = self._auth.endpoint + url |
60
|
1 |
|
headers = self._auth.headers |
61
|
|
|
|
62
|
1 |
|
if data is not None: |
63
|
1 |
|
data = urlencode(data) |
64
|
1 |
|
if method in ['GET', 'DELETE']: |
65
|
1 |
|
url = url + '?' + data |
66
|
1 |
|
data = None |
67
|
|
|
else: |
68
|
1 |
|
headers.update({'Content-Type': POST_CONTENT_TYPE}) |
69
|
1 |
|
if sys.version_info > (3,): # python3 |
70
|
|
|
data = data.encode('utf-8') |
71
|
|
|
|
72
|
1 |
|
log.debug(method + ' ' + url) |
73
|
1 |
|
log.debug(data) |
74
|
|
|
|
75
|
1 |
|
try: |
76
|
1 |
|
opener = build_opener(HTTPHandler) |
77
|
1 |
|
request = Request(url, data=data, headers=headers) |
78
|
1 |
|
request.get_method = lambda: method |
79
|
1 |
|
response = opener.open(request).read() |
80
|
1 |
|
data = self._parse_response(response) |
81
|
|
|
except HTTPError as e: |
82
|
|
|
log.error(e) |
83
|
|
|
data = self._parse_response(e.read()) |
84
|
|
|
raise ApiHandlerError('Invalid server response', data) |
85
|
|
|
except ValueError as e: |
86
|
|
|
log.error(e) |
87
|
|
|
raise ApiHandlerError('Invalid server response') |
88
|
|
|
|
89
|
1 |
|
return data |
90
|
|
|
|
91
|
1 |
|
@staticmethod |
92
|
|
|
def _parse_response(response): |
93
|
1 |
|
try: |
94
|
1 |
|
return json.loads(response.decode('utf-8')) |
95
|
|
|
except ValueError: |
96
|
|
|
return False |
97
|
|
|
|