3434from contextlib import contextmanager
3535from datetime import datetime
3636from functools import wraps
37- from io import BytesIO
38- from urllib import parse
3937from http import client
4038from http .cookies import SimpleCookie
39+ from io import BytesIO
40+ from urllib import parse
4141from xml .etree .ElementTree import XML , ParseError
42- from .data import record
43- from . import __version__
4442
43+ from . import __version__
44+ from .data import record
4545
4646logger = logging .getLogger (__name__ )
4747
4848__all__ = [
4949 "AuthenticationError" ,
50- "connect" ,
5150 "Context" ,
52- "handler" ,
5351 "HTTPError" ,
5452 "UrlEncoded" ,
53+ "_NoAuthenticationToken" ,
5554 "_encode" ,
5655 "_make_cookie_header" ,
57- "_NoAuthenticationToken" ,
56+ "connect" ,
57+ "handler" ,
5858 "namespace" ,
5959]
6060
@@ -102,7 +102,7 @@ def mask_sensitive_data(data):
102102 if not isinstance (data , dict ):
103103 try :
104104 data = json .loads (data )
105- except Exception as ex :
105+ except Exception :
106106 return data
107107
108108 # json.loads will return "123"(str) as 123(int), so return the data if it's not 'dict' type
@@ -251,7 +251,7 @@ def __mod__(self, fields):
251251 raise TypeError ("Cannot interpolate into a UrlEncoded object." )
252252
253253 def __repr__ (self ):
254- return f"UrlEncoded({ repr ( parse .unquote (str (self ))) } )"
254+ return f"UrlEncoded({ parse .unquote (str (self ))!r } )"
255255
256256
257257@contextmanager
@@ -345,9 +345,7 @@ def wrapper(self, *args, **kwargs):
345345 ):
346346 return request_fun (self , * args , ** kwargs )
347347 elif he .status == 401 and not self .autologin :
348- raise AuthenticationError (
349- "Request failed: Session is not logged in." , he
350- )
348+ raise AuthenticationError ("Request failed: Session is not logged in." , he )
351349 else :
352350 raise
353351
@@ -612,9 +610,7 @@ def _auth_headers(self):
612610 if token :
613611 header .append (("Authorization" , token ))
614612 if self .get_cookies ():
615- header .append (
616- ("Cookie" , _make_cookie_header (list (self .get_cookies ().items ())))
617- )
613+ header .append (("Cookie" , _make_cookie_header (list (self .get_cookies ().items ()))))
618614
619615 return header
620616
@@ -666,10 +662,8 @@ def delete(self, path_segment, owner=None, app=None, sharing=None, **query):
666662 default :class:`Context` namespace. All other keyword arguments are
667663 included in the URL as query parameters.
668664
669- :raises AuthenticationError: Raised when the ``Context`` object is not
670- logged in.
671- :raises HTTPError: Raised when an error occurred in a GET operation from
672- *path_segment*.
665+ :raises AuthenticationError: Raised when the ``Context`` object is not logged in.
666+ :raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
673667 :param path_segment: A REST path segment.
674668 :type path_segment: ``string``
675669 :param owner: The owner context of the namespace (optional).
@@ -678,12 +672,10 @@ def delete(self, path_segment, owner=None, app=None, sharing=None, **query):
678672 :type app: ``string``
679673 :param sharing: The sharing mode of the namespace (optional).
680674 :type sharing: ``string``
681- :param query: All other keyword arguments, which are used as query
682- parameters.
675+ :param query: All other keyword arguments, which are used as query parameters.
683676 :type query: ``string``
684677 :return: The response from the server.
685- :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
686- and ``status``
678+ :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
687679
688680 **Example**::
689681
@@ -699,24 +691,18 @@ def delete(self, path_segment, owner=None, app=None, sharing=None, **query):
699691 ('content-type', 'text/xml; charset=utf-8')],
700692 'reason': 'OK',
701693 'status': 200}
702- c.delete('nonexistant /path') # raises HTTPError
694+ c.delete('nonexistent /path') # raises HTTPError
703695 c.logout()
704696 c.delete('apps/local') # raises AuthenticationError
705697 """
706- path = self .authority + self ._abspath (
707- path_segment , owner = owner , app = app , sharing = sharing
708- )
709- logger .debug (
710- "DELETE request to %s (body: %s)" , path , mask_sensitive_data (query )
711- )
698+ path = self .authority + self ._abspath (path_segment , owner = owner , app = app , sharing = sharing )
699+ logger .debug ("DELETE request to %s (body: %s)" , path , mask_sensitive_data (query ))
712700 response = self .http .delete (path , self ._auth_headers , ** query )
713701 return response
714702
715703 @_authentication
716704 @_log_duration
717- def get (
718- self , path_segment , owner = None , app = None , headers = None , sharing = None , ** query
719- ):
705+ def get (self , path_segment , owner = None , app = None , headers = None , sharing = None , ** query ):
720706 """Performs a GET operation from the REST path segment with the given
721707 namespace and query.
722708
@@ -729,10 +715,8 @@ def get(
729715 default :class:`Context` namespace. All other keyword arguments are
730716 included in the URL as query parameters.
731717
732- :raises AuthenticationError: Raised when the ``Context`` object is not
733- logged in.
734- :raises HTTPError: Raised when an error occurred in a GET operation from
735- *path_segment*.
718+ :raises AuthenticationError: Raised when the ``Context`` object is not logged in.
719+ :raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
736720 :param path_segment: A REST path segment.
737721 :type path_segment: ``string``
738722 :param owner: The owner context of the namespace (optional).
@@ -743,12 +727,10 @@ def get(
743727 :type headers: ``list`` of 2-tuples.
744728 :param sharing: The sharing mode of the namespace (optional).
745729 :type sharing: ``string``
746- :param query: All other keyword arguments, which are used as query
747- parameters.
730+ :param query: All other keyword arguments, which are used as query parameters.
748731 :type query: ``string``
749732 :return: The response from the server.
750- :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
751- and ``status``
733+ :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
752734
753735 **Example**::
754736
@@ -764,26 +746,22 @@ def get(
764746 ('content-type', 'text/xml; charset=utf-8')],
765747 'reason': 'OK',
766748 'status': 200}
767- c.get('nonexistant /path') # raises HTTPError
749+ c.get('nonexistent /path') # raises HTTPError
768750 c.logout()
769751 c.get('apps/local') # raises AuthenticationError
770752 """
771753 if headers is None :
772754 headers = []
773755
774- path = self .authority + self ._abspath (
775- path_segment , owner = owner , app = app , sharing = sharing
776- )
756+ path = self .authority + self ._abspath (path_segment , owner = owner , app = app , sharing = sharing )
777757 logger .debug ("GET request to %s (body: %s)" , path , mask_sensitive_data (query ))
778758 all_headers = headers + self .additional_headers + self ._auth_headers
779759 response = self .http .get (path , all_headers , ** query )
780760 return response
781761
782762 @_authentication
783763 @_log_duration
784- def post (
785- self , path_segment , owner = None , app = None , sharing = None , headers = None , ** query
786- ):
764+ def post (self , path_segment , owner = None , app = None , sharing = None , headers = None , ** query ):
787765 """Performs a POST operation from the REST path segment with the given
788766 namespace and query.
789767
@@ -803,10 +781,8 @@ def post(
803781 body, and all other keyword arguments will be passed as
804782 GET-style arguments in the URL.
805783
806- :raises AuthenticationError: Raised when the ``Context`` object is not
807- logged in.
808- :raises HTTPError: Raised when an error occurred in a GET operation from
809- *path_segment*.
784+ :raises AuthenticationError: Raised when the ``Context`` object is not logged in.
785+ :raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
810786 :param path_segment: A REST path segment.
811787 :type path_segment: ``string``
812788 :param owner: The owner context of the namespace (optional).
@@ -817,17 +793,15 @@ def post(
817793 :type sharing: ``string``
818794 :param headers: List of extra HTTP headers to send (optional).
819795 :type headers: ``list`` of 2-tuples.
820- :param query: All other keyword arguments, which are used as query
821- parameters.
796+ :param query: All other keyword arguments, which are used as query parameters.
822797 :param body: Parameters to be used in the post body. If specified,
823798 any parameters in the query will be applied to the URL instead of
824799 the body. If a dict is supplied, the key-value pairs will be form
825800 encoded. If a string is supplied, the body will be passed through
826801 in the request unchanged.
827802 :type body: ``dict`` or ``str``
828803 :return: The response from the server.
829- :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
830- and ``status``
804+ :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
831805
832806 **Example**::
833807
@@ -844,7 +818,7 @@ def post(
844818 ('content-type', 'text/xml; charset=utf-8')],
845819 'reason': 'Created',
846820 'status': 201}
847- c.post('nonexistant /path') # raises HTTPError
821+ c.post('nonexistent /path') # raises HTTPError
848822 c.logout()
849823 # raises AuthenticationError:
850824 c.post('saved/searches', name='boris',
@@ -853,9 +827,7 @@ def post(
853827 if headers is None :
854828 headers = []
855829
856- path = self .authority + self ._abspath (
857- path_segment , owner = owner , app = app , sharing = sharing
858- )
830+ path = self .authority + self ._abspath (path_segment , owner = owner , app = app , sharing = sharing )
859831
860832 logger .debug ("POST request to %s (body: %s)" , path , mask_sensitive_data (query ))
861833 all_headers = headers + self .additional_headers + self ._auth_headers
@@ -883,10 +855,8 @@ def request(
883855 default :class:`Context` namespace. All other keyword arguments are
884856 included in the URL as query parameters.
885857
886- :raises AuthenticationError: Raised when the ``Context`` object is not
887- logged in.
888- :raises HTTPError: Raised when an error occurred in a GET operation from
889- *path_segment*.
858+ :raises AuthenticationError: Raised when the ``Context`` object is not logged in.
859+ :raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
890860 :param path_segment: A REST path segment.
891861 :type path_segment: ``string``
892862 :param method: The HTTP method to use (optional).
@@ -902,8 +872,7 @@ def request(
902872 :param sharing: The sharing mode of the namespace (optional).
903873 :type sharing: ``string``
904874 :return: The response from the server.
905- :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
906- and ``status``
875+ :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
907876
908877 **Example**::
909878
@@ -919,16 +888,14 @@ def request(
919888 ('content-type', 'text/xml; charset=utf-8')],
920889 'reason': 'OK',
921890 'status': 200}
922- c.request('nonexistant /path', method='GET') # raises HTTPError
891+ c.request('nonexistent /path', method='GET') # raises HTTPError
923892 c.logout()
924893 c.get('apps/local') # raises AuthenticationError
925894 """
926895 if headers is None :
927896 headers = []
928897
929- path = self .authority + self ._abspath (
930- path_segment , owner = owner , app = app , sharing = sharing
931- )
898+ path = self .authority + self ._abspath (path_segment , owner = owner , app = app , sharing = sharing )
932899
933900 all_headers = headers + self .additional_headers + self ._auth_headers
934901 logger .debug (
@@ -979,9 +946,7 @@ def login(self):
979946 # logged in.
980947 return
981948
982- if self .token is not _NoAuthenticationToken and (
983- not self .username and not self .password
984- ):
949+ if self .token is not _NoAuthenticationToken and (not self .username and not self .password ):
985950 # If we were passed a session token, but no username or
986951 # password, then login is a nop, since we're automatically
987952 # logged in.
@@ -1078,9 +1043,7 @@ def _abspath(self, path_segment, owner=None, app=None, sharing=None):
10781043
10791044 oname = "nobody" if ns .owner is None else ns .owner
10801045 aname = "system" if ns .app is None else ns .app
1081- path = UrlEncoded (
1082- f"/servicesNS/{ oname } /{ aname } /{ path_segment } " , skip_encode = skip_encode
1083- )
1046+ path = UrlEncoded (f"/servicesNS/{ oname } /{ aname } /{ path_segment } " , skip_encode = skip_encode )
10841047 return path
10851048
10861049
@@ -1223,11 +1186,7 @@ def _spliturl(url):
12231186 parsed_url = parse .urlparse (url )
12241187 host = parsed_url .hostname
12251188 port = parsed_url .port
1226- path = (
1227- "?" .join ((parsed_url .path , parsed_url .query ))
1228- if parsed_url .query
1229- else parsed_url .path
1230- )
1189+ path = "?" .join ((parsed_url .path , parsed_url .query )) if parsed_url .query else parsed_url .path
12311190 # Strip brackets if its an IPv6 address
12321191 if host .startswith ("[" ) and host .endswith ("]" ):
12331192 host = host [1 :- 1 ]
@@ -1574,10 +1533,7 @@ def request(url, message, **kwargs):
15741533 if timeout is not None :
15751534 connection .sock .settimeout (timeout )
15761535 response = connection .getresponse ()
1577- is_keepalive = (
1578- "keep-alive"
1579- in response .getheader ("connection" , default = "close" ).lower ()
1580- )
1536+ is_keepalive = "keep-alive" in response .getheader ("connection" , default = "close" ).lower ()
15811537 finally :
15821538 if not is_keepalive :
15831539 connection .close ()
0 commit comments