|
25 | 25 |
|
26 | 26 | """ |
27 | 27 |
|
| 28 | +from __future__ import annotations |
| 29 | + |
28 | 30 | import ipaddress |
29 | 31 | import json |
30 | 32 | from typing import Any, Dict, cast, List, Optional, Type, Union |
31 | 33 |
|
32 | | -import aiohttp |
33 | | -import aiohttp.http |
34 | | -import requests |
35 | | -import requests.utils |
| 34 | +try: |
| 35 | + import aiohttp |
| 36 | + import aiohttp.http |
| 37 | +except ImportError: |
| 38 | + aiohttp = None # type: ignore[assignment] |
| 39 | + |
| 40 | +try: |
| 41 | + import requests |
| 42 | + import requests.utils |
| 43 | +except ImportError: |
| 44 | + requests = None # type: ignore[assignment] |
| 45 | + |
36 | 46 |
|
37 | 47 | import geoip2 |
38 | 48 | import geoip2.models |
|
48 | 58 | from geoip2.models import City, Country, Insights |
49 | 59 | from geoip2.types import IPAddress |
50 | 60 |
|
51 | | -_AIOHTTP_UA = ( |
52 | | - f"GeoIP2-Python-Client/{geoip2.__version__} {aiohttp.http.SERVER_SOFTWARE}" |
53 | | -) |
54 | | - |
55 | | -_REQUEST_UA = ( |
56 | | - f"GeoIP2-Python-Client/{geoip2.__version__} {requests.utils.default_user_agent()}" |
57 | | -) |
58 | | - |
59 | 61 |
|
60 | 62 | class BaseClient: # pylint: disable=missing-class-docstring, too-few-public-methods |
61 | 63 | _account_id: str |
@@ -326,10 +328,19 @@ async def insights(self, ip_address: IPAddress = "me") -> Insights: |
326 | 328 | ) |
327 | 329 |
|
328 | 330 | async def _session(self) -> aiohttp.ClientSession: |
| 331 | + if aiohttp is None: |
| 332 | + raise ImportError( |
| 333 | + "aiohttp is required for async mode; install `GeoIP2[aiohttp]`" |
| 334 | + ) |
| 335 | + |
329 | 336 | if not hasattr(self, "_existing_session"): |
| 337 | + user_agent = ( |
| 338 | + f"GeoIP2-Python-Client/{geoip2.__version__} " |
| 339 | + f"{aiohttp.http.SERVER_SOFTWARE}" |
| 340 | + ) |
330 | 341 | self._existing_session = aiohttp.ClientSession( |
331 | 342 | auth=aiohttp.BasicAuth(self._account_id, self._license_key), |
332 | | - headers={"Accept": "application/json", "User-Agent": _AIOHTTP_UA}, |
| 343 | + headers={"Accept": "application/json", "User-Agent": user_agent}, |
333 | 344 | timeout=aiohttp.ClientTimeout(total=self._timeout), |
334 | 345 | ) |
335 | 346 |
|
@@ -436,7 +447,10 @@ def __init__( # pylint: disable=too-many-arguments |
436 | 447 | self._session = requests.Session() |
437 | 448 | self._session.auth = (self._account_id, self._license_key) |
438 | 449 | self._session.headers["Accept"] = "application/json" |
439 | | - self._session.headers["User-Agent"] = _REQUEST_UA |
| 450 | + self._session.headers["User-Agent"] = ( |
| 451 | + f"GeoIP2-Python-Client/{geoip2.__version__}" |
| 452 | + f" {requests.utils.default_user_agent()}" |
| 453 | + ) |
440 | 454 | if proxy is None: |
441 | 455 | self._proxies = None |
442 | 456 | else: |
|
0 commit comments