Example #1
0
 def create_engine(self, engine_name: str, source_engines=None):
     if source_engines:
         data = {"name": engine_name, "type": "meta", "source_engines": source_engines}
     else:
         data = {"name": engine_name, "language": ENGINE_LANGUAGE}
     response = requests.post(self.engines_url, headers=self.headers, json=data)
     return response
Example #2
0
        def make_post_request(api: BatchAPI) -> None:
            try:
                response = requests.post(
                    f"{settings.BATCH_API_URL}/1.1/{api.value}/transactional/send",
                    headers=self.headers,
                    json={
                        "group_id": notification_data.group_id,
                        "recipients": {
                            "custom_ids": [
                                str(user_id)
                                for user_id in notification_data.user_ids
                            ]
                        },
                        "message": {
                            "title": notification_data.message.title,
                            "body": notification_data.message.body,
                        },
                        **notification_data.extra,
                    },
                )
            except Exception as exc:  # pylint: disable=broad-except
                logger.exception(
                    "Error with Batch Transactional API trying to send group_id=%s notification to users with ids=%s: %s",
                    notification_data.group_id,
                    notification_data.user_ids,
                    exc,
                )
                return

            if not response.ok:
                logger.error(
                    "Got %d status code from Batch Transactional API: content=%s",
                    response.status_code,
                    response.content,
                )
Example #3
0
def get_token_validation_and_score(token: str) -> dict:
    params = {"secret": settings.RECAPTCHA_SECRET, "response": token}
    api_response = requests.post(settings.RECAPTCHA_API_URL, data=params)
    json_response = api_response.json()

    return {
        "success": json_response.get("success"),
        "error-codes": json_response.get("error-codes", []),
        "score": json_response.get("score", 0),
        "action": json_response.get("action", ""),
    }
Example #4
0
 def create_or_update_documents(self, documents: Iterable[dict]) -> None:
     # Error handling is done by the caller.
     for engine_name, batch in get_batches(documents, self.engine_selector, size=DOCUMENTS_PER_REQUEST_LIMIT):
         data = json.dumps(batch, cls=AppSearchJsonEncoder)
         response = requests.post(self.get_documents_url(engine_name), headers=self.headers, data=data)
         response.raise_for_status()
         # Except here when App Search returns a 200 OK response
         # even if *some* documents cannot be processed. In that
         # case we log it here. It denotes a bug on our side: type
         # mismatch on a field, bogus JSON serialization, etc.
         response_data = response.json()
         errors = [item for item in response_data if item["errors"]]
         if errors:
             logger.error("Some documents could not be indexed, possible typing bug", extra={"errors": errors})
def log_user_becomes_beneficiary_event_job(user_id: int) -> None:
    user = User.query.get(user_id)

    if "apps_flyer" not in user.externalIds:
        raise AppsFlyerMissingError("user has no apps flyer information")

    user_apps_flyer = user.externalIds["apps_flyer"]
    context = AppsFlyerContext(apps_flyer_user_id=user_apps_flyer["user"],
                               platform=user_apps_flyer["platform"])

    base = APPS_FLYER_API_URL.strip("/")
    resource = context.get_app_id().strip("/")
    url = f"{base}/{resource}"

    headers = {
        "authentication": context.get_api_key(),
        "Content-Type": "application/json"
    }
    data = {
        "customer_user_id": str(user.id),
        "appsflyer_id": context.apps_flyer_user_id,
        "eventName": "af_complete_beneficiary_registration",
        "eventValue": {
            "af_user_id": str(user.id)
        },
    }

    try:
        response = requests.post(url, headers=headers, json=data)
    except (ConnectionError, RequestException) as error:
        extra_infos = {
            "user": user.id,
            "user.apps_flyer_id": context.apps_flyer_user_id,
            "error": str(error)
        }
        logger.error("[APPS FLYER][BECOMES BENEFICIARY] request failed",
                     extra=extra_infos)
        return

    if response.status_code != 200:
        extra_infos = {
            "user": user.id,
            "user.apps_flyer_id": context.apps_flyer_user_id,
            "code": response.status_code,
            "text": response.text,
        }
        logger.error(
            "[APPS FLYER][BECOMES BENEFICIARY] request returned an error",
            extra=extra_infos)
Example #6
0
        def make_post_request(api: BatchAPI) -> None:
            try:
                response = requests.post(
                    f"{settings.BATCH_API_URL}/1.0/{api.value}/data/users/",
                    headers=self.headers,
                    json=[payload_template(user) for user in users_data],
                )
            except Exception as exc:  # pylint: disable=broad-except
                logger.exception(
                    "Error with Batch Custom Data API trying to update attributes of users: %s",
                    exc)
                return

            if not response.ok:
                logger.error(
                    "Got %d status code from Batch Custom Data API (batch update): content=%s",
                    response.status_code,
                    response.content,
                )
Example #7
0
    def update_user_attributes_with_legacy_internal_task(
            self, user_id: int, attribute_values: dict) -> None:
        for api in (BatchAPI.ANDROID, BatchAPI.IOS):
            try:
                response = requests.post(
                    f"{settings.BATCH_API_URL}/1.0/{api.value}/data/users/{user_id}",
                    headers=self.headers,
                    json={
                        "overwrite": False,
                        "values": attribute_values
                    },
                )
            except Exception as exc:  # pylint: disable=broad-except
                logger.exception(
                    "Error with Batch Custom Data API trying to update attributes of user with id %s: %s",
                    user_id, exc)
                return

            if not response.ok:
                logger.error(
                    "Got %d status code from Batch Custom Data API: content=%s",
                    response.status_code, response.content)
Example #8
0
 def update_synonyms(self, engine_name: str):
     url = self.get_synonyms_url(engine_name)
     for synonym_set in self.synonyms:
         data = {"synonyms": list(synonym_set)}
         response = requests.post(url, headers=self.headers, json=data)
         yield response
Example #9
0
 def update_schema(self, engine_name: str):
     response = requests.post(self.get_schema_url(engine_name), headers=self.headers, json=self.schema)
     return response