pumpwood_communication.microservice_abc.base

Module with base classes for requests on Pumpwood Server.

1"""Module with base classes for requests on Pumpwood Server."""
2from .base import PumpWoodMicroServiceBase
3
4
5__docformat__ = "google"
6__all__ = [
7    PumpWoodMicroServiceBase
8]
class PumpWoodMicroServiceBase:
  41class PumpWoodMicroServiceBase:
  42    """Base class for Pumpwood MicroService.
  43
  44    Environment variables can be used to set MicroService parameters.
  45    Correct spelling is ``PUMPWOOD_COMMUNICATION__*``; legacy typo
  46    ``PUMPWOOD_COMUNICATION__*`` is still supported as fallback:
  47    - **PUMPWOOD_COMMUNICATION__DEFAULT_TIMEOUT:** Default requests timeout
  48        in seconds.
  49    - **PUMPWOOD_COMMUNICATION__DEBUG:** If object will be initiated using
  50        debug parameter. It will have more verbosity and login at each
  51        request. Options 'TRUE', 'FALSE'.
  52    - **PUMPWOOD_COMMUNICATION__VERIFY_SSL:** If requests will validate SSL
  53        certificate.
  54    """
  55
  56    __base_header = {'Content-Type': 'application/json'}
  57    """Base header for the requests."""
  58
  59    @staticmethod
  60    def _adjust_server_url(server_url):
  61        """Remove tralling / if present on server URL."""
  62        if server_url is None:
  63            return None
  64        if server_url[-1] != '/':
  65            return server_url + '/'
  66        else:
  67            return server_url
  68
  69    def __init__(self, name: str = None, server_url: str = None,
  70                 username: str = None, password: str = None,
  71                 verify_ssl: bool = True, debug: bool = None,
  72                 default_timeout: int = None, **kwargs):
  73        """Create new PumpWoodMicroService object.
  74
  75        Creates a new microservice object. If just name is passed, object must
  76        be initiate after with init() method.
  77
  78        Args:
  79            name:
  80                Name of the microservice, helps when exceptions
  81                are raised.
  82            server_url:
  83                URL of the server that will be connected.
  84            username:
  85                Username that will be logged on.
  86            password:
  87                Variable to be converted to JSON and posted along
  88                with the request.
  89            verify_ssl:
  90                Set if microservice will verify SSL certificate.
  91            debug:
  92                If microservice will be used as debug mode. This will obrigate
  93                auth token refresh for each call.
  94            default_timeout:
  95                Default timeout for Pumpwood calls.
  96            **kwargs:
  97                Other parameters used for compatibility between versions.
  98
  99        Returns:
 100            PumpWoodMicroService: New PumpWoodMicroService object
 101
 102        Raises:
 103            No particular Raises.
 104        """
 105        # Create attributes to be set at init function
 106        self.name = None
 107        """Name of the microservice instance."""
 108        self.server_url = None
 109        """Pumpwood server URL."""
 110        self._default_timeout: int = None
 111        """Default timeout for Pumpwood requests."""
 112        self._debug: bool = None
 113        """Name of the microservice instance."""
 114        self._verify_ssl: bool = None
 115        """If microservice should check the certificate."""
 116        self._is_mfa_login: bool = None
 117        """Set if is MFA login."""
 118        self.__headers: dict = None
 119        """Headers to be used on the requests."""
 120        self.__user: dict = None
 121        """Information of the logged user."""
 122        self.__auth_header: dict = None
 123        """Authenticated auth header."""
 124        self.__token_expiry: pd.Timedelta = None
 125        """Expirity datetime of the authetication token."""
 126        self.__username: str = None
 127        """Username associated with microservice."""
 128        self.__password: str = None
 129        """Password associated with microservice."""
 130        self.init(
 131            name=name, server_url=server_url,
 132            username=username, password=password,
 133            verify_ssl=verify_ssl, debug=debug,
 134            default_timeout=default_timeout)
 135
 136    def init(self, name: str = None, server_url: str = None,
 137             username: str = None, password: str = None,
 138             verify_ssl: bool = True, debug: bool = None,
 139             default_timeout: int = None, **kwargs):
 140        """Lazzy initialization of the MicroService of object.
 141
 142        This function might be usefull to use the object as a singleton at
 143        the backends. Using this function it is possible to instanciate an
 144        empty object and them set the attributes latter at the systems.
 145
 146        Args:
 147            name:
 148                Name of the microservice, helps when exceptions
 149                are raised.
 150            server_url:
 151                URL of the server that will be connected.
 152            username:
 153                Username that will be logged on.
 154            password:
 155                Variable to be converted to JSON and posted along
 156                with the request.
 157            verify_ssl:
 158                Set if microservice will verify SSL certificate.
 159            debug:
 160                If microservice will be used as debug mode. This will obrigate
 161                auth token refresh for each call.
 162            default_timeout:
 163                Default timeout for Pumpwood calls.
 164            **kwargs:
 165                Other parameters used for compatibility between versions.
 166
 167        Returns:
 168            No return
 169
 170        Raises:
 171            No particular Raises
 172        """
 173        self.name = name
 174        """Name of the microservice instance."""
 175        self.server_url = self._adjust_server_url(server_url)
 176        """Pumpwood server URL."""
 177
 178        # Set parameter using arguments or environment variables
 179        if default_timeout is None:
 180            self._default_timeout = DEFAULT_TIMEOUT
 181        else:
 182            self._default_timeout = default_timeout
 183
 184        if debug is None:
 185            self._debug = DEBUG
 186        else:
 187            self._debug = debug
 188
 189        if verify_ssl is None:
 190            self._verify_ssl = VERIFY_SSL
 191        else:
 192            self._verify_ssl = verify_ssl
 193
 194        self._is_mfa_login = False
 195        self.__headers = None
 196        self.__user = None
 197        self.__auth_header = None
 198        self.__token_expiry = None
 199        self.__username = username
 200        self.__password = password
 201
 202    @staticmethod
 203    def angular_json(request_result) -> Any:
 204        r"""Convert text to Json removing any XSSI at the beging of JSON.
 205
 206        Some backends add `)]}',\n` at the beginning of the JSON data to
 207        prevent injection of functions. This function remove this characters
 208        if present.
 209
 210        Args:
 211            request_result:
 212                JSON request to be converted.
 213
 214        Returns:
 215            No return
 216
 217        Raises:
 218            PumpWoodJSONLoadError:
 219                If it is not possible to load JSON from request data.
 220        """
 221        if request_result.text == '':
 222            return None
 223
 224        string_start = ")]}',\n"
 225        try:
 226            if request_result.text[:6] == string_start:
 227                return (orjson.loads(request_result.text[6:]))
 228            else:
 229                return (orjson.loads(request_result.text))
 230        except Exception:
 231            msg = "Can not decode to Json"
 232            raise PumpWoodJSONLoadError(
 233                message=msg, payload={"request_data": request_result.text})
 234
 235    def time_to_expiry(self) -> pd.Timedelta:
 236        """Return time to token expiry.
 237
 238        Args:
 239            No Args.
 240
 241        Returns:
 242            Return time until token expiration.
 243        """
 244        if self.__token_expiry is None:
 245            return None
 246
 247        now_datetime = pd.to_datetime(
 248            datetime.datetime.now(datetime.UTC), utc=True)
 249        time_to_expiry = self.__token_expiry - now_datetime
 250        return time_to_expiry
 251
 252    def is_credential_set(self) -> bool:
 253        """Check if username and password are set on object.
 254
 255        Args:
 256            No Args.
 257
 258        Returns:
 259            True if usename and password were set during object creation or
 260            later with init function.
 261        """
 262        is_username_not_none = self.__username is not None
 263        is_password_not_none = self.__password is not None
 264        return is_username_not_none and is_password_not_none
 265
 266    @classmethod
 267    def is_invalid_token_response(cls, response: Response) -> bool:
 268        """Check if reponse has invalid token error.
 269
 270        Args:
 271            response:
 272                Request reponse to check for invalid token.
 273
 274        Returns:
 275            Return True if response has an invalid token status.
 276        """
 277        if response.status_code == 401:
 278            return True
 279        return False
 280
 281    def _login_resquest(self) -> Response:
 282        """Request login with object credentials.
 283
 284        Args:
 285            No Args
 286
 287        Returns (Response):
 288            Request object.
 289        """
 290        login_url = urljoin(
 291            self.server_url, 'rest/registration/login/')
 292
 293        # Make a retry loop for authentication
 294        login_result = None
 295        for i in range(5):
 296            login_result = requests.post(
 297                login_url, json={
 298                    'username': self.__username,
 299                    'password': self.__password},
 300                verify=self._verify_ssl, timeout=self._default_timeout)
 301            if login_result.ok:
 302                try:
 303                    login_data = self.angular_json(login_result)
 304                    return login_data
 305                except Exception: # NOQA
 306                    pass
 307
 308            # Handle Unauthorized responses
 309            elif self.is_invalid_token_response(login_result):
 310                error_data = self.angular_json(login_result)
 311                raise PumpWoodUnauthorized(
 312                    message="Login is not possible",
 313                    payload=error_data)
 314
 315            # Handle Forbidden responses
 316            elif login_result.status_code == 403:
 317                error_data = self.angular_json(login_result)
 318                raise PumpWoodForbidden(
 319                    message="Login resquest is forbidden",
 320                    payload=error_data)
 321            time.sleep(0.2)
 322
 323        # If response is not returned then something is not ok
 324        error_data = self.angular_json(login_result)
 325        raise PumpWoodOtherException(
 326            message="Login not possible, server is not responding correctly",
 327            payload=error_data)
 328
 329    def confirm_mfa_code(self, mfa_login_data: dict) -> dict:
 330        """Ask user to confirm MFA code to login.
 331
 332        Open an input interface at terminal for user to validate MFA token.
 333
 334        Args:
 335            mfa_login_data:
 336                Result from login request with 'mfa_token'
 337                as key.
 338
 339        Returns:
 340            Return login returned with MFA confimation.
 341
 342        Raise:
 343            Raise error if reponse is not valid using error_handler.
 344        """
 345        code = input("## Please enter MFA code: ")
 346        url = urljoin(
 347            self.server_url, 'rest/registration/mfa-validate-code/')
 348        mfa_response = requests.post(url, headers={
 349            "X-PUMPWOOD-MFA-Autorization": mfa_login_data['mfa_token']},
 350            json={"mfa_code": code}, timeout=self._default_timeout)
 351        self.error_handler(mfa_response)
 352
 353        # Set _is_mfa_login true to indicate that login required MFA
 354        self._is_mfa_login = True
 355        return self.angular_json(mfa_response)
 356
 357    def login(self, force_refresh: bool = False) -> None:
 358        """Log microservice in using username and password provided.
 359
 360        Args:
 361            force_refresh (bool):
 362                Force token refresh despise still valid
 363                according to self.__token_expiry.
 364
 365        Returns:
 366            No return
 367
 368        Raises:
 369            Exception:
 370                If login response has status diferent from 200.
 371        """
 372        if not self.is_credential_set():
 373            raise PumpWoodUnauthorized(
 374                message="Microservice username or/and password not set")
 375
 376        # Check if expiry time is 1h from now
 377        refresh_expiry = False
 378        if self.__token_expiry is None:
 379            refresh_expiry = True
 380        else:
 381            time_to_expiry = self.time_to_expiry()
 382            if time_to_expiry < datetime.timedelta(hours=1):
 383                refresh_expiry = True
 384
 385        # When if debug always refresh token
 386        if refresh_expiry or force_refresh or self._debug:
 387            login_data = self._login_resquest()
 388            if 'mfa_token' in login_data.keys():
 389                login_data = self.confirm_mfa_code(
 390                    mfa_login_data=login_data)
 391
 392            self.set_auth_header(
 393                auth_token='Token ' + login_data['token'],
 394                token_expiry=pd.to_datetime(login_data['expiry']),
 395                user=login_data["user"])
 396        else:
 397            # Token is not expired or envicted, them keep same token
 398            return None
 399
 400    def _evict_auth_state(self) -> None:
 401        """Clear local authentication state after logout.
 402
 403        Resets token expiry, auth header, and cached user information so
 404        ``is_superuser`` and ``login`` behave correctly after logout.
 405        """
 406        self.__token_expiry = None
 407        self.__auth_header = None
 408        self.__user = None
 409
 410    def logout(self, auth_header: dict = None) -> bool:
 411        """Logout token.
 412
 413        Args:
 414            auth_header:
 415                Authentication header.
 416
 417        Returns:
 418            True if logout was ok.
 419        """
 420        resp = self.request_post(
 421            url='rest/registration/logout/',
 422            data={}, auth_header=auth_header)
 423        self._evict_auth_state()
 424        return resp is None
 425
 426    def logout_all(self, auth_header: dict = None) -> bool:
 427        """Logout all tokens from user.
 428
 429        Args:
 430            auth_header (dict):
 431                Authentication header.
 432
 433        Returns:
 434            True if logout all was ok.
 435        """
 436        resp = self.request_post(
 437            url='rest/registration/logoutall/',
 438            data={}, auth_header=auth_header)
 439        self._evict_auth_state()
 440        return resp is None
 441
 442    def get_auth_header(self) -> dict:
 443        """Retrieve auth_header and token_expiry from object.
 444
 445        Args:
 446            No Args.
 447
 448        Returns:
 449            Return authorization header and token_expiry datetime from object.
 450        """
 451        # Copy the dictonary to avoid updating the original one
 452        return copy.deepcopy({
 453            "auth_header": self.__auth_header,
 454            "token_expiry": self.__token_expiry})
 455
 456    def set_auth_header(self, auth_token: str,
 457                        token_expiry: pd.Timestamp,
 458                        user: dict = None) -> dict:
 459        """Retrieve auth_header and token_expiry from object.
 460
 461        Args:
 462            auth_token (str):
 463                Auth token that will be set for authentication.
 464            token_expiry (pd.Timestamp):
 465                Token expiry time.
 466            user (dict):
 467                User information to be set on authetication.
 468
 469        Returns:
 470            Return authorization header and token_expiry datetime from object.
 471        """
 472        # Copy the dictonary to avoid updating the original one
 473        self.__auth_header = {
 474            'Authorization': auth_token}
 475        self.__token_expiry = token_expiry
 476        self.__user = user
 477        return True
 478
 479    def clone(self, copy_session: bool = True) -> "PumpWoodMicroServiceBase":
 480        """Create a copy of this microservice instance.
 481
 482        Builds a new instance of the same class with the same connection
 483        configuration. When ``copy_session`` is True and this instance has
 484        an active session, the auth header, token expiry, and user data
 485        are copied so the clone can run requests independently (for
 486        example in a background thread) without sharing mutable auth
 487        state with the original.
 488
 489        Args:
 490            copy_session (bool):
 491                If True and this instance is logged in, copy the
 492                authentication session to the clone. Defaults to True.
 493
 494        Returns:
 495            PumpWoodMicroServiceBase:
 496                A new microservice instance with the same configuration.
 497        """
 498        cloned = self.__class__(
 499            name=self.name, server_url=self.server_url,
 500            username=self.__username, password=self.__password,
 501            verify_ssl=self._verify_ssl, debug=self._debug,
 502            default_timeout=self._default_timeout)
 503        if copy_session and self.__auth_header is not None:
 504            cloned.set_auth_header(
 505                auth_token=self.__auth_header['Authorization'],
 506                token_expiry=self.__token_expiry,
 507                user=copy.deepcopy(self.__user))
 508            cloned._is_mfa_login = self._is_mfa_login
 509        return cloned
 510
 511    def is_superuser(self) -> bool:
 512        """Check if is superuser.
 513
 514        Args:
 515            No Args.
 516
 517        Returns:
 518            Return True if is superuser.
 519        """
 520        user = self.__user
 521        if user is None:
 522            return False
 523        return user.get("is_superuser", False)
 524
 525    def _resolve_base_filter_skip(self, base_filter_skip):
 526        """Resolve base filter skip.
 527
 528        Args:
 529            base_filter_skip:
 530                Base filter skip to be resolved.
 531
 532        Returns:
 533            Return base filter skip resolved.
 534        """
 535        if base_filter_skip is None:
 536            if self.is_superuser():
 537                base_filter_skip = ['ALL']
 538            else:
 539                base_filter_skip = []
 540        return base_filter_skip
 541
 542    def _check_auth_header(self, auth_header: dict | None,
 543                           multipart: bool = False) -> dict:
 544        """Check if auth_header is set or auth_header if provided.
 545
 546        Args:
 547            auth_header (dict):
 548                AuthHeader to substitute the microservice original
 549                at the request (user impersonation).
 550            multipart (dict):
 551                Set if call should be made as a multipart instead of JSON.
 552
 553        Returns (dict):
 554            Return a header dict to be used in requests.
 555
 556        Raises:
 557            PumpWoodUnauthorized:
 558                If microservice is not logged and a auth_header method
 559                argument is not provided.
 560            PumpWoodUnauthorized:
 561                If microservice is logged and a auth_header method argument
 562                is provided.
 563        """
 564        if auth_header is None:
 565            # Login will refresh token if it is 1h to expire, it will also
 566            # check if credentials are set.
 567            self.login()
 568            auth_header_data = self.get_auth_header()
 569            auth_header = auth_header_data['auth_header']
 570            if multipart:
 571                return auth_header
 572            else:
 573                return self.__base_header | auth_header
 574        else:
 575            if self.is_credential_set():
 576                msg = (
 577                    'Microservice [{object_name}] with credentials and '
 578                    'auth_header was provided')
 579                raise PumpWoodUnauthorized(
 580                    message=msg, payload={'object_name': self.name})
 581
 582            # Set base header as JSON since unserialization is done using
 583            # Pumpwood Communication serialization function
 584            temp__auth_header = auth_header.copy()
 585            if multipart:
 586                return temp__auth_header
 587            else:
 588                return self.__base_header | temp__auth_header
 589
 590    @classmethod
 591    def error_handler(cls, response):
 592        """Handle request error.
 593
 594        Check if is a Json and propagate the error with
 595        same type if possible. If not Json raises the content.
 596
 597        Args:
 598            response:
 599                response to be handled, it is a PumpWoodException
 600                return it will raise the same exception at microservice
 601                object.
 602
 603        Returns:
 604            No return.
 605
 606        Raises:
 607            PumpWoodOtherException:
 608                If content-type is not application/json.
 609            PumpWoodOtherException:
 610                If content-type is application/json, but type not
 611                present or not recognisable at `exceptions.exceptions_dict`.
 612            Other PumpWoodException sub-types:
 613                If content-type is application/json if type is present and
 614                recognisable.
 615
 616        Example:
 617            No example
 618        """
 619        if not response.ok:
 620            utcnow = datetime.datetime.now(datetime.UTC)
 621            response_content_type = response.headers['content-type']
 622
 623            # Request information
 624            url = response.url
 625            method = response.request.method
 626            if 'application/json' not in response_content_type.lower():
 627                # Raise the exception as first in exception deep.
 628                exception_dict = [{
 629                    "exception_url": url,
 630                    "exception_method": method,
 631                    "exception_utcnow": utcnow.isoformat(),
 632                    "exception_deep": 1}]
 633                raise PumpWoodOtherException(
 634                    message=response.text, payload={
 635                        "!exception_stack!": exception_dict})
 636
 637            # Build error stack
 638            response_dict = cls.angular_json(response)
 639
 640            # Removing previous error stack
 641            payload = copy.deepcopy(
 642                response_dict.get("payload", {}))
 643            exception_stack = copy.deepcopy(
 644                payload.pop("!exception_stack!", []))
 645
 646            exception_deep = len(exception_stack)
 647            exception_dict = {
 648                "exception_url": url,
 649                "exception_method": method,
 650                "exception_utcnow": utcnow.isoformat(),
 651                "exception_deep": exception_deep + 1
 652            }
 653            exception_stack.insert(0, exception_dict)
 654            payload["!exception_stack!"] = exception_stack
 655
 656            ###################
 657            # Propagate error #
 658            # get exception using 'type' key at response data and get the
 659            # exception from exceptions_dict at exceptions
 660            exception_message = response_dict.get(
 661                "message_not_fmt", response_dict.get("message", ""))
 662            exception_type = response_dict.get("type")
 663            TempPumpwoodException = exceptions_dict\
 664                .get(exception_type, None)
 665            if TempPumpwoodException is not None:
 666                raise TempPumpwoodException(
 667                    message=exception_message,
 668                    status_code=response_dict.get(
 669                        "status_code", response.status_code),
 670                    payload=payload,
 671                    was_translated=response_dict.get("was_translated", False),
 672                    parallel=response_dict.get("parallel", False))
 673            else:
 674                # If token is invalid is at response, return a
 675                # PumpWoodUnauthorized error
 676                is_invalid_token = cls.is_invalid_token_response(response)
 677                response_dict["!exception_stack!"] = exception_stack
 678                if is_invalid_token:
 679                    raise PumpWoodUnauthorized(
 680                        message="Invalid token", payload=payload)
 681                else:
 682                    # If the error is not mapped return a
 683                    # PumpWoodOtherException limiting the message size to 1k
 684                    # characters
 685                    raise PumpWoodOtherException(
 686                        message="Not mapped exception JSON",
 687                        payload=response_dict)
 688
 689    def _request_post_json(self, post_url: str, data: any,
 690                           auth_header: dict = None,
 691                           parameters: None | dict = None) -> any:
 692        """Make a POST a request to url with data as JSON payload.
 693
 694        Args:
 695            post_url:
 696                URL to make the request, already with server url.
 697            data:
 698                Data to be used as Json payload.
 699            parameters:
 700                URL parameters.
 701            auth_header:
 702                AuthHeader to substitute the microservice original
 703                at the request (user impersonation).
 704
 705        Returns:
 706            Return the post response data.
 707
 708        Raises:
 709            PumpWoodException sub-types:
 710                Response is passed to error_handler.
 711        """
 712        parameters = {} if parameters is None else parameters
 713
 714        response = None
 715        request_header = self._check_auth_header(auth_header=auth_header)
 716        dumped_data = pumpJsonDump(data)
 717        response = requests.post(
 718            url=post_url, data=dumped_data,
 719            params=parameters, verify=self._verify_ssl,
 720            headers=request_header, timeout=self._default_timeout)
 721
 722        # Retry request if token is not valid forcing token renew
 723        retry_with_login = (
 724            self.is_invalid_token_response(response) and
 725            auth_header is None)
 726        if not retry_with_login:
 727            return response
 728        else:
 729            # Force token refresh if Unauthorized
 730            time.sleep(0.5)
 731            self.login(force_refresh=True)
 732            request_header = self._check_auth_header(auth_header=auth_header)
 733            return requests.post(
 734                url=post_url, data=dumped_data,
 735                params=parameters, verify=self._verify_ssl,
 736                headers=request_header, timeout=self._default_timeout)
 737
 738    def _request_post_multi(self, post_url: str, data: any, files: list = None,
 739                            auth_header: dict = None,
 740                            parameters: None | dict = None) -> any:
 741        """Make a POST a request to url with data as multipart payload.
 742
 743        Args:
 744            post_url:
 745                URL to make the request, already with server url.
 746            data:
 747                Data to be used as Json payload.
 748            files:
 749                A dictonary with file data, files will be set on field
 750                corresponding.to dictonary key.
 751                `{'file1': open('file1', 'rb'), {'file2': open('file2', 'rb')}`
 752            parameters:
 753                URL parameters.
 754            auth_header:
 755                AuthHeader to substitute the microservice original
 756                at the request (user impersonation).
 757
 758        Returns:
 759            Return the post response data.
 760
 761        Raises:
 762            PumpWoodException sub-types:
 763                Response is passed to error_handler.
 764        """
 765        parameters = {} if parameters is None else parameters
 766
 767        # Request with files are done using multipart serializing all fields
 768        # as JSON
 769        request_header = self._check_auth_header(
 770            auth_header=auth_header, multipart=True)
 771        temp_data = {'__json__': pumpJsonDump(data)}
 772
 773        response = requests.post(
 774            url=post_url, data=temp_data, files=files, params=parameters,
 775            verify=self._verify_ssl, headers=request_header,
 776            timeout=self._default_timeout)
 777        retry_with_login = (
 778            self.is_invalid_token_response(response) and
 779            auth_header is None)
 780        if not retry_with_login:
 781            return response
 782        else:
 783            # Force token refresh if Unauthorized
 784            time.sleep(0.5)
 785            self.login(force_refresh=True)
 786            request_header = self._check_auth_header(
 787                auth_header=auth_header, multipart=True)
 788            return requests.post(
 789                url=post_url, data=temp_data, files=files,
 790                params=parameters, verify=self._verify_ssl,
 791                headers=request_header, timeout=self._default_timeout)
 792
 793    @classmethod
 794    def _treat_response_for_file(cls, response: Response) -> dict:
 795        """Return if response contain a file.
 796
 797        Args:
 798            response (Response):
 799                Response to be checked for a file content.
 800
 801        Returns (bool):
 802            Returns if reponse has a file.
 803        """
 804        headers = response.headers
 805        content_disposition = headers.get('content-disposition')
 806        if content_disposition is None:
 807            return cls.angular_json(response)
 808        else:
 809            fname = re.findall("filename=(.+)", content_disposition)[0]
 810            return {
 811                "__file__": True,
 812                "content": response.content,
 813                "content-type": response.headers['content-type'],
 814                "filename": fname}
 815
 816    @classmethod
 817    def _dump_query_parameters(cls, parameters: dict) -> dict:
 818        """Dump query parameters to javascript compatibility.
 819
 820        Args:
 821            parameters (dict):
 822                Parameters to be parsed to JSON.
 823
 824        Returns:
 825            pass
 826        """
 827        # If parameters are not none convert them to json before
 828        # sending information on query string, 'True' is 'true' on javascript
 829        # for example
 830        if parameters is not None:
 831            temp_parameters = copy.deepcopy(parameters)
 832            for key in temp_parameters.keys():
 833                # Do not convert str to json, it put extra "" araound string
 834                if type(temp_parameters[key]) is not str:
 835                    temp_parameters[key] = pumpJsonDump(parameters[key])
 836            return temp_parameters
 837        else:
 838            return None
 839
 840    def request_post(self, url: str, data: any, files: list = None,
 841                     auth_header: dict = None,
 842                     parameters: None | dict = {}) -> any:
 843        """Make a POST a request to url with data as multipart/json payload.
 844
 845        Args:
 846            url:
 847                URL to make the request, already with server url.
 848            data:
 849                Data to be used as Json payload.
 850            files:
 851                A dictonary with file data, files will be set on field
 852                corresponding.to dictonary key.
 853                `{'file1': open('file1', 'rb'), {'file2': open('file2', 'rb')}`
 854            parameters:
 855                URL parameters.
 856            auth_header:
 857                AuthHeader to substitute the microservice original
 858                at the request (user impersonation).
 859
 860        Returns:
 861            Return the post response data.
 862
 863        Raises:
 864            PumpWoodException sub-types:
 865                Response is passed to error_handler.
 866        """
 867        parameters = {} if parameters is None else parameters
 868
 869        post_url = urljoin(self.server_url, url)
 870        dumped_parameters = self._dump_query_parameters(parameters=parameters)
 871        response = None
 872        if files is None:
 873            response = self._request_post_json(
 874                post_url=post_url, data=data, auth_header=auth_header,
 875                parameters=dumped_parameters)
 876        else:
 877            response = self._request_post_multi(
 878                post_url=post_url, data=data, files=files,
 879                auth_header=auth_header, parameters=dumped_parameters)
 880
 881        # Handle errors and re-raise if Pumpwood Exceptions
 882        self.error_handler(response)
 883        return self._treat_response_for_file(response=response)
 884
 885    def request_get(self, url: str, parameters: None | dict = None,
 886                    auth_header: dict = None,
 887                    use_disk_cache: bool = False,
 888                    disk_cache_expire: int = None,
 889                    disk_cache_tag_dict: dict = None) -> Any:
 890        """Make a GET a request to url with data as JSON payload.
 891
 892        Add the auth_header acording to login information and refresh token
 893        if auth_header=None and object token is expired.
 894
 895        Args:
 896            url (str):
 897                URL to make the request.
 898            parameters (dict):
 899                URL parameters to make the request.
 900            auth_header (dict):
 901                Auth header to substitute the microservice original
 902                at the request (user impersonation).
 903            use_disk_cache (bool):
 904                If set true, get request will use local cache to reduce
 905                the requests to the backend.
 906            disk_cache_expire (int):
 907                Time in seconds to expire the cache, it None it will
 908                use de default set be PumpwoodCache.
 909            disk_cache_tag_dict (dict):
 910                Dictionary to be used as a tag on get request.
 911
 912        Returns:
 913            Return the post reponse data.
 914
 915        Raises:
 916            PumpWoodException sub-types:
 917                Raise exception if reponse is not 2XX and if 'type' key on
 918                JSON payload if found at exceptions_dict. Use the same
 919                exception, message and payload.
 920            PumpWoodOtherException:
 921                If exception type is not found or return is not a json.
 922        """
 923        parameters = {} if parameters is None else parameters
 924
 925        request_header = self._check_auth_header(auth_header)
 926        # If is set to use diskcache, it will create a hash cash using
 927        # the query paramerers, url and user access token. The
 928        # hash will be used as index, not exposing the token at cache
 929        # database
 930        hash_dict = None
 931        if use_disk_cache:
 932            hash_dict = RequestGetCacheHash(
 933                context='pumpwood_communication-request_get',
 934                authorization=request_header['Authorization'],
 935                parameters=parameters,
 936                url=url)
 937
 938            cache_results = default_cache.get(hash_dict=hash_dict)
 939            if cache_results is not None:
 940                msg = "get from cache url[{url}]".format(url=url)
 941                logger.info(msg)
 942                return cache_results
 943
 944        dumped_parameters = self._dump_query_parameters(parameters=parameters)
 945        get_url = urljoin(self.server_url, url)
 946        response = requests.get(
 947            get_url, verify=self._verify_ssl, headers=request_header,
 948            params=dumped_parameters, timeout=self._default_timeout)
 949
 950        # If token is expired, refresh it
 951        retry_with_login = (
 952            self.is_invalid_token_response(response) and
 953            auth_header is None)
 954        if retry_with_login:
 955            time.sleep(0.5)
 956            self.login(force_refresh=True)
 957            request_header = self._check_auth_header(auth_header=auth_header)
 958            response = requests.get(
 959                get_url, verify=self._verify_ssl, headers=request_header,
 960                params=dumped_parameters, timeout=self._default_timeout)
 961
 962        # Re-raise Pumpwood exceptions
 963        self.error_handler(response=response)
 964        results = self._treat_response_for_file(response=response)
 965
 966        # If is set to use cache for this calls, set the local cache
 967        if use_disk_cache and not results.get('__file__', False):
 968            default_cache.set(
 969                hash_dict=hash_dict, value=results,
 970                expire=disk_cache_expire,
 971                tag_dict=disk_cache_tag_dict)
 972        return results
 973
 974    def request_delete(self, url, parameters: dict = None,
 975                       auth_header: dict = None):
 976        """Make a DELETE a request to url with data as Json payload.
 977
 978        Args:
 979            url:
 980                Url to make the request.
 981            parameters:
 982                Dictionary with Urls parameters.
 983            auth_header:
 984                Auth header to substitute the microservice original
 985                at the request (user impersonation).
 986
 987        Returns:
 988            Return the delete reponse payload.
 989
 990        Raises:
 991            PumpWoodException sub-types:
 992                Raise exception if reponse is not 2XX and if 'type' key on
 993                JSON payload if found at exceptions_dict. Use the same
 994                exception, message and payload.
 995            PumpWoodOtherException:
 996                If exception type is not found or return is not a json.
 997        """
 998        request_header = self._check_auth_header(auth_header)
 999        dumped_parameters = self._dump_query_parameters(parameters=parameters)
