-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.py
86 lines (72 loc) · 2.73 KB
/
connection.py
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
# This file is part of krakenex.
#
# krakenex is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# krakenex is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser
# General Public LICENSE along with krakenex. If not, see
# <http://www.gnu.org/licenses/lgpl-3.0.txt>.
"""Connection handling."""
import http.client
import urllib.request
import urllib.parse
import urllib.error
import version
class Connection(object):
""" Object representing a single connection.
Opens a reusable HTTPS connection. Allows specifying HTTPS timeout,
or server URI (for testing purposes).
"""
def __init__(self, uri='api.kraken.com', timeout=30):
""" Create an object for reusable connections.
:param uri: URI to connect to
:type uri: str
:param timeout: blocking operations' timeout (in seconds)
:type timeout: int
:returns: None
"""
self.headers = {
'User-Agent': 'krakenex/' + version.__version__ +
' (+' + version.__url__ + ')'
}
self.conn = http.client.HTTPSConnection(uri, timeout=timeout)
return
def close(self):
""" Close this connection.
:returns: None
"""
self.conn.close()
return
def _request(self, url, req=None, headers=None):
""" Send POST request to API server using this connection.
If not provided, sets empty request parameters and HTTPS
headers for this request.
:param url: fully-qualified URL with all necessary urlencoded
information
:type url: str
:param req: (optional) API request parameters
:type req: dict
:param headers: (optional) HTTPS headers, such as API-Key and API-Sign
:type headers: dict
:returns: :py:mod:`http.client`-decoded response
:raises: :py:exc:`http.client.HTTPException`: if response status not
successful
"""
if req is None:
req = {}
if headers is None:
headers = {}
data = urllib.parse.urlencode(req)
headers.update(self.headers)
self.conn.request('POST', url, data, headers)
response = self.conn.getresponse()
if response.status not in (200, 201, 202):
raise http.client.HTTPException(response.status)
return response.read().decode()