|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding=utf-8 |
| 3 | + |
| 4 | +import json |
| 5 | +import logging |
| 6 | + |
| 7 | +import requests |
| 8 | +from requests.compat import urljoin |
| 9 | +from .utils.version import get_version |
| 10 | + |
| 11 | +requests.packages.urllib3.disable_warnings() |
| 12 | + |
| 13 | + |
| 14 | +class Config(object): |
| 15 | + API_URL = 'https://api.mailjet.com/' |
| 16 | + API_REF = 'http://dev.mailjet.com/email-api/v3/' |
| 17 | + version = 'v3' |
| 18 | + user_agent = 'mailjet-apiv3-python/v' + get_version() |
| 19 | + |
| 20 | + def __init__(self, version=None): |
| 21 | + if version is not None: |
| 22 | + self.version = version |
| 23 | + |
| 24 | + def __getitem__(self, key): |
| 25 | + url = self.API_URL[0:] |
| 26 | + # Append version to URL. |
| 27 | + # Forward slash is ignored if present in self.version. |
| 28 | + url = urljoin(url, self.version + '/') |
| 29 | + headers = {'Content-type': 'application/json', 'User-agent': self.user_agent} |
| 30 | + if key.lower() == 'contactslist_csvdata': |
| 31 | + url = urljoin(url, 'DATA/') |
| 32 | + headers['Content-type'] = 'text/plain' |
| 33 | + elif key.lower() == 'batchjob_csverror': |
| 34 | + url = urljoin(url, 'DATA/') |
| 35 | + headers['Content-type'] = 'text/csv' |
| 36 | + elif key.lower() != 'send': |
| 37 | + url = urljoin(url, 'REST/') |
| 38 | + url = url + key.split('_')[0].lower() |
| 39 | + return url, headers |
| 40 | + |
| 41 | + |
| 42 | +class Endpoint(object): |
| 43 | + |
| 44 | + def __init__(self, url, headers, auth, action=None): |
| 45 | + self._url, self.headers, self._auth, self.action = url, headers, auth, action |
| 46 | + |
| 47 | + def __doc__(self): |
| 48 | + return self._doc |
| 49 | + |
| 50 | + def _get(self, filters=None, action_id=None, id=None, **kwargs): |
| 51 | + return api_call(self._auth, 'get', self._url, headers=self.headers, action=self.action, action_id=action_id, filters=filters, resource_id=id, **kwargs) |
| 52 | + |
| 53 | + def get_many(self, filters=None, action_id=None, **kwargs): |
| 54 | + return self._get(filters=filters, **kwargs) |
| 55 | + |
| 56 | + def get(self, id=None, filters=None, action_id=None, **kwargs): |
| 57 | + return self._get(id=id, filters=filters, **kwargs) |
| 58 | + |
| 59 | + def create(self, data=None, filters=None, id=None, action_id=None, **kwargs): |
| 60 | + if self.headers['Content-type'] == 'application/json': |
| 61 | + data = json.dumps(data) |
| 62 | + return api_call(self._auth, 'post', self._url, headers=self.headers, resource_id=id, data=data, action=self.action, action_id=action_id, filters=filters, **kwargs) |
| 63 | + |
| 64 | + def update(self, id, data, filters=None, action_id=None, **kwargs): |
| 65 | + if self.headers['Content-type'] == 'application/json': |
| 66 | + data = json.dumps(data) |
| 67 | + return api_call(self._auth, 'put', self._url, resource_id=id, headers=self.headers, data=data, action=self.action, action_id=action_id, filters=filters, **kwargs) |
| 68 | + |
| 69 | + def delete(self, id, **kwargs): |
| 70 | + return api_call(self._auth, 'delete', self._url, action=self.action, headers=self.headers, resource_id=id, **kwargs) |
| 71 | + |
| 72 | + |
| 73 | +class Client(object): |
| 74 | + |
| 75 | + def __init__(self, auth=None, **kwargs): |
| 76 | + self.auth = auth |
| 77 | + version = kwargs.get('version', None) |
| 78 | + self.config = Config(version=version) |
| 79 | + |
| 80 | + def __getattr__(self, name): |
| 81 | + split = name.split('_') |
| 82 | + fname = split[0] |
| 83 | + action = None |
| 84 | + if (len(split) > 1): |
| 85 | + action = split[1] |
| 86 | + if action == 'csvdata': |
| 87 | + action = 'csvdata/text:plain' |
| 88 | + if action == 'csverror': |
| 89 | + action = 'csverror/text:csv' |
| 90 | + url, headers = self.config[name] |
| 91 | + return type(fname, (Endpoint,), {})(url=url, headers=headers, action=action, auth=self.auth) |
| 92 | + |
| 93 | + |
| 94 | +def api_call(auth, method, url, headers, data=None, filters=None, resource_id=None, |
| 95 | + timeout=60, debug=False, action=None, action_id=None, **kwargs): |
| 96 | + url = build_url(url, method=method, action=action, resource_id=resource_id, action_id=action_id) |
| 97 | + req_method = getattr(requests, method) |
| 98 | + |
| 99 | + try: |
| 100 | + response = req_method(url, data=data, params=filters, headers=headers, auth=auth, |
| 101 | + timeout=timeout, verify=True, stream=False) |
| 102 | + return response |
| 103 | + |
| 104 | + except requests.exceptions.Timeout: |
| 105 | + raise TimeoutError |
| 106 | + except requests.RequestException as e: |
| 107 | + raise ApiError(e) |
| 108 | + except Exception as e: |
| 109 | + raise |
| 110 | + |
| 111 | + |
| 112 | +def build_headers(resource, action=None, extra_headers=None): |
| 113 | + headers = {'Content-type': 'application/json'} |
| 114 | + |
| 115 | + if resource.lower() == 'contactslist' and action.lower() == 'csvdata': |
| 116 | + headers = {'Content-type': 'text/plain'} |
| 117 | + elif resource.lower() == 'batchjob' and action.lower() == 'csverror': |
| 118 | + headers = {'Content-type': 'text/csv'} |
| 119 | + |
| 120 | + if extra_headers: |
| 121 | + headers.update(extra_headers) |
| 122 | + |
| 123 | + return headers |
| 124 | + |
| 125 | + |
| 126 | +def build_url(url, method, action=None, resource_id=None, action_id=None): |
| 127 | + if resource_id: |
| 128 | + url += '/%s' % str(resource_id) |
| 129 | + if action: |
| 130 | + url += '/%s' % action |
| 131 | + if action_id: |
| 132 | + url += '/%d' % action_id |
| 133 | + |
| 134 | + return url |
| 135 | + |
| 136 | + |
| 137 | +def parse_response(response, debug=False): |
| 138 | + data = response.json() |
| 139 | + |
| 140 | + if debug: |
| 141 | + logging.debug('REQUEST: %s' % response.request.url) |
| 142 | + logging.debug('REQUEST_HEADERS: %s' % response.request.headers) |
| 143 | + logging.debug('REQUEST_CONTENT: %s' % response.request.body) |
| 144 | + |
| 145 | + logging.debug('RESPONSE: %s' % response.content) |
| 146 | + logging.debug('RESP_HEADERS: %s' % response.headers) |
| 147 | + logging.debug('RESP_CODE: %s' % response.status_code) |
| 148 | + |
| 149 | + return data |
| 150 | + |
| 151 | + |
| 152 | +class ApiError(Exception): |
| 153 | + pass |
| 154 | + |
| 155 | + |
| 156 | +class AuthorizationError(ApiError): |
| 157 | + pass |
| 158 | + |
| 159 | + |
| 160 | +class ActionDeniedError(ApiError): |
| 161 | + pass |
| 162 | + |
| 163 | + |
| 164 | +class CriticalApiError(ApiError): |
| 165 | + pass |
| 166 | + |
| 167 | + |
| 168 | +class ApiRateLimitError(ApiError): |
| 169 | + pass |
| 170 | + |
| 171 | + |
| 172 | +class TimeoutError(ApiError): |
| 173 | + pass |
| 174 | + |
| 175 | + |
| 176 | +class DoesNotExistError(ApiError): |
| 177 | + pass |
| 178 | + |
| 179 | + |
| 180 | +class ValidationError(ApiError): |
| 181 | + pass |
0 commit comments