Ejemplo n.º 1
0
def get_distant_image(
    url: str,
    accepted_types: tuple = ACCEPTED_THUMBNAIL_FORMATS,
    max_size: int = MAX_THUMBNAIL_SIZE,
) -> bytes:
    try:
        streaming_response = pcapi_requests.get(
            url,
            timeout=DISTANT_IMAGE_REQUEST_TIMEOUT,
            stream=True,
            log_at_error_level=False)
        streaming_response.raise_for_status()
    except Exception:
        raise exceptions.FailureToRetrieve()

    # These two headers are recommended to be included by the server, but they could be missing
    content_type = streaming_response.headers.get("Content-Type", "")
    if content_type and content_type.lstrip("image/") not in accepted_types:
        raise exceptions.UnacceptedFileType(accepted_types=accepted_types)

    content_length = streaming_response.headers.get("Content-Length", 0)
    if int(content_length) > max_size:
        raise exceptions.FileSizeExceeded(max_size=max_size)

    response_content = b""
    for chunk in streaming_response.iter_content(CHUNK_SIZE_IN_BYTES):
        response_content += chunk
        if len(response_content) > max_size:
            streaming_response.close()
            raise exceptions.FileSizeExceeded(max_size=max_size)
    return response_content
Ejemplo n.º 2
0
    def stocks(self,
               siret: str,
               last_processed_reference: str = "",
               modified_since: str = "",
               limit: int = 1000) -> dict:
        api_url = self._build_local_provider_url(siret)
        params = self._build_local_provider_params(last_processed_reference,
                                                   modified_since, limit)
        headers = {}

        if self.authentication_token is not None:
            headers = {"Authorization": f"Basic {self.authentication_token}"}

        response = requests.get(
            url=api_url,
            params=params,
            headers=headers,
            timeout=REQUEST_TIMEOUT_FOR_PROVIDERS_IN_SECOND)

        if response.status_code != 200:
            raise ProviderAPIException(
                f"Error {response.status_code} when getting {self.name} stocks for SIRET: {siret}"
            )

        if not response.content:
            return {}

        return response.json()
Ejemplo n.º 3
0
def get_movie_poster_from_allocine(poster_url: str) -> bytes:
    api_response = requests.get(poster_url)

    if api_response.status_code != 200:
        raise AllocineException(
            f"Error getting API Allocine movie poster {poster_url}"
            f" with code {api_response.status_code}")

    return api_response.content
Ejemplo n.º 4
0
    def is_siret_registered(self, siret: str) -> bool:
        api_url = self._build_local_provider_url(siret)
        headers = {}

        if self.authentication_token is not None:
            headers = {"Authorization": f"Basic {self.authentication_token}"}

        response = requests.get(url=api_url, headers=headers, timeout=REQUEST_TIMEOUT_FOR_PROVIDERS_IN_SECOND)

        return response.status_code == 200
Ejemplo n.º 5
0
def get_application_details(application_id: int, procedure_id: int,
                            token: str) -> dict:
    response = requests.get(
        f"https://www.demarches-simplifiees.fr/api/v1/procedures/{procedure_id}/dossiers/{application_id}?token={token}"
    )

    if response.status_code != 200:
        raise ApiDemarchesSimplifieesException(
            f"Error getting API démarches simplifiées DATA for procedure_id: {procedure_id}, application_id: {application_id} and token {token}"
        )

    return response.json()
Ejemplo n.º 6
0
def get_all_applications_for_procedure(procedure_id: int,
                                       token: str,
                                       page: int = 1,
                                       results_per_page: int = 100) -> dict:
    response = requests.get(
        f"https://www.demarches-simplifiees.fr/api/v1/procedures/{procedure_id}/dossiers?token={token}&page={page}&resultats_par_page={results_per_page}"
    )

    if response.status_code != 200:
        raise ApiDemarchesSimplifieesException(
            f"Error getting API démarches simplifiées DATA for procedure_id: {procedure_id} and token {token}"
        )

    return response.json()