1000
1001        post_url = self.server_url + url
1002        response = requests.delete(
1003            post_url, verify=self._verify_ssl, headers=request_header,
1004            params=dumped_parameters, timeout=self._default_timeout)
1005
1006        # Retry request if token is not valid forcing token renew
1007        retry_with_login = (
1008            self.is_invalid_token_response(response) and
1009            auth_header is None)
1010        if retry_with_login:
1011            time.sleep(0.5)
1012            self.login(force_refresh=True)
1013            request_header = self._check_auth_header(auth_header=auth_header)
1014            response = requests.delete(
1015                post_url, verify=self._verify_ssl, headers=request_header,
1016                params=dumped_parameters, timeout=self._default_timeout)
1017
1018        # Re-raise Pumpwood Exceptions
1019        self.error_handler(response)
1020        return self.angular_json(response)
1021
1022    def get_user_info(self, auth_header: dict = None,
1023                      use_disk_cache: bool = False,
1024                      disk_cache_expire: int = None) -> dict:
1025        """Get user info.
1026
1027        Args:
1028            auth_header (dict): = None
1029                AuthHeader to substitute the microservice original at
1030                request. If not passed, microservice object auth_header
1031                will be used.
1032            use_disk_cache (bool):
1033                It possible use disk cache.
1034            disk_cache_expire (int):
1035                Set a time to expire the cache. If not passed env variable
1036                ``PUMPWOOD_COMMUNICATION__AUTHORIZATION_CACHE_TIMEOUT``
1037                env variable (legacy spelling supported), default 60 s.
1038
1039        Returns:
1040            A serialized user object with information of the logged user.
1041        """
1042        url = "rest/registration/retrieveauthenticateduser/"
1043        temp_disk_cache_expire = (
1044            disk_cache_expire
1045            if disk_cache_expire is not None else
1046            AUTHORIZATION_CACHE_TIMEOUT)
1047
1048        user_info = self.request_get(
1049            url=url, auth_header=auth_header, use_disk_cache=use_disk_cache,
1050            disk_cache_expire=temp_disk_cache_expire)
1051        return user_info

