Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Httpx adapter to be implemented #544

Open
novitae opened this issue Mar 13, 2023 · 0 comments
Open

Httpx adapter to be implemented #544

novitae opened this issue Mar 13, 2023 · 0 comments

Comments

@novitae
Copy link

novitae commented Mar 13, 2023

Hello, I just a made an async httpx geocoder since the aiohttp one is not working well (aio-libs/aiohttp#6239). I don't have the time to do all the pr stuff etc, so if someone wants to implement it, do it, here's the code:

from geopy.adapters import BaseAsyncAdapter, _normalize_proxies
import json

try:
    import httpx
    httpx_available = True
except ImportError:
    httpx_available = False

class AsyncHttpxAdapter(BaseAsyncAdapter):
    is_available = httpx_available

    def __init__(self, *, proxies, ssl_context):
        if not httpx_available:
            raise ImportError(
                "`httpx` must be installed in order to use AsyncHttpxAdapter. "
                "If you have installed geopy via pip, you may use "
                "this command to install httpx: "
                '`pip install httpx`.'
            )
        proxies = _normalize_proxies(proxies)
        super().__init__(proxies=proxies, ssl_context=ssl_context)

        self.proxies = proxies
        self.ssl_context = ssl_context

    @property
    def session(self):
        # Lazy session creation, which allows to avoid "unclosed socket"
        # warnings if a Geocoder instance is created without entering
        # async context and making any requests.
        session = self.__dict__.get("session")
        if session is None:
            session = httpx.AsyncClient(
                trust_env=False,  # don't use system proxies
            )
            self.__dict__["session"] = session
        return session

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.session.aclose()

    async def get_text(self, url, *, timeout, headers):
        response = await self.session.get(
            url,
            timeout=httpx.Timeout(timeout),
            headers=headers
        )
        return response.text
    
    async def get_json(self, *args, **kwargs):
        return json.loads(await self.get_text(*args, **kwargs))
@KostyaEsmukov KostyaEsmukov changed the title Httpx geocoder to be implemented Httpx adapter to be implemented Aug 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant