Beispiel #1
0
    def _send_payload(self, payload: Dict[str, Any]) -> None:
        """Sends payload to GA via Measurement Protocol REST API.

    Args:
      payload: Parameters containing required data for app conversion tracking.

    Returns:
      results: Includes request body, status_code, error_msg, response body and
      dry_run flag.
      The response refers to the definition of conversion tracking response in
      https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=firebase
    """

        if self.dry_run:
            self.log.info(
                """Dry run mode: Dry run mode: Simulating sending event to GA4 (data
          will not actually be sent). URL:{}. payload data:{}.""".format(
                    self.post_url, payload))
            return

        try:
            response = requests.post(self.post_url, json=payload)
            if response.status_code < 200 or response.status_code >= 300:
                raise errors.DataOutConnectorSendUnsuccessfulError(
                    msg='Sending payload to GA did not complete successfully.',
                    error_num=errors.ErrorNameIDMap.
                    RETRIABLE_GA_HOOK_ERROR_HTTP_ERROR)
        except requests.ConnectionError:
            raise errors.DataOutConnectorSendUnsuccessfulError(
                msg='Sending payload to GA did not complete successfully.',
                error_num=errors.ErrorNameIDMap.
                RETRIABLE_GA_HOOK_ERROR_HTTP_ERROR)
Beispiel #2
0
    def send_hit(self,
                 payload: str,
                 user_agent: str = '',
                 send_type: SendTypes = SendTypes.SINGLE) -> None:
        """Sends hit via measurement protocol.

    Sends hit based on payload data.

    Args:
      payload: Contains payload data for hit.
      user_agent: User agent string injected in http request header.
      send_type: The hit request type; can be 'single' or 'batch'.

    Raises:
      DataOutConnectorSendUnsuccessfulError: If sending a hit to GA has failed.
    """
        url = self._get_hit_url(send_type.value)

        if self.dry_run:
            self.log.info('Dry Run Mode: Skipped sending the hit to GA.')
            return

        headers = {'User-Agent': user_agent} if user_agent else {}
        try:
            self._send_http_request(payload, url, headers)
        except googleapiclient_errors.HttpError as error:
            raise errors.DataOutConnectorSendUnsuccessfulError(
                error=error,
                msg='Sending a hit to GA has completed unsuccessfully.',
                error_num=errors.ErrorNameIDMap.
                RETRIABLE_GA_HOOK_ERROR_HTTP_ERROR)
Beispiel #3
0
    def add_members_to_user_list(self, user_list_id: int,
                                 payload: List[Dict[str, Any]]) -> None:
        """Adds new members to a Google Ads user list.

    Args:
      user_list_id: The ID of the user list to upload.
      payload: A batch of payload data that will be sent to AdWords API.

    Raises:
      DataOutConnectorAuthenticationError raised when authentication errors
      occurred.
      DataOutConnectorSendUnsuccessfulError if the member list uploaded haven't
      been processed successfully by the API.
    """
        service = self._get_service(ServiceType.ADWORDS_USER_LIST_SERVICE)
        mutate_members_operation = {
            'operand': {
                'userListId': user_list_id,
                'membersList': payload
            },
            'operator': 'ADD'
        }

        try:
            response = service.mutateMembers([mutate_members_operation])
        except (googleads_errors.GoogleAdsServerFault,
                google_auth_exceptions.RefreshError) as error:
            raise errors.DataOutConnectorAuthenticationError(
                error=error,
                msg=
                'Failed to add members to user list due to authentication error.',
                error_num=(errors.ErrorNameIDMap.
                           RETRIABLE_ERROR_OUTPUT_AUTHENTICATION_FAILED))

        try:
            if response['userLists'][0]['dataUploadResult'] == 'FAILURE':
                raise errors.DataOutConnectorSendUnsuccessfulError(
                    'Failed to add members to the user list.',
                    error_num=errors.ErrorNameIDMap.
                    RETRIABLE_ADS_HOOK_ERROR_FAIL_ADDING_MEMBERS_TO_USER_LIST)
        except (KeyError, IndexError):
            raise errors.DataOutConnectorSendUnsuccessfulError(
                'Failed to add members to the user list.',
                error_num=errors.ErrorNameIDMap.
                RETRIABLE_ADS_HOOK_ERROR_FAIL_ADDING_MEMBERS_TO_USER_LIST)
Beispiel #4
0
    def test_ads_cm_hook_send_events_contact_info_add_members_to_list(self):
        """Test hook send_events success with contact info payload."""
        hook = self.create_ads_cm_hook(create_list=True)
        hook.add_members_to_user_list.side_effect = (
            errors.DataOutConnectorSendUnsuccessfulError())
        blb = blob.Blob(events=[self.contact_info_event_email], location='')

        hook = self.create_ads_cm_hook()
        blb = hook.send_events(blb)

        self.assertListEqual([], blb.failed_events)
        hook.add_members_to_user_list.assert_called()