Base class for Pumpwood MicroService.

Environment variables can be used to set MicroService parameters. Correct spelling is PUMPWOOD_COMMUNICATION__*; legacy typo PUMPWOOD_COMUNICATION__* is still supported as fallback:

  • PUMPWOOD_COMMUNICATION__DEFAULT_TIMEOUT: Default requests timeout in seconds.
  • PUMPWOOD_COMMUNICATION__DEBUG: If object will be initiated using debug parameter. It will have more verbosity and login at each request. Options 'TRUE', 'FALSE'.
  • PUMPWOOD_COMMUNICATION__VERIFY_SSL: If requests will validate SSL certificate.
PumpWoodMicroServiceBase( name: str = None, server_url: str = None, username: str = None, password: str = None, verify_ssl: bool = True, debug: bool = None, default_timeout: int = None, **kwargs)
 69    def __init__(self, name: str = None, server_url: str = None,
 70                 username: str = None, password: str = None,
 71                 verify_ssl: bool = True, debug: bool = None,
 72                 default_timeout: int = None, **kwargs):
 73        """Create new PumpWoodMicroService object.
 74
 75        Creates a new microservice object. If just name is passed, object must
 76        be initiate after with init() method.
 77
 78        Args:
 79            name:
 80                Name of the microservice, helps when exceptions
 81                are raised.
 82            server_url:
 83                URL of the server that will be connected.
 84            username:
 85                Username that will be logged on.
 86            password:
 87                Variable to be converted to JSON and posted along
 88                with the request.
 89            verify_ssl:
 90                Set if microservice will verify SSL certificate.
 91            debug:
 92                If microservice will be used as debug mode. This will obrigate
 93                auth token refresh for each call.
 94            default_timeout:
 95                Default timeout for Pumpwood calls.
 96            **kwargs:
 97                Other parameters used for compatibility between versions.
 98
 99        Returns:
100            PumpWoodMicroService: New PumpWoodMicroService object
101
102        Raises:
103            No particular Raises.
104        """
105        # Create attributes to be set at init function
106        self.name = None
107        """Name of the microservice instance."""
108        self.server_url = None
109        """Pumpwood server URL."""
110        self._default_timeout: int = None
111        """Default timeout for Pumpwood requests."""
112        self._debug: bool = None
113        """Name of the microservice instance."""
114        self._verify_ssl: bool = None
115        """If microservice should check the certificate."""
116        self._is_mfa_login: bool = None
117        """Set if is MFA login."""
118        self.__headers: dict = None
119        """Headers to be used on the requests."""
120        self.__user: dict = None
121        """Information of the logged user."""
122        self.__auth_header: dict = None
123        """Authenticated auth header."""
124        self.__token_expiry: pd.Timedelta = None
125        """Expirity datetime of the authetication token."""
126        self.__username: str = None
127        """Username associated with microservice."""
128        self.__password: str = None
129        """Password associated with microservice."""
130        self.init(
131            name=name, server_url=server_url,
132            username=username, password=password,
133            verify_ssl=verify_ssl, debug=debug,
134            default_timeout=default_timeout)

