| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright 2014 Sébastien Alix |
| 3 |
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl) |
| 4 |
"""Provides the :class:`ProxyJSON` class for JSON-RPC requests.""" |
| 5 |
import copy |
| 6 |
import json |
| 7 |
import logging |
| 8 |
import random |
| 9 |
import sys |
| 10 |
|
| 11 |
# Python 2 |
| 12 |
if sys.version_info[0] < 3: |
| 13 |
from cookielib import CookieJar |
| 14 |
from urllib2 import HTTPCookieProcessor, Request, build_opener |
| 15 |
|
| 16 |
def encode_data(data): |
| 17 |
return data |
| 18 |
|
| 19 |
def decode_data(data): |
| 20 |
return data |
| 21 |
|
| 22 |
|
| 23 |
# Python >= 3 |
| 24 |
else: |
| 25 |
import io |
| 26 |
from http.cookiejar import CookieJar |
| 27 |
from urllib.request import HTTPCookieProcessor, Request, build_opener |
| 28 |
|
| 29 |
def encode_data(data): |
| 30 |
try: |
| 31 |
return bytes(data, 'utf-8') |
| 32 |
except: # noqa: E722 |
| 33 |
return bytes(data) |
| 34 |
|
| 35 |
def decode_data(data): |
| 36 |
return io.StringIO(data.read().decode('utf-8')) |
| 37 |
|
| 38 |
|
| 39 |
LOG_HIDDEN_JSON_PARAMS = ['password'] |
| 40 |
LOG_JSON_SEND_MSG = u"(JSON,send) %(url)s %(data)s" |
| 41 |
LOG_JSON_RECV_MSG = u"(JSON,recv) %(url)s %(data)s => %(result)s" |
| 42 |
LOG_HTTP_SEND_MSG = u"(HTTP,send) %(url)s%(data)s" |
| 43 |
LOG_HTTP_RECV_MSG = u"(HTTP,recv) %(url)s%(data)s => %(result)s" |
| 44 |
|
| 45 |
logger = logging.getLogger(__name__) |
| 46 |
|
| 47 |
|
| 48 |
def get_json_log_data(data): |
| 49 |
"""Returns a new `data` dictionary with hidden params |
| 50 |
for log purpose. |
| 51 |
""" |
| 52 |
log_data = data |
| 53 |
for param in LOG_HIDDEN_JSON_PARAMS: |
| 54 |
if param in data['params']: |
| 55 |
if log_data is data: |
| 56 |
log_data = copy.deepcopy(data) |
| 57 |
log_data['params'][param] = "**********" |
| 58 |
return log_data |
| 59 |
|
| 60 |
|
| 61 |
class Proxy(object): |
| 62 |
"""Base class to implement a proxy to perform requests.""" |
| 63 |
|
| 64 |
def __init__(self, host, port, timeout=120, ssl=False, opener=None): |
| 65 |
self._root_url = "{http}{host}:{port}".format( |
| 66 |
http=(ssl and "https://" or "http://"), host=host, port=port |
| 67 |
) |
| 68 |
self._timeout = timeout |
| 69 |
self._builder = URLBuilder(self) |
| 70 |
self._opener = opener |
| 71 |
if not opener: |
| 72 |
cookie_jar = CookieJar() |
| 73 |
self._opener = build_opener(HTTPCookieProcessor(cookie_jar)) |
| 74 |
|
| 75 |
def __getattr__(self, name): |
| 76 |
return getattr(self._builder, name) |
| 77 |
|
| 78 |
def __getitem__(self, url): |
| 79 |
return self._builder[url] |
| 80 |
|
| 81 |
def _get_full_url(self, url): |
| 82 |
return '/'.join([self._root_url, url]) |
| 83 |
|
| 84 |
|
| 85 |
class ProxyJSON(Proxy): |
| 86 |
"""The :class:`ProxyJSON` class provides a dynamic access |
| 87 |
to all JSON methods. |
| 88 |
""" |
| 89 |
|
| 90 |
def __init__( |
| 91 |
self, host, port, timeout=120, ssl=False, opener=None, deserialize=True |
| 92 |
): |
| 93 |
Proxy.__init__(self, host, port, timeout, ssl, opener) |
| 94 |
self._deserialize = deserialize |
| 95 |
|
| 96 |
def __call__(self, url, params=None): |
| 97 |
if params is None: |
| 98 |
params = {} |
| 99 |
data = { |
| 100 |
"jsonrpc": "2.0", |
| 101 |
"method": "call", |
| 102 |
"params": params, |
| 103 |
"id": random.randint(0, 1000000000), |
| 104 |
} |
| 105 |
if url.startswith('/'): |
| 106 |
url = url[1:] |
| 107 |
full_url = self._get_full_url(url) |
| 108 |
log_data = get_json_log_data(data) |
| 109 |
logger.debug(LOG_JSON_SEND_MSG, {'url': full_url, 'data': log_data}) |
| 110 |
data_json = json.dumps(data) |
| 111 |
request = Request(url=full_url, data=encode_data(data_json)) |
| 112 |
request.add_header('Content-Type', 'application/json') |
| 113 |
response = self._opener.open(request, timeout=self._timeout) |
| 114 |
if not self._deserialize: |
| 115 |
return response |
| 116 |
result = json.load(decode_data(response)) |
| 117 |
logger.debug( |
| 118 |
LOG_JSON_RECV_MSG, |
| 119 |
{'url': full_url, 'data': log_data, 'result': result}, |
| 120 |
) |
| 121 |
return result |
| 122 |
|
| 123 |
|
| 124 |
class ProxyHTTP(Proxy): |
| 125 |
"""The :class:`ProxyHTTP` class provides a dynamic access |
| 126 |
to all HTTP methods. |
| 127 |
""" |
| 128 |
|
| 129 |
def __call__(self, url, data=None, headers=None): |
| 130 |
if url.startswith('/'): |
| 131 |
url = url[1:] |
| 132 |
full_url = self._get_full_url(url) |
| 133 |
logger.debug( |
| 134 |
LOG_HTTP_SEND_MSG, |
| 135 |
{'url': full_url, 'data': data and u" (%s)" % data or u""}, |
| 136 |
) |
| 137 |
kwargs = {'url': full_url} |
| 138 |
if data: |
| 139 |
kwargs['data'] = encode_data(data) |
| 140 |
request = Request(**kwargs) |
| 141 |
if headers: |
| 142 |
for hkey in headers: |
| 143 |
hvalue = headers[hkey] |
| 144 |
request.add_header(hkey, hvalue) |
| 145 |
response = self._opener.open(request, timeout=self._timeout) |
| 146 |
logger.debug( |
| 147 |
LOG_HTTP_RECV_MSG, |
| 148 |
{ |
| 149 |
'url': full_url, |
| 150 |
'data': data and u" (%s)" % data or u"", |
| 151 |
'result': response, |
| 152 |
}, |
| 153 |
) |
| 154 |
return response |
| 155 |
|
| 156 |
|
| 157 |
class URLBuilder(object): |
| 158 |
"""Auto-builds an URL while getting its attributes. |
| 159 |
Used by the :class:`ProxyJSON` and :class:`ProxyHTTP` classes. |
| 160 |
""" |
| 161 |
|
| 162 |
def __init__(self, rpc, url=None): |
| 163 |
self._rpc = rpc |
| 164 |
self._url = url |
| 165 |
|
| 166 |
def __getattr__(self, path): |
| 167 |
new_url = self._url and '/'.join([self._url, path]) or path |
| 168 |
return URLBuilder(self._rpc, new_url) |
| 169 |
|
| 170 |
def __getitem__(self, path): |
| 171 |
if path and path[0] == '/': |
| 172 |
path = path[1:] |
| 173 |
if path and path[-1] == '/': |
| 174 |
path = path[:-1] |
| 175 |
return getattr(self, path) |
| 176 |
|
| 177 |
def __call__(self, **kwargs): |
| 178 |
return self._rpc(self._url, kwargs) |
| 179 |
|
| 180 |
def __str__(self): |
| 181 |
return self._url |