mondbaron / mvg

An unofficial interface to timetable information of the Münchner Verkehrsgesellschaft (MVG).
https://pypi.org/project/mvg
MIT License
18 stars 7 forks source link

Add proxy support #8

Open medlor opened 5 months ago

medlor commented 5 months ago

Hi,

thanks for your nice tool.

I am behind a proxy and currently your tool does not support it. This can be fixed by setting trust_env=True in aiohttp.ClientSession(trust_env=True).

A rather quick working fix is mentioned below.

    @staticmethod
    async def __api(base: Base, endpoint: Endpoint, args: dict[str, Any] | None = None) -> Any:
        """
        Call the API endpoint with the given arguments.

        :param base: the API base
        :param endpoint: the endpoint
        :param args: a dictionary containing arguments
        :raises MvgApiError: raised on communication failure or unexpected result
        :return: the response as JSON object
        """
        url = furl(base.value)
        url /= endpoint.value[0]
        url.set(query_params=args)

        try:
            async with aiohttp.ClientSession(trust_env=True if "https_proxy" in os.environ else False) as session:
                print(url.url)
                async with session.get(
                    url.url,
                ) as resp:
                    if resp.status != 200:
                        raise MvgApiError(f"Bad API call: Got response ({resp.status}) from {url.url}")
                    if resp.content_type != "application/json":
                        raise MvgApiError(f"Bad API call: Got content type {resp.content_type} from {url.url}")
                    return await resp.json()

        except aiohttp.ClientError as exc:
            raise MvgApiError(f"Bad API call: Got {str(type(exc))} from {url.url}") from exc

best regards