|
27 | 27 | import json |
28 | 28 | from typing import TYPE_CHECKING, cast |
29 | 29 |
|
30 | | -import aiohttp |
31 | | -import aiohttp.http |
32 | | -import requests |
33 | | -import requests.utils |
| 30 | +try: |
| 31 | + import aiohttp |
| 32 | + import aiohttp.http |
| 33 | +except ImportError: |
| 34 | + aiohttp = None # type: ignore[assignment] |
| 35 | + |
| 36 | +try: |
| 37 | + import requests |
| 38 | + import requests.utils |
| 39 | +except ImportError: |
| 40 | + requests = None # type: ignore[assignment] |
| 41 | + |
34 | 42 |
|
35 | 43 | import geoip2 |
36 | 44 | import geoip2.models |
|
52 | 60 | from geoip2.models import City, Country, Insights |
53 | 61 | from geoip2.types import IPAddress |
54 | 62 |
|
55 | | -_AIOHTTP_UA = ( |
56 | | - f"GeoIP2-Python-Client/{geoip2.__version__} {aiohttp.http.SERVER_SOFTWARE}" |
57 | | -) |
58 | | - |
59 | | -_REQUEST_UA = ( |
60 | | - f"GeoIP2-Python-Client/{geoip2.__version__} {requests.utils.default_user_agent()}" |
61 | | -) |
62 | | - |
63 | 63 |
|
64 | 64 | class BaseClient: |
65 | 65 | """Base class for AsyncClient and Client.""" |
@@ -352,15 +352,23 @@ async def insights(self, ip_address: IPAddress = "me") -> Insights: |
352 | 352 | ) |
353 | 353 |
|
354 | 354 | async def _session(self) -> aiohttp.ClientSession: |
| 355 | + if aiohttp is None: |
| 356 | + msg = "aiohttp is required for async mode; install `GeoIP2[aiohttp]`" |
| 357 | + raise ImportError(msg) |
| 358 | + |
355 | 359 | if not hasattr(self, "_existing_session"): |
| 360 | + user_agent = ( |
| 361 | + f"GeoIP2-Python-Client/{geoip2.__version__} " |
| 362 | + f"{aiohttp.http.SERVER_SOFTWARE}" |
| 363 | + ) |
356 | 364 | self._existing_session = aiohttp.ClientSession( |
357 | 365 | headers={ |
358 | 366 | "Accept": "application/json", |
359 | 367 | "Authorization": aiohttp.encode_basic_auth( |
360 | 368 | self._account_id, |
361 | 369 | self._license_key, |
362 | 370 | ), |
363 | | - "User-Agent": _AIOHTTP_UA, |
| 371 | + "User-Agent": user_agent, |
364 | 372 | }, |
365 | 373 | timeout=aiohttp.ClientTimeout(total=self._timeout), |
366 | 374 | ) |
@@ -474,7 +482,10 @@ def __init__( # noqa: PLR0913 |
474 | 482 | self._session = requests.Session() |
475 | 483 | self._session.auth = (self._account_id, self._license_key) |
476 | 484 | self._session.headers["Accept"] = "application/json" |
477 | | - self._session.headers["User-Agent"] = _REQUEST_UA |
| 485 | + self._session.headers["User-Agent"] = ( |
| 486 | + f"GeoIP2-Python-Client/{geoip2.__version__}" |
| 487 | + f" {requests.utils.default_user_agent()}" |
| 488 | + ) |
478 | 489 | if proxy is None: |
479 | 490 | self._proxies = None |
480 | 491 | else: |
|
0 commit comments