|
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,10 +352,19 @@ 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 | + raise ImportError( |
| 357 | + "aiohttp is required for async mode; install `GeoIP2[aiohttp]`" |
| 358 | + ) |
| 359 | + |
355 | 360 | if not hasattr(self, "_existing_session"):
|
| 361 | + user_agent = ( |
| 362 | + f"GeoIP2-Python-Client/{geoip2.__version__} " |
| 363 | + f"{aiohttp.http.SERVER_SOFTWARE}" |
| 364 | + ) |
356 | 365 | self._existing_session = aiohttp.ClientSession(
|
357 | 366 | auth=aiohttp.BasicAuth(self._account_id, self._license_key),
|
358 |
| - headers={"Accept": "application/json", "User-Agent": _AIOHTTP_UA}, |
| 367 | + headers={"Accept": "application/json", "User-Agent": user_agent}, |
359 | 368 | timeout=aiohttp.ClientTimeout(total=self._timeout),
|
360 | 369 | )
|
361 | 370 |
|
@@ -468,7 +477,10 @@ def __init__( # noqa: PLR0913
|
468 | 477 | self._session = requests.Session()
|
469 | 478 | self._session.auth = (self._account_id, self._license_key)
|
470 | 479 | self._session.headers["Accept"] = "application/json"
|
471 |
| - self._session.headers["User-Agent"] = _REQUEST_UA |
| 480 | + self._session.headers["User-Agent"] = ( |
| 481 | + f"GeoIP2-Python-Client/{geoip2.__version__}" |
| 482 | + f" {requests.utils.default_user_agent()}" |
| 483 | + ) |
472 | 484 | if proxy is None:
|
473 | 485 | self._proxies = None
|
474 | 486 | else:
|
|
0 commit comments