Create new PumpWoodMicroService object.

Creates a new microservice object. If just name is passed, object must be initiate after with init() method.

Arguments:
  • name: Name of the microservice, helps when exceptions are raised.
  • server_url: URL of the server that will be connected.
  • username: Username that will be logged on.
  • password: Variable to be converted to JSON and posted along with the request.
  • verify_ssl: Set if microservice will verify SSL certificate.
  • debug: If microservice will be used as debug mode. This will obrigate auth token refresh for each call.
  • default_timeout: Default timeout for Pumpwood calls.
  • **kwargs: Other parameters used for compatibility between versions.
Returns:

PumpWoodMicroService: New PumpWoodMicroService object

Raises:
  • No particular Raises.
name

Name of the microservice instance.

server_url

Pumpwood server URL.

def init( self, name: str = None, server_url: str = None, username: str = None, password: str = None, verify_ssl: bool = True, debug: bool = None, default_timeout: int = None, **kwargs):
136    def init(self, name: str = None, server_url: str = None,
137             username: str = None, password: str = None,
138             verify_ssl: bool = True, debug: bool = None,
139             default_timeout: int = None, **kwargs):
140        """Lazzy initialization of the MicroService of object.
141
142        This function might be usefull to use the object as a singleton at
143        the backends. Using this function it is possible to instanciate an
144        empty object and them set the attributes latter at the systems.
145
146        Args:
147            name:
148                Name of the microservice, helps when exceptions
149                are raised.
150            server_url:
151                URL of the server that will be connected.
152            username:
153                Username that will be logged on.
154            password:
155                Variable to be converted to JSON and posted along
156                with the request.
157            verify_ssl:
158                Set if microservice will verify SSL certificate.
159            debug:
160                If microservice will be used as debug mode. This will obrigate
161                auth token refresh for each call.
162            default_timeout:
163                Default timeout for Pumpwood calls.
164            **kwargs:
165                Other parameters used for compatibility between versions.
166
167        Returns:
168            No return
169
170        Raises:
171            No particular Raises
172        """
173        self.name = name
174        """Name of the microservice instance."""
175        self.server_url = self._adjust_server_url(server_url)
176        """Pumpwood server URL."""
177
178        # Set parameter using arguments or environment variables
179        if default_timeout is None:
180            self._default_timeout = DEFAULT_TIMEOUT
181        else:
182            self._default_timeout = default_timeout
183
184        if debug is None:
185            self._debug = DEBUG
186        else:
187            self._debug = debug
188
189        if verify_ssl is None:
190            self._verify_ssl = VERIFY_SSL
191        else:
192            self._verify_ssl = verify_ssl
193
194        self._is_mfa_login = False
195        self.__headers = None
196        self.__user = None
197        self.__auth_header = None
198        self.__token_expiry = None
199        self.__username = username
200        self.__password = password

