|
| 1 | +import json |
| 2 | +import urllib |
| 3 | + |
| 4 | +from requests import request, Session |
| 5 | +from requests.exceptions import RequestException |
| 6 | +from multidimensional_urlencode import urlencode |
| 7 | + |
| 8 | +from .process import Process |
| 9 | +from .exceptions import ( |
| 10 | + APIError, HTTPError, BadRequest, ConversionFailed, TemporaryUnavailable, InvalidResponse, InvalidParameterException |
| 11 | +) |
| 12 | + |
| 13 | +class Api(object): |
| 14 | + """ |
| 15 | + Base CloudConvert API Wrapper for Python |
| 16 | + """ |
| 17 | + |
| 18 | + endpoint = "api.cloudconvert.com" |
| 19 | + protocol = "https" |
| 20 | + |
| 21 | + def __init__(self, api_key=None): |
| 22 | + """ |
| 23 | + Creates a new API Client. No credential check is done at this point. |
| 24 | +
|
| 25 | + :param str api_key: API key as provided by CloudConvert (https://cloudconvert.com/user/profile) |
| 26 | + """ |
| 27 | + |
| 28 | + self._api_key = api_key |
| 29 | + |
| 30 | + # use a requests session to reuse HTTPS connections between requests |
| 31 | + self._session = Session() |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | + def get(self, path, parameters=None, is_authenticated=False): |
| 37 | + """ |
| 38 | + 'GET' :py:func:`Client.call` wrapper. |
| 39 | + Query string parameters can be set either directly in ``_target`` or as |
| 40 | + keywork arguments. |
| 41 | + :param string path: API method to call |
| 42 | + :param string is_authenticated: If True, send authentication headers. This is |
| 43 | + the default |
| 44 | + """ |
| 45 | + if parameters: |
| 46 | + query_string = urlencode(parameters) |
| 47 | + if '?' in path: |
| 48 | + path = '%s&%s' % (path, query_string) |
| 49 | + else: |
| 50 | + path = '%s?%s' % (path, query_string) |
| 51 | + return self.rawCall('GET', path, None, is_authenticated) |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + def post(self, path, parameters=None, is_authenticated=False): |
| 56 | + """ |
| 57 | + 'POST' :py:func:`Client.call` wrapper |
| 58 | + Body parameters can be set either directly in ``_target`` or as keywork |
| 59 | + arguments. |
| 60 | + :param string path: API method to call |
| 61 | + :param string is_authenticated: If True, send authentication headers. This is |
| 62 | + the default |
| 63 | + """ |
| 64 | + return self.rawCall('POST', path, parameters, is_authenticated) |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | + def delete(self, path, is_authenticated=False): |
| 69 | + """ |
| 70 | + 'DELETE' :py:func:`Client.call` wrapper |
| 71 | + :param string path: API method to call |
| 72 | + :param string is_authenticated: If True, send authentication headers. This is |
| 73 | + the default |
| 74 | + """ |
| 75 | + return self.rawCall('DELETE', path, None, is_authenticated) |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + def rawCall(self, method, path, content=None, is_authenticated=False, stream=False): |
| 80 | + """ |
| 81 | + Low level call helper for making HTTP requests. |
| 82 | + :param str method: HTTP method of request (GET,POST,PUT,DELETE) |
| 83 | + :param str path: relative url of API request |
| 84 | + :param content: body of the request (query parameters for GET requests or body for POST requests) |
| 85 | + :param boolean is_authenticated: if the request use authentication |
| 86 | + :raises HTTPError: when underlying request failed for network reason |
| 87 | + :raises InvalidResponse: when API response could not be decoded |
| 88 | + """ |
| 89 | + |
| 90 | + url = path |
| 91 | + if path.startswith("//"): |
| 92 | + url = self.protocol + ":" + path |
| 93 | + elif not path.startswith("http"): |
| 94 | + url = self.protocol + "://" + self.endpoint + path |
| 95 | + |
| 96 | + |
| 97 | + body = None |
| 98 | + files = None |
| 99 | + headers = {} |
| 100 | + |
| 101 | + # include payload |
| 102 | + if content is not None: |
| 103 | + |
| 104 | + ## check if we upload anything |
| 105 | + isupload = False |
| 106 | + for key, value in content.items(): |
| 107 | + if isinstance(value, file): |
| 108 | + ## if it is file: remove from content dict and add it to files dict |
| 109 | + isupload = True |
| 110 | + files = {key: value} |
| 111 | + del content[key] |
| 112 | + break |
| 113 | + |
| 114 | + if isupload: |
| 115 | + url += "?" + urllib.unquote(urlencode(content)) |
| 116 | + else: |
| 117 | + headers['Content-type'] = 'application/json' |
| 118 | + body = json.dumps(content) |
| 119 | + |
| 120 | + |
| 121 | + # add auth header |
| 122 | + if is_authenticated and self._api_key is not None: |
| 123 | + headers['Authorization'] = 'Bearer ' + self._api_key |
| 124 | + |
| 125 | + # attempt request |
| 126 | + try: |
| 127 | + result = self._session.request(method, url, headers=headers, |
| 128 | + data=body, files=files, stream=stream) |
| 129 | + except RequestException as error: |
| 130 | + raise HTTPError("HTTP request failed error", error) |
| 131 | + |
| 132 | + code = result.status_code |
| 133 | + |
| 134 | + |
| 135 | + # attempt to decode and return the response |
| 136 | + |
| 137 | + if not stream: |
| 138 | + try: |
| 139 | + json_result = result.json() |
| 140 | + except ValueError as error: |
| 141 | + raise InvalidResponse("Failed to decode API response", error) |
| 142 | + |
| 143 | + |
| 144 | + # error check |
| 145 | + if code >= 100 and code < 300: |
| 146 | + if stream: |
| 147 | + return result |
| 148 | + else: |
| 149 | + return json_result |
| 150 | + else: |
| 151 | + msg = json_result.get('message') if json_result.get('message') else json_result.get('error') |
| 152 | + if code == 400: |
| 153 | + raise BadRequest(msg) |
| 154 | + elif code == 422: |
| 155 | + raise ConversionFailed(msg) |
| 156 | + elif code == 503: |
| 157 | + raise TemporaryUnavailable(msg) |
| 158 | + else: |
| 159 | + raise APIError(msg) |
| 160 | + |
| 161 | + |
| 162 | + |
| 163 | + def createProcess(self, parameters): |
| 164 | + """ |
| 165 | + Create a new Process |
| 166 | + :param parameters: Parameters for creating the Process. See https://cloudconvert.com/apidoc#create |
| 167 | + :raises APIError: if the CloudConvert API returns an error |
| 168 | + """ |
| 169 | + result = self.post("/process", parameters, True) |
| 170 | + return Process(self, result['url']) |
| 171 | + |
| 172 | + |
| 173 | + def convert(self, parameters): |
| 174 | + """ |
| 175 | + Shortcut: Create a new Process and starts it |
| 176 | + :param parameters: Parameters for starting the Process. See https://cloudconvert.com/apidoc#start |
| 177 | + :raises APIError: if the CloudConvert API returns an error |
| 178 | + """ |
| 179 | + |
| 180 | + startparameters=parameters.copy() |
| 181 | + ## we don't need the input file for creating the process |
| 182 | + del startparameters['file'] |
| 183 | + process = self.createProcess(startparameters) |
| 184 | + return process.start(parameters) |
0 commit comments