1- #!/usr/bin/env python
2- # coding=utf-8
3-
41import json
52import logging
63import re
74
85import requests
96from requests .compat import urljoin
7+
108from .utils .version import get_version
119
10+
1211requests .packages .urllib3 .disable_warnings ()
1312
1413
1514def prepare_url (key ):
1615 """Replaces capital letters to lower one with dash prefix."""
1716 char_elem = key .group (0 )
1817 if char_elem .isupper ():
19- return '-' + char_elem .lower ()
18+ return "-" + char_elem .lower ()
19+ return ""
2020
2121
22- class Config ( object ) :
23- DEFAULT_API_URL = ' https://api.mailjet.com/'
24- API_REF = ' http://dev.mailjet.com/email-api/v3/'
25- version = 'v3'
26- user_agent = ' mailjet-apiv3-python/v' + get_version ()
22+ class Config :
23+ DEFAULT_API_URL = " https://api.mailjet.com/"
24+ API_REF = " http://dev.mailjet.com/email-api/v3/"
25+ version = "v3"
26+ user_agent = " mailjet-apiv3-python/v" + get_version ()
2727
2828 def __init__ (self , version = None , api_url = None ):
2929 if version is not None :
@@ -33,110 +33,188 @@ def __init__(self, version=None, api_url=None):
3333 def __getitem__ (self , key ):
3434 # Append version to URL.
3535 # Forward slash is ignored if present in self.version.
36- url = urljoin (self .api_url , self .version + '/' )
37- headers = {' Content-type' : ' application/json' , ' User-agent' : self .user_agent }
38- if key .lower () == ' contactslist_csvdata' :
39- url = urljoin (url , ' DATA/' )
40- headers [' Content-type' ] = ' text/plain'
41- elif key .lower () == ' batchjob_csverror' :
42- url = urljoin (url , ' DATA/' )
43- headers [' Content-type' ] = ' text/csv'
44- elif key .lower () != ' send' and self .version != 'v4' :
45- url = urljoin (url , ' REST/' )
46- url = url + key .split ('_' )[0 ].lower ()
36+ url = urljoin (self .api_url , self .version + "/" )
37+ headers = {" Content-type" : " application/json" , " User-agent" : self .user_agent }
38+ if key .lower () == " contactslist_csvdata" :
39+ url = urljoin (url , " DATA/" )
40+ headers [" Content-type" ] = " text/plain"
41+ elif key .lower () == " batchjob_csverror" :
42+ url = urljoin (url , " DATA/" )
43+ headers [" Content-type" ] = " text/csv"
44+ elif key .lower () != " send" and self .version != "v4" :
45+ url = urljoin (url , " REST/" )
46+ url += key .split ("_" )[0 ].lower ()
4747 return url , headers
4848
4949
50- class Endpoint (object ):
51-
50+ class Endpoint :
5251 def __init__ (self , url , headers , auth , action = None ):
5352 self ._url , self .headers , self ._auth , self .action = url , headers , auth , action
5453
55- def __doc__ (self ):
56- return self ._doc
57-
5854 def _get (self , filters = None , action_id = None , id = None , ** kwargs ):
59- return api_call (self ._auth , 'get' , self ._url , headers = self .headers , action = self .action , action_id = action_id , filters = filters , resource_id = id , ** kwargs )
55+ return api_call (
56+ self ._auth ,
57+ "get" ,
58+ self ._url ,
59+ headers = self .headers ,
60+ action = self .action ,
61+ action_id = action_id ,
62+ filters = filters ,
63+ resource_id = id ,
64+ ** kwargs ,
65+ )
6066
6167 def get_many (self , filters = None , action_id = None , ** kwargs ):
62- return self ._get (filters = filters , action_id = action_id ** kwargs )
68+ return self ._get (filters = filters , action_id = action_id , ** kwargs )
6369
6470 def get (self , id = None , filters = None , action_id = None , ** kwargs ):
6571 return self ._get (id = id , filters = filters , action_id = action_id , ** kwargs )
6672
67- def create (self , data = None , filters = None , id = None , action_id = None , ensure_ascii = True , data_encoding = "utf-8" , ** kwargs ):
68- if self .headers ['Content-type' ] == 'application/json' :
73+ def create (
74+ self ,
75+ data = None ,
76+ filters = None ,
77+ id = None ,
78+ action_id = None ,
79+ ensure_ascii = True ,
80+ data_encoding = "utf-8" ,
81+ ** kwargs ,
82+ ):
83+ if self .headers ["Content-type" ] == "application/json" :
6984 if ensure_ascii :
7085 data = json .dumps (data )
7186 else :
7287 data = json .dumps (data , ensure_ascii = False ).encode (data_encoding )
73- 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 )
74-
75- def update (self , id , data , filters = None , action_id = None , ensure_ascii = True , data_encoding = "utf-8" , ** kwargs ):
76- if self .headers ['Content-type' ] == 'application/json' :
88+ return api_call (
89+ self ._auth ,
90+ "post" ,
91+ self ._url ,
92+ headers = self .headers ,
93+ resource_id = id ,
94+ data = data ,
95+ action = self .action ,
96+ action_id = action_id ,
97+ filters = filters ,
98+ ** kwargs ,
99+ )
100+
101+ def update (
102+ self ,
103+ id ,
104+ data ,
105+ filters = None ,
106+ action_id = None ,
107+ ensure_ascii = True ,
108+ data_encoding = "utf-8" ,
109+ ** kwargs ,
110+ ):
111+ if self .headers ["Content-type" ] == "application/json" :
77112 if ensure_ascii :
78113 data = json .dumps (data )
79114 else :
80115 data = json .dumps (data , ensure_ascii = False ).encode (data_encoding )
81- 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 )
116+ return api_call (
117+ self ._auth ,
118+ "put" ,
119+ self ._url ,
120+ resource_id = id ,
121+ headers = self .headers ,
122+ data = data ,
123+ action = self .action ,
124+ action_id = action_id ,
125+ filters = filters ,
126+ ** kwargs ,
127+ )
82128
83129 def delete (self , id , ** kwargs ):
84- return api_call (self ._auth , 'delete' , self ._url , action = self .action , headers = self .headers , resource_id = id , ** kwargs )
85-
86-
87- class Client (object ):
88-
130+ return api_call (
131+ self ._auth ,
132+ "delete" ,
133+ self ._url ,
134+ action = self .action ,
135+ headers = self .headers ,
136+ resource_id = id ,
137+ ** kwargs ,
138+ )
139+
140+
141+ class Client :
89142 def __init__ (self , auth = None , ** kwargs ):
90143 self .auth = auth
91- version = kwargs .get (' version' , None )
92- api_url = kwargs .get (' api_url' , None )
144+ version = kwargs .get (" version" )
145+ api_url = kwargs .get (" api_url" )
93146 self .config = Config (version = version , api_url = api_url )
94147
95148 def __getattr__ (self , name ):
96149 name = re .sub (r"[A-Z]" , prepare_url , name )
97- split = name .split ('_' )
98- #identify the resource
150+ split = name .split ("_" )
151+ # identify the resource
99152 fname = split [0 ]
100153 action = None
101- if ( len (split ) > 1 ) :
102- #identify the sub resource (action)
154+ if len (split ) > 1 :
155+ # identify the sub resource (action)
103156 action = split [1 ]
104- if action == ' csvdata' :
105- action = ' csvdata/text:plain'
106- if action == ' csverror' :
107- action = ' csverror/text:csv'
157+ if action == " csvdata" :
158+ action = " csvdata/text:plain"
159+ if action == " csverror" :
160+ action = " csverror/text:csv"
108161 url , headers = self .config [name ]
109- return type (fname , (Endpoint ,), {})(url = url , headers = headers , action = action , auth = self .auth )
110-
111-
112- def api_call (auth , method , url , headers , data = None , filters = None , resource_id = None ,
113- timeout = 60 , debug = False , action = None , action_id = None , ** kwargs ):
114- url = build_url (url , method = method , action = action , resource_id = resource_id , action_id = action_id )
162+ return type (fname , (Endpoint ,), {})(
163+ url = url , headers = headers , action = action , auth = self .auth
164+ )
165+
166+
167+ def api_call (
168+ auth ,
169+ method ,
170+ url ,
171+ headers ,
172+ data = None ,
173+ filters = None ,
174+ resource_id = None ,
175+ timeout = 60 ,
176+ debug = False ,
177+ action = None ,
178+ action_id = None ,
179+ ** kwargs ,
180+ ):
181+ url = build_url (
182+ url , method = method , action = action , resource_id = resource_id , action_id = action_id
183+ )
115184 req_method = getattr (requests , method )
116185
117186 try :
118187 filters_str = None
119188 if filters :
120189 filters_str = "&" .join ("%s=%s" % (k , v ) for k , v in filters .items ())
121- response = req_method (url , data = data , params = filters_str , headers = headers , auth = auth ,
122- timeout = timeout , verify = True , stream = False )
123- return response
190+ response = req_method (
191+ url ,
192+ data = data ,
193+ params = filters_str ,
194+ headers = headers ,
195+ auth = auth ,
196+ timeout = timeout ,
197+ verify = True ,
198+ stream = False ,
199+ )
124200
125201 except requests .exceptions .Timeout :
126202 raise TimeoutError
127203 except requests .RequestException as e :
128204 raise ApiError (e )
129- except Exception as e :
205+ except Exception :
130206 raise
207+ else :
208+ return response
131209
132210
133211def build_headers (resource , action = None , extra_headers = None ):
134- headers = {' Content-type' : ' application/json' }
212+ headers = {" Content-type" : " application/json" }
135213
136- if resource .lower () == ' contactslist' and action .lower () == ' csvdata' :
137- headers = {' Content-type' : ' text/plain' }
138- elif resource .lower () == ' batchjob' and action .lower () == ' csverror' :
139- headers = {' Content-type' : ' text/csv' }
214+ if resource .lower () == " contactslist" and action .lower () == " csvdata" :
215+ headers = {" Content-type" : " text/plain" }
216+ elif resource .lower () == " batchjob" and action .lower () == " csverror" :
217+ headers = {" Content-type" : " text/csv" }
140218
141219 if extra_headers :
142220 headers .update (extra_headers )
@@ -146,25 +224,25 @@ def build_headers(resource, action=None, extra_headers=None):
146224
147225def build_url (url , method , action = None , resource_id = None , action_id = None ):
148226 if action :
149- url += '/%s' % action
227+ url += f"/ { action } "
150228 if action_id :
151- url += '/{}' . format ( action_id )
229+ url += f"/ { action_id } "
152230 if resource_id :
153- url += '/%s' % str ( resource_id )
231+ url += f"/ { resource_id } "
154232 return url
155233
156234
157235def parse_response (response , debug = False ):
158236 data = response .json ()
159237
160238 if debug :
161- logging .debug (' REQUEST: %s' % response .request .url )
162- logging .debug (' REQUEST_HEADERS: %s' % response .request .headers )
163- logging .debug (' REQUEST_CONTENT: %s' % response .request .body )
239+ logging .debug (" REQUEST: %s" , response .request .url )
240+ logging .debug (" REQUEST_HEADERS: %s" , response .request .headers )
241+ logging .debug (" REQUEST_CONTENT: %s" , response .request .body )
164242
165- logging .debug (' RESPONSE: %s' % response .content )
166- logging .debug (' RESP_HEADERS: %s' % response .headers )
167- logging .debug (' RESP_CODE: %s' % response .status_code )
243+ logging .debug (" RESPONSE: %s" , response .content )
244+ logging .debug (" RESP_HEADERS: %s" , response .headers )
245+ logging .debug (" RESP_CODE: %s" , response .status_code )
168246
169247 return data
170248
0 commit comments