Lazzy initialization of the MicroService of object.

This function might be usefull to use the object as a singleton at the backends. Using this function it is possible to instanciate an empty object and them set the attributes latter at the systems.

Arguments:
  • name: Name of the microservice, helps when exceptions are raised.
  • server_url: URL of the server that will be connected.
  • username: Username that will be logged on.
  • password: Variable to be converted to JSON and posted along with the request.
  • verify_ssl: Set if microservice will verify SSL certificate.
  • debug: If microservice will be used as debug mode. This will obrigate auth token refresh for each call.
  • default_timeout: Default timeout for Pumpwood calls.
  • **kwargs: Other parameters used for compatibility between versions.
Returns:

No return

Raises:
  • No particular Raises
@staticmethod
def angular_json(request_result) -> Any:
202    @staticmethod
203    def angular_json(request_result) -> Any:
204        r"""Convert text to Json removing any XSSI at the beging of JSON.
205
206        Some backends add `)]}',\n` at the beginning of the JSON data to
207        prevent injection of functions. This function remove this characters
208        if present.
209
210        Args:
211            request_result:
212                JSON request to be converted.
213
214        Returns:
215            No return
216
217        Raises:
218            PumpWoodJSONLoadError:
219                If it is not possible to load JSON from request data.
220        """
221        if request_result.text == '':
222            return None
223
224        string_start = ")]}',\n"
225        try:
226            if request_result.text[:6] == string_start:
227                return (orjson.loads(request_result.text[6:]))
228            else:
229                return (orjson.loads(request_result.text))
230        except Exception:
231            msg = "Can not decode to Json"
232            raise PumpWoodJSONLoadError(
233                message=msg, payload={"request_data": request_result.text})

