11import datetime
22import json
33import platform
4- import time
54import uuid
65from enum import Enum
76from json import JSONDecodeError
87from typing import (
98 Any ,
109 Optional ,
1110 Tuple ,
12- Union ,
1311)
14- from urllib .parse import urlencode
1512
1613import requests
1714
1815from easypost .constant import (
1916 API_VERSION ,
2017 COMMUNICATION_ERROR ,
21- INVALID_REQUEST_LIB_ERROR ,
2218 INVALID_REQUEST_METHOD_ERROR ,
2319 INVALID_REQUEST_PARAMETERS_ERROR ,
2420 INVALID_RESPONSE_BODY_ERROR ,
@@ -212,16 +208,9 @@ def request_raw(
212208 request_uuid = request_uuid ,
213209 )
214210
215- if self ._client ._request_lib == "urlfetch" :
216- http_body , http_status , http_headers = self .urlfetch_request (
217- method = method , abs_url = abs_url , headers = headers , params = params
218- )
219- elif self ._client ._request_lib == "requests" :
220- http_body , http_status , http_headers = self .requests_request (
221- method = method , abs_url = abs_url , headers = headers , params = params
222- )
223- else :
224- raise EasyPostError (INVALID_REQUEST_LIB_ERROR .format (self ._client ._request_lib , SUPPORT_EMAIL ))
211+ http_body , http_status , http_headers = self .requests_request (
212+ method = method , abs_url = abs_url , headers = headers , params = params
213+ )
225214
226215 response_timestamp = datetime .datetime .now (datetime .timezone .utc )
227216 self ._client ._response_hook (
@@ -293,40 +282,6 @@ def requests_request(
293282
294283 return http_body , http_status , http_headers
295284
296- def urlfetch_request (
297- self ,
298- method : RequestMethod ,
299- abs_url : str ,
300- headers : dict [str , Any ],
301- params : dict [str , Any ],
302- ) -> Tuple [str , int , dict [str , Any ]]:
303- """Make a request by using the `urlfetch` library."""
304- fetch_args = {
305- "method" : method .value ,
306- "headers" : headers ,
307- "validate_certificate" : False ,
308- "deadline" : self ._client .timeout ,
309- }
310-
311- if method in [RequestMethod .GET , RequestMethod .DELETE ]:
312- # GET/DELETE requests use query params
313- fetch_args ["url" ] = self .add_params_to_url (url = abs_url , params = params , method = method )
314- elif method in [RequestMethod .POST , RequestMethod .PUT ]:
315- fetch_args ["url" ] = abs_url
316- # POST/PUT requests use body params
317- fetch_args ["payload" ] = json .dumps (params , default = self ._utf8 )
318- else :
319- raise EasyPostError (INVALID_REQUEST_METHOD_ERROR .format (method , SUPPORT_EMAIL ))
320-
321- try :
322- from google .appengine .api import urlfetch # type: ignore
323-
324- result = urlfetch .fetch (** fetch_args ) # type: ignore
325- except Exception as e :
326- raise HttpError (COMMUNICATION_ERROR .format (SUPPORT_EMAIL , e ))
327-
328- return result .content , result .status_code , result .headers
329-
330285 def handle_api_error (self , http_status : int , http_body : str , response : dict [str , Any ]) -> None :
331286 """Handles API errors returned from the EasyPost API."""
332287 try :
@@ -348,37 +303,3 @@ def handle_api_error(self, http_status: int, http_body: str, response: dict[str,
348303 http_status = http_status ,
349304 http_body = http_body ,
350305 )
351-
352- def _utf8 (self , value : Union [str , bytes ]) -> str :
353- # Python3's str(bytestring) returns "b'bytestring'" so we use .decode instead
354- if isinstance (value , bytes ):
355- return value .decode (encoding = "utf-8" )
356- return value
357-
358- def encode_url_params (self , params : dict [str , Any ], method : RequestMethod ) -> Union [str , None ]:
359- """Encode params for a URL."""
360- if method not in [RequestMethod .GET , RequestMethod .DELETE ]:
361- raise EasyPostError (INVALID_REQUEST_PARAMETERS_ERROR )
362-
363- converted_params = []
364-
365- for key , value in sorted (params .items ()):
366- if value is None :
367- continue # Don't add Nones to the query
368- elif isinstance (value , datetime .datetime ):
369- value = int (time .mktime (value .timetuple ())) # to UTC timestamp
370- converted_params .append ((key , value ))
371-
372- return urlencode (query = converted_params )
373-
374- def add_params_to_url (self , url : str , params : dict [str , Any ], method : RequestMethod ) -> str :
375- """Add params to the URL."""
376- if method not in [RequestMethod .GET , RequestMethod .DELETE ]:
377- raise EasyPostError (INVALID_REQUEST_PARAMETERS_ERROR )
378-
379- encoded_params = self .encode_url_params (params = params , method = method )
380-
381- if encoded_params :
382- return "%s?%s" % (url , encoded_params )
383-
384- return url
0 commit comments