Ejemplo n.º 7
0
def get_movies_showtimes_from_allocine(api_key: str, theater_id: str) -> dict:
    api_url = f"https://graph-api-proxy.allocine.fr/api/query/movieShowtimeList?token={api_key}&theater={theater_id}"

    try:
        api_response = requests.get(api_url)
    except Exception:
        raise AllocineException(
            f"Error connecting Allocine API for theater {theater_id}")

    if api_response.status_code != 200:
        raise AllocineException(
            f"Error getting API Allocine DATA for theater {theater_id}")

    return api_response.json()
Ejemplo n.º 8
0
 def delete_all_documents(self) -> None:
     if settings.IS_PROD:
         raise ValueError("You cannot delete all documents on production.")
     # As of 2021-07-16, there is no endpoint to delete all
     # documents. We need to fetch all documents.
     # Error handling is done by the caller.
     list_url = self.get_documents_url(self.meta_engine_name) + "/list"
     page = 1
     while True:
         page_data = {"page": {"page": page, "size": DOCUMENTS_PER_REQUEST_LIMIT}}
         response = requests.get(list_url, headers=self.headers, json=page_data)
         document_ids = [int(document["id"].split("|")[-1]) for document in response.json()["results"]]
         if not document_ids:
             break
         self.delete_documents(document_ids)
         page += 1
Ejemplo n.º 9
0
def get_by_offerer(offerer: "Offerer") -> dict:
    response = requests.get(
        f"https://entreprise.data.gouv.fr/api/sirene/v3/unites_legales/{offerer.siren}",
        verify=False)

    if response.status_code != 200:
        raise ApiEntrepriseException(
            "Error getting API entreprise DATA for SIREN : {}".format(
                offerer.siren))

    response_json = response.json()
    etablissements = response_json["unite_legale"].pop("etablissements")
    response_json["other_etablissements_sirets"] = []
    response_json[
        "other_etablissements_sirets"] = _extract_etablissements_communs_siren(
            etablissements)
    return response_json
def _fetch_image(url: str) -> bytes:
    if not url[0:4] == "http":
        raise ValueError("Invalid URL: %s" % url)

    try:
        response = requests.get(url)
    except Exception as error:
        logger.exception("Could not download image at %s: %s", url, error)
        raise ApiErrors({"thumbUrl": ["Impossible de télécharger l'image à cette adresse"]})

    content_type = response.headers.get("Content-type", "")
    if response.status_code != 200 or not content_type.startswith("image/"):
        raise ValueError(
            "Got status_code=%s, content_type=%s when downloading thumb from url=%s"
            % (response.status_code, content_type, url)
        )

    return response.content
Ejemplo n.º 11
0
def get_institutional_project_redactor_by_email(
        email: str) -> InstitutionalProjectRedactorResponse:
    api_url = f"{settings.ADAGE_API_URL}/v1/redacteur-projet/{email}"

    api_response = requests.get(
        api_url,
        headers={
            "X-omogen-api-key": settings.ADAGE_API_KEY,
        },
    )

    if api_response.status_code == 404:
        raise InstitutionalProjectRedactorNotFoundException(
            "Requested email is not a known Project Redactor for Adage")
    if api_response.status_code != 200:
        raise AdageException("Error getting Adage API",
                             api_response.status_code, api_response.text)

    return InstitutionalProjectRedactorResponse.parse_obj(api_response.json())
Ejemplo n.º 12
0
    def is_siret_registered(self, siret: str) -> bool:
        api_url = self._build_local_provider_url(siret)
        headers = {}

        if self.authentication_token is not None:
            headers = {"Authorization": f"Basic {self.authentication_token}"}

        try:
            response = requests.get(
                url=api_url,
                headers=headers,
                timeout=REQUEST_TIMEOUT_FOR_PROVIDERS_IN_SECOND)
        except RequestException as error:
            extra_infos = {
                "siret": siret,
                "api_url": self.api_url,
                "error": str(error)
            }
            logger.exception("[PROVIDER] request failed", extra=extra_infos)
            raise ConnexionToProviderApiFailed

        return response.status_code == 200