Convert text to Json removing any XSSI at the beging of JSON.

Some backends add )]}',\n at the beginning of the JSON data to prevent injection of functions. This function remove this characters if present.

Arguments:
  • request_result: JSON request to be converted.
Returns:

No return

Raises:
  • PumpWoodJSONLoadError: If it is not possible to load JSON from request data.
def time_to_expiry(self) -> pandas.Timedelta:
235    def time_to_expiry(self) -> pd.Timedelta:
236        """Return time to token expiry.
237
238        Args:
239            No Args.
240
241        Returns:
242            Return time until token expiration.
243        """
244        if self.__token_expiry is None:
245            return None
246
247        now_datetime = pd.to_datetime(
248            datetime.datetime.now(datetime.UTC), utc=True)
249        time_to_expiry = self.__token_expiry - now_datetime
250        return time_to_expiry

Return time to token expiry.

Arguments:
  • No Args.
Returns:

Return time until token expiration.

def is_credential_set(self) -> bool:
252    def is_credential_set(self) -> bool:
253        """Check if username and password are set on object.
254
255        Args:
256            No Args.
257
258        Returns:
259            True if usename and password were set during object creation or
260            later with init function.
261        """
262        is_username_not_none = self.__username is not None
263        is_password_not_none = self.__password is not None
264        return is_username_not_none and is_password_not_none

Check if username and password are set on object.

Arguments:
  • No Args.
Returns:

True if usename and password were set during object creation or later with init function.

@classmethod
def is_invalid_token_response(cls, response: requests.models.Response) -> bool:
266    @classmethod
267    def is_invalid_token_response(cls, response: Response) -> bool:
268        """Check if reponse has invalid token error.
269
270        Args:
271            response:
272                Request reponse to check for invalid token.
273
274        Returns:
275            Return True if response has an invalid token status.
276        """
277        if response.status_code == 401:
278            return True
279        return False

Check if reponse has invalid token error.

Arguments:
  • response: Request reponse to check for invalid token.
Returns:

Return True if response has an invalid token status.

def confirm_mfa_code(self, mfa_login_data: dict) -> dict:
329    def confirm_mfa_code(self, mfa_login_data: dict) -> dict:
330        """Ask user to confirm MFA code to login.
331
332        Open an input interface at terminal for user to validate MFA token.
333
334        Args:
335            mfa_login_data:
336                Result from login request with 'mfa_token'
337                as key.
338
339        Returns:
340            Return login returned with MFA confimation.
341
342        Raise:
343            Raise error if reponse is not valid using error_handler.
344        """
345        code = input("## Please enter MFA code: ")
346        url = urljoin(
347            self.server_url, 'rest/registration/mfa-validate-code/')
348        mfa_response = requests.post(url, headers={
349            "X-PUMPWOOD-MFA-Autorization": mfa_login_data['mfa_token']},
350            json={"mfa_code": code}, timeout=self._default_timeout)
351        self.error_handler(mfa_response)
352
353        # Set _is_mfa_login true to indicate that login required MFA
354        self._is_mfa_login = True
355        return self.angular_json(mfa_response)

Ask user to confirm MFA code to login.

Open an input interface at terminal for user to validate MFA token.

Arguments:
  • mfa_login_data: Result from login request with 'mfa_token' as key.
Returns:

Return login returned with MFA confimation.

Raises:
  • Raise error if reponse is not valid using error_handler.
def login(self, force_refresh: bool = False) -> None:
357    def login(self, force_refresh: bool = False) -> None:
358        """Log microservice in using username and password provided.
359
360        Args:
361            force_refresh (bool):
362                Force token refresh despise still valid
363                according to self.__token_expiry.
364
365        Returns:
366            No return
367
368        Raises:
369            Exception:
370                If login response has status diferent from 200.
371        """
372        if not self.is_credential_set():
373            raise PumpWoodUnauthorized(
374                message="Microservice username or/and password not set")
375
376        # Check if expiry time is 1h from now
377        refresh_expiry = False
378        if self.__token_expiry is None:
379            refresh_expiry = True
380        else:
381            time_to_expiry = self.time_to_expiry()
382            if time_to_expiry < datetime.timedelta(hours=1):
383                refresh_expiry = True
384
385        # When if debug always refresh token
386        if refresh_expiry or force_refresh or self._debug:
387            login_data = self._login_resquest()
388            if 'mfa_token' in login_data.keys():
389                login_data = self.confirm_mfa_code(
390                    mfa_login_data=login_data)
391
392            self.set_auth_header(
393                auth_token='Token ' + login_data['token'],
394                token_expiry=pd.to_datetime(login_data['expiry']),
395                user=login_data["user"])
396        else:
397            # Token is not expired or envicted, them keep same token
398            return None

Log microservice in using username and password provided.

Arguments:
  • force_refresh (bool): Force token refresh despise still valid according to self.__token_expiry.
Returns:

No return

Raises:
  • Exception: If login response has status diferent from 200.
def logout(self, auth_header: dict = None) -> bool:
410    def logout(self, auth_header: dict = None) -> bool:
411        """Logout token.
412
413        Args:
414            auth_header:
415                Authentication header.
416
417        Returns:
418            True if logout was ok.
419        """
420        resp = self.request_post(
421            url='rest/registration/logout/',
422            data={}, auth_header=auth_header)
423        self._evict_auth_state()
424        return resp is None

Logout token.

Arguments:
  • auth_header: Authentication header.
Returns:

True if logout was ok.

def logout_all(self, auth_header: dict = None) -> bool:
426    def logout_all(self, auth_header: dict = None) -> bool:
427        """Logout all tokens from user.
428
429        Args:
430            auth_header (dict):
431                Authentication header.
432
433        Returns:
434            True if logout all was ok.
435        """
436        resp = self.request_post(
437            url='rest/registration/logoutall/',
438            data={}, auth_header=auth_header)
439        self._evict_auth_state()
440        return resp is None

Logout all tokens from user.

Arguments:
  • auth_header (dict): Authentication header.
Returns:

True if logout all was ok.

def get_auth_header(self) -> dict:
442    def get_auth_header(self) -> dict:
443        """Retrieve auth_header and token_expiry from object.
444
445        Args:
446            No Args.
447
448        Returns:
449            Return authorization header and token_expiry datetime from object.
450        """
451        # Copy the dictonary to avoid updating the original one
452        return copy.deepcopy({
453            "auth_header": self.__auth_header,
454            "token_expiry": self.__token_expiry})

Retrieve auth_header and token_expiry from object.

Arguments:
  • No Args.
Returns:

Return authorization header and token_expiry datetime from object.

def set_auth_header( self, auth_token: str, token_expiry: pandas.Timestamp, user: dict = None) -> dict:
456    def set_auth_header(self, auth_token: str,
457                        token_expiry: pd.Timestamp,
458                        user: dict = None) -> dict:
459        """Retrieve auth_header and token_expiry from object.
460
461        Args:
462            auth_token (str):
463                Auth token that will be set for authentication.
464            token_expiry (pd.Timestamp):
465                Token expiry time.
466            user (dict):
467                User information to be set on authetication.
468
469        Returns:
470            Return authorization header and token_expiry datetime from object.
471        """
472        # Copy the dictonary to avoid updating the original one
473        self.__auth_header = {
474            'Authorization': auth_token}
475        self.__token_expiry = token_expiry
476        self.__user = user
477        return True

Retrieve auth_header and token_expiry from object.

Arguments:
  • auth_token (str): Auth token that will be set for authentication.
  • token_expiry (pd.Timestamp): Token expiry time.
  • user (dict): User information to be set on authetication.
