|
20 | 20 | from urllib.request import Request |
21 | 21 | from urllib.request import urlopen |
22 | 22 | from urllib.error import HTTPError |
| 23 | + from urllib.parse import urlunsplit |
23 | 24 |
|
24 | | - def request(url, method, headers, data=None): |
| 25 | + def request(url, method, headers, data=None, timeout=None): |
25 | 26 | ''' Make an HTTP request in Python 3.x |
26 | 27 |
|
27 | 28 | This method will abstract the underlying organization and invocation of |
@@ -50,21 +51,20 @@ def request(url, method, headers, data=None): |
50 | 51 | if data: |
51 | 52 | request.add_header('Content-Type', 'application/json') |
52 | 53 |
|
53 | | - response = urlopen(request).read().decode('utf8') |
| 54 | + response = urlopen(request, timeout=timeout).read().decode('utf8') |
54 | 55 |
|
55 | 56 | try: |
56 | 57 | return json.loads(response) |
57 | 58 | except ValueError: |
58 | 59 | raise ButtonClientError('Invalid response: {0}'.format(response)) |
59 | 60 |
|
60 | | - __all__ = [Request, urlopen, HTTPError, request] |
61 | | - |
62 | 61 | else: |
63 | 62 | from urllib2 import Request |
64 | 63 | from urllib2 import urlopen |
65 | 64 | from urllib2 import HTTPError |
| 65 | + from urlparse import urlunsplit |
66 | 66 |
|
67 | | - def request(url, method, headers, data=None): |
| 67 | + def request(url, method, headers, data=None, timeout=None): |
68 | 68 | ''' Make an HTTP request in Python 2.x |
69 | 69 |
|
70 | 70 | This method will abstract the underlying organization and invocation of |
@@ -96,11 +96,30 @@ def request(url, method, headers, data=None): |
96 | 96 | request.add_header('Content-Type', 'application/json') |
97 | 97 | request.add_data(json.dumps(data)) |
98 | 98 |
|
99 | | - response = urlopen(request).read() |
| 99 | + response = urlopen(request, timeout=timeout).read() |
100 | 100 |
|
101 | 101 | try: |
102 | 102 | return json.loads(response) |
103 | 103 | except ValueError: |
104 | 104 | raise ButtonClientError('Invalid response: {0}'.format(response)) |
105 | 105 |
|
106 | | - __all__ = [Request, urlopen, HTTPError, request] |
| 106 | + |
| 107 | +def request_url(secure, hostname, port, path): |
| 108 | + ''' |
| 109 | + Combines url components into a url passable into the request function. |
| 110 | +
|
| 111 | + Args: |
| 112 | + secure (boolean): Whether or not to use HTTPS. |
| 113 | + hostname (str): The host name for the url. |
| 114 | + port (int): The port number, as an integer. |
| 115 | + path (str): The hierarchical path. |
| 116 | +
|
| 117 | + Returns: |
| 118 | + (str) A complete url made up of the arguments. |
| 119 | + ''' |
| 120 | + scheme = 'https' if secure else 'http' |
| 121 | + netloc = '{0}:{1}'.format(hostname, port) |
| 122 | + |
| 123 | + return urlunsplit((scheme, netloc, path, '', '')) |
| 124 | + |
| 125 | +__all__ = [Request, urlopen, HTTPError, request, request_url] |
0 commit comments