Returns:

Return authorization header and token_expiry datetime from object.

def clone( self, copy_session: bool = True) -> PumpWoodMicroServiceBase:
479    def clone(self, copy_session: bool = True) -> "PumpWoodMicroServiceBase":
480        """Create a copy of this microservice instance.
481
482        Builds a new instance of the same class with the same connection
483        configuration. When ``copy_session`` is True and this instance has
484        an active session, the auth header, token expiry, and user data
485        are copied so the clone can run requests independently (for
486        example in a background thread) without sharing mutable auth
487        state with the original.
488
489        Args:
490            copy_session (bool):
491                If True and this instance is logged in, copy the
492                authentication session to the clone. Defaults to True.
493
494        Returns:
495            PumpWoodMicroServiceBase:
496                A new microservice instance with the same configuration.
497        """
498        cloned = self.__class__(
499            name=self.name, server_url=self.server_url,
500            username=self.__username, password=self.__password,
501            verify_ssl=self._verify_ssl, debug=self._debug,
502            default_timeout=self._default_timeout)
503        if copy_session and self.__auth_header is not None:
504            cloned.set_auth_header(
505                auth_token=self.__auth_header['Authorization'],
506                token_expiry=self.__token_expiry,
507                user=copy.deepcopy(self.__user))
508            cloned._is_mfa_login = self._is_mfa_login
509        return cloned

Create a copy of this microservice instance.

Builds a new instance of the same class with the same connection configuration. When copy_session is True and this instance has an active session, the auth header, token expiry, and user data are copied so the clone can run requests independently (for example in a background thread) without sharing mutable auth state with the original.

Arguments:
  • copy_session (bool): If True and this instance is logged in, copy the authentication session to the clone. Defaults to True.
Returns:

PumpWoodMicroServiceBase: A new microservice instance with the same configuration.

def is_superuser(self) -> bool:
511    def is_superuser(self) -> bool:
512        """Check if is superuser.
513
514        Args:
515            No Args.
516
517        Returns:
518            Return True if is superuser.
519        """
520        user = self.__user
521        if user is None:
522            return False
523        return user.get("is_superuser", False)

Check if is superuser.

Arguments:
  • No Args.
Returns:

Return True if is superuser.

@classmethod
def error_handler(cls, response):
590    @classmethod
591    def error_handler(cls, response):
592        """Handle request error.
593
594        Check if is a Json and propagate the error with
595        same type if possible. If not Json raises the content.
596
597        Args:
598            response:
599                response to be handled, it is a PumpWoodException
600                return it will raise the same exception at microservice
601                object.
602
603        Returns:
604            No return.
605
606        Raises:
607            PumpWoodOtherException:
608                If content-type is not application/json.
609            PumpWoodOtherException:
610                If content-type is application/json, but type not
611                present or not recognisable at `exceptions.exceptions_dict`.
612            Other PumpWoodException sub-types:
613                If content-type is application/json if type is present and
614                recognisable.
615
616        Example:
617            No example
618        """
619        if not response.ok:
620            utcnow = datetime.datetime.now(datetime.UTC)
621            response_content_type = response.headers['content-type']
622
623            # Request information
624            url = response.url
625            method = response.request.method
626            if 'application/json' not in response_content_type.lower():
627                # Raise the exception as first in exception deep.
628                exception_dict = [{
629                    "exception_url": url,
630                    "exception_method": method,
631                    "exception_utcnow": utcnow.isoformat(),
632                    "exception_deep": 1}]
633                raise PumpWoodOtherException(
634                    message=response.text, payload={
635                        "!exception_stack!": exception_dict})
636
637            # Build error stack
638            response_dict = cls.angular_json(response)
639
640            # Removing previous error stack
641            payload = copy.deepcopy(
642                response_dict.get("payload", {}))
643            exception_stack = copy.deepcopy(
644                payload.pop("!exception_stack!", []))
645
646            exception_deep = len(exception_stack)
647            exception_dict = {
648                "exception_url": url,
649                "exception_method": method,
650                "exception_utcnow": utcnow.isoformat(),
651                "exception_deep": exception_deep + 1
652            }
653            exception_stack.insert(0, exception_dict)
654            payload["!exception_stack!"] = exception_stack
655
656            ###################
657            # Propagate error #
658            # get exception using 'type' key at response data and get the
659            # exception from exceptions_dict at exceptions
660            exception_message = response_dict.get(
661                "message_not_fmt", response_dict.get("message", ""))
662            exception_type = response_dict.get("type")
663            TempPumpwoodException = exceptions_dict\
664                .get(exception_type, None)
665            if TempPumpwoodException is not None:
666                raise TempPumpwoodException(
667                    message=exception_message,
668                    status_code=response_dict.get(
669                        "status_code", response.status_code),
670                    payload=payload,
671                    was_translated=response_dict.get("was_translated", False),
672                    parallel=response_dict.get("parallel", False))
673            else:
674                # If token is invalid is at response, return a
675                # PumpWoodUnauthorized error
676                is_invalid_token = cls.is_invalid_token_response(response)
677                response_dict["!exception_stack!"] = exception_stack
678                if is_invalid_token:
679                    raise PumpWoodUnauthorized(
680                        message="Invalid token", payload=payload)
681                else:
682                    # If the error is not mapped return a
683                    # PumpWoodOtherException limiting the message size to 1k
684                    # characters
685                    raise PumpWoodOtherException(
686                        message="Not mapped exception JSON",
687                        payload=response_dict)

Handle request error.

Check if is a Json and propagate the error with same type if possible. If not Json raises the content.

Arguments:
  • response: response to be handled, it is a PumpWoodException return it will raise the same exception at microservice object.
Returns:

No return.

Raises:
  • PumpWoodOtherException: If content-type is not application/json.
  • PumpWoodOtherException: If content-type is application/json, but type not present or not recognisable at exceptions.exceptions_dict.
  • Other PumpWoodException sub-types: If content-type is application/json if type is present and recognisable.
Example:

No example

def request_post( self, url: str, data: <built-in function any>, files: list = None, auth_header: dict = None, parameters: None | dict = {}) -> <built-in function any>:
840    def request_post(self, url: str, data: any, files: list = None,
841                     auth_header: dict = None,
842                     parameters: None | dict = {}) -> any:
843        """Make a POST a request to url with data as multipart/json payload.
844
845        Args:
846            url:
847                URL to make the request, already with server url.
848            data:
849                Data to be used as Json payload.
850            files:
851                A dictonary with file data, files will be set on field
852                corresponding.to dictonary key.
853                `{'file1': open('file1', 'rb'), {'file2': open('file2', 'rb')}`
854            parameters:
855                URL parameters.
856            auth_header:
857                AuthHeader to substitute the microservice original
858                at the request (user impersonation).
859
860        Returns:
861            Return the post response data.
862
863        Raises:
864            PumpWoodException sub-types:
865                Response is passed to error_handler.
866        """
867        parameters = {} if parameters is None else parameters
868
869        post_url = urljoin(self.server_url, url)
870        dumped_parameters = self._dump_query_parameters(parameters=parameters)
871        response = None
872        if files is None:
873            response = self._request_post_json(
874                post_url=post_url, data=data, auth_header=auth_header,
875                parameters=dumped_parameters)
876        else:
877            response = self._request_post_multi(
878                post_url=post_url, data=data, files=files,
879                auth_header=auth_header, parameters=dumped_parameters)
880
881        # Handle errors and re-raise if Pumpwood Exceptions
882        self.error_handler(response)
883        return self._treat_response_for_file(response=response)

Make a POST a request to url with data as multipart/json payload.

Arguments:
  • url: URL to make the request, already with server url.
  • data: Data to be used as Json payload.
  • files: A dictonary with file data, files will be set on field corresponding.to dictonary key. {'file1': open('file1', 'rb'), {'file2': open('file2', 'rb')}
  • parameters: URL parameters.
  • auth_header: AuthHeader to substitute the microservice original at the request (user impersonation).
Returns:

Return the post response data.

Raises:
  • PumpWoodException sub-types: Response is passed to error_handler.
def request_get( self, url: str, parameters: None | dict = None, auth_header: dict = None, use_disk_cache: bool = False, disk_cache_expire: int = None, disk_cache_tag_dict: dict = None) -> Any:
885    def request_get(self, url: str, parameters: None | dict = None,
886                    auth_header: dict = None,
887                    use_disk_cache: bool = False,
888                    disk_cache_expire: int = None,
889                    disk_cache_tag_dict: dict = None) -> Any:
890        """Make a GET a request to url with data as JSON payload.
891
892        Add the auth_header acording to login information and refresh token
893        if auth_header=None and object token is expired.
894
895        Args:
896            url (str):
897                URL to make the request.
898            parameters (dict):
899                URL parameters to make the request.
900            auth_header (dict):
901                Auth header to substitute the microservice original
902                at the request (user impersonation).
903            use_disk_cache (bool):
904                If set true, get request will use local cache to reduce
905                the requests to the backend.
906            disk_cache_expire (int):
907                Time in seconds to expire the cache, it None it will
908                use de default set be PumpwoodCache.
909            disk_cache_tag_dict (dict):
910                Dictionary to be used as a tag on get request.
911
912        Returns:
913            Return the post reponse data.
914
915        Raises:
916            PumpWoodException sub-types:
917                Raise exception if reponse is not 2XX and if 'type' key on
918                JSON payload if found at exceptions_dict. Use the same
919                exception, message and payload.
920            PumpWoodOtherException:
921                If exception type is not found or return is not a json.
922        """
923        parameters = {} if parameters is None else parameters
924
925        request_header = self._check_auth_header(auth_header)
926        # If is set to use diskcache, it will create a hash cash using
927        # the query paramerers, url and user access token. The
928        # hash will be used as index, not exposing the token at cache
929        # database
930        hash_dict = None
931        if use_disk_cache:
932            hash_dict = RequestGetCacheHash(
933                context='pumpwood_communication-request_get',
934                authorization=request_header['Authorization'],
935                parameters=parameters,
936                url=url)
937
938            cache_results = default_cache.get(hash_dict=hash_dict)
939            if cache_results is not None:
940                msg = "get from cache url[{url}]".format(url=url)
941                logger.info(msg)
942                return cache_results
943
944        dumped_parameters = self._dump_query_parameters(parameters=parameters)
945        get_url = urljoin(self.server_url, url)
946        response = requests.get(
947            get_url, verify=self._verify_ssl, headers=request_header,
948            params=dumped_parameters, timeout=self._default_timeout)
949
950        # If token is expired, refresh it
951        retry_with_login = (
952            self.is_invalid_token_response(response) and
953            auth_header is None)
954        if retry_with_login:
955            time.sleep(0.5)
956            self.login(force_refresh=True)
957            request_header = self._check_auth_header(auth_header=auth_header)
958            response = requests.get(
959                get_url, verify=self._verify_ssl, headers=request_header,
960                params=dumped_parameters, timeout=self._default_timeout)
961
962        # Re-raise Pumpwood exceptions
963        self.error_handler(response=response)
964        results = self._treat_response_for_file(response=response)
965
966        # If is set to use cache for this calls, set the local cache
967        if use_disk_cache and not results.get('__file__', False):
968            default_cache.set(
969                hash_dict=hash_dict, value=results,
970                expire=disk_cache_expire,
971                tag_dict=disk_cache_tag_dict)
972        return results

Make a GET a request to url with data as JSON payload.

Add the auth_header acording to login information and refresh token if auth_header=None and object token is expired.

Arguments:
  • url (str): URL to make the request.
  • parameters (dict): URL parameters to make the request.
  • auth_header (dict): Auth header to substitute the microservice original at the request (user impersonation).
  • use_disk_cache (bool): If set true, get request will use local cache to reduce the requests to the backend.
  • disk_cache_expire (int): Time in seconds to expire the cache, it None it will use de default set be PumpwoodCache.
  • disk_cache_tag_dict (dict): Dictionary to be used as a tag on get request.
Returns:

Return the post reponse data.

Raises:
  • PumpWoodException sub-types: Raise exception if reponse is not 2XX and if 'type' key on JSON payload if found at exceptions_dict. Use the same exception, message and payload.
  • PumpWoodOtherException: If exception type is not found or return is not a json.
def request_delete(self, url, parameters: dict = None, auth_header: dict = None):
 974    def request_delete(self, url, parameters: dict = None,
 975                       auth_header: dict = None):
 976        """Make a DELETE a request to url with data as Json payload.
 977
 978        Args:
 979            url:
 980                Url to make the request.
 981            parameters:
 982                Dictionary with Urls parameters.
 983            auth_header:
 984                Auth header to substitute the microservice original
 985                at the request (user impersonation).
 986
 987        Returns:
 988            Return the delete reponse payload.
 989
 990        Raises:
 991            PumpWoodException sub-types:
 992                Raise exception if reponse is not 2XX and if 'type' key on
 993                JSON payload if found at exceptions_dict. Use the same
 994                exception, message and payload.
 995            PumpWoodOtherException:
 996                If exception type is not found or return is not a json.
 997        """
 998        request_header = self._check_auth_header(auth_header)
 999        dumped_parameters = self._dump_query_parameters(parameters=parameters)
1000
1001        post_url = self.server_url + url
1002        response = requests.delete(
1003            post_url, verify=self._verify_ssl, headers=request_header,
1004            params=dumped_parameters, timeout=self._default_timeout)
1005
1006        # Retry request if token is not valid forcing token renew
1007        retry_with_login = (
1008            self.is_invalid_token_response(response) and
1009            auth_header is None)
1010        if retry_with_login:
1011            time.sleep(0.5)
1012            self.login(force_refresh=True)
1013            request_header = self._check_auth_header(auth_header=auth_header)
1014            response = requests.delete(
1015                post_url, verify=self._verify_ssl, headers=request_header,
1016                params=dumped_parameters, timeout=self._default_timeout)
1017
1018        # Re-raise Pumpwood Exceptions
1019        self.error_handler(response)
1020        return self.angular_json(response)

Make a DELETE a request to url with data as Json payload.

Arguments:
  • url: Url to make the request.
  • parameters: Dictionary with Urls parameters.
  • auth_header: Auth header to substitute the microservice original at the request (user impersonation).
Returns:

Return the delete reponse payload.

Raises:
  • PumpWoodException sub-types: Raise exception if reponse is not 2XX and if 'type' key on JSON payload if found at exceptions_dict. Use the same exception, message and payload.
  • PumpWoodOtherException: If exception type is not found or return is not a json.
def get_user_info( self, auth_header: dict = None, use_disk_cache: bool = False, disk_cache_expire: int = None) -> dict:
1022    def get_user_info(self, auth_header: dict = None,
1023                      use_disk_cache: bool = False,
1024                      disk_cache_expire: int = None) -> dict:
1025        """Get user info.
1026
1027        Args:
1028            auth_header (dict): = None
1029                AuthHeader to substitute the microservice original at
1030                request. If not passed, microservice object auth_header
1031                will be used.
1032            use_disk_cache (bool):
1033                It possible use disk cache.
1034            disk_cache_expire (int):
1035                Set a time to expire the cache. If not passed env variable
1036                ``PUMPWOOD_COMMUNICATION__AUTHORIZATION_CACHE_TIMEOUT``
1037                env variable (legacy spelling supported), default 60 s.
1038
1039        Returns:
1040            A serialized user object with information of the logged user.
1041        """
1042        url = "rest/registration/retrieveauthenticateduser/"
1043        temp_disk_cache_expire = (
1044            disk_cache_expire
1045            if disk_cache_expire is not None else
1046            AUTHORIZATION_CACHE_TIMEOUT)
1047
1048        user_info = self.request_get(
1049            url=url, auth_header=auth_header, use_disk_cache=use_disk_cache,
1050            disk_cache_expire=temp_disk_cache_expire)
1051        return user_info

Get user info.

Arguments:
  • auth_header (dict): = None AuthHeader to substitute the microservice original at request. If not passed, microservice object auth_header will be used.
  • use_disk_cache (bool): It possible use disk cache.
  • disk_cache_expire (int): Set a time to expire the cache. If not passed env variable PUMPWOOD_COMMUNICATION__AUTHORIZATION_CACHE_TIMEOUT env variable (legacy spelling supported), default 60 s.
Returns:

A serialized user object with information of the logged user.