Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ To install the ``geoip2`` module, type:
.. code-block:: bash

$ pip install geoip2
$ pip install geoip2[aiohttp] # Install aiohttp as well
$ pip install geoip2[requests] # Install requests as well
Comment thread
akx marked this conversation as resolved.

If you are not able to install from PyPI, you may also use ``pip`` from the
source directory:
Expand Down
14 changes: 12 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ authors = [
{name = "Gregory Oschwald", email = "goschwald@maxmind.com"},
]
dependencies = [
"aiohttp>=3.14.1,<4.0.0",
"maxminddb>=3.0.0,<4.0.0",
"requests>=2.24.0,<3.0.0",
]
requires-python = ">=3.10"
readme = "README.rst"
Expand All @@ -30,6 +28,14 @@ classifiers = [
"Topic :: Internet :: Proxy Servers",
]

[project.optional-dependencies]
aiohttp = [
"aiohttp>=3.14.1,<4.0.0",
]
requests = [
"requests>=2.24.0,<3.0.0",
]

[dependency-groups]
dev = [
"pytest>=9.1.1",
Expand Down Expand Up @@ -115,6 +121,10 @@ commands = [
[tool.tox.env.lint]
description = "Code linting"
python = "3.14"
extras = [
"aiohttp",
"requests",
]
dependency_groups = [
"dev",
"lint",
Expand Down
39 changes: 25 additions & 14 deletions src/geoip2/webservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,18 @@
import json
from typing import TYPE_CHECKING, cast

import aiohttp
import aiohttp.http
import requests
import requests.utils
try:
import aiohttp
import aiohttp.http
except ImportError:
aiohttp = None # type: ignore[assignment]

try:
import requests
import requests.utils
except ImportError:
requests = None # type: ignore[assignment]
Comment thread
akx marked this conversation as resolved.


import geoip2
import geoip2.models
Expand All @@ -52,14 +60,6 @@
from geoip2.models import City, Country, Insights
from geoip2.types import IPAddress

_AIOHTTP_UA = (
f"GeoIP2-Python-Client/{geoip2.__version__} {aiohttp.http.SERVER_SOFTWARE}"
)

_REQUEST_UA = (
f"GeoIP2-Python-Client/{geoip2.__version__} {requests.utils.default_user_agent()}"
)


class BaseClient:
"""Base class for AsyncClient and Client."""
Expand Down Expand Up @@ -352,15 +352,23 @@ async def insights(self, ip_address: IPAddress = "me") -> Insights:
)

async def _session(self) -> aiohttp.ClientSession:
if aiohttp is None:
msg = "aiohttp is required for async mode; install `GeoIP2[aiohttp]`"
raise ImportError(msg)

if not hasattr(self, "_existing_session"):
user_agent = (
f"GeoIP2-Python-Client/{geoip2.__version__} "
f"{aiohttp.http.SERVER_SOFTWARE}"
)
self._existing_session = aiohttp.ClientSession(
headers={
"Accept": "application/json",
"Authorization": aiohttp.encode_basic_auth(
self._account_id,
self._license_key,
),
"User-Agent": _AIOHTTP_UA,
"User-Agent": user_agent,
},
timeout=aiohttp.ClientTimeout(total=self._timeout),
)
Expand Down Expand Up @@ -474,7 +482,10 @@ def __init__( # noqa: PLR0913
self._session = requests.Session()
self._session.auth = (self._account_id, self._license_key)
self._session.headers["Accept"] = "application/json"
self._session.headers["User-Agent"] = _REQUEST_UA
self._session.headers["User-Agent"] = (
f"GeoIP2-Python-Client/{geoip2.__version__}"
f" {requests.utils.default_user_agent()}"
)
if proxy is None:
self._proxies = None
else:
Expand Down
3 changes: 0 additions & 3 deletions tests/database_test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import datetime
import ipaddress
import sys
import unittest
from unittest.mock import MagicMock, patch

sys.path.append("..")

import maxminddb

import geoip2.database
Expand Down
3 changes: 0 additions & 3 deletions tests/models_test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import datetime
import ipaddress
import sys
import unittest
from typing import ClassVar

sys.path.append("..")

import geoip2.models


Expand Down
4 changes: 2 additions & 2 deletions tests/webservice_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import asyncio
import copy
import ipaddress
import sys
import unittest
from abc import ABC, abstractmethod
from collections import defaultdict
Expand All @@ -13,7 +12,6 @@
import pytest_httpserver
from pytest_httpserver import HeaderValueMatcher

sys.path.append("..")
import geoip2
from geoip2.errors import (
AddressNotFoundError,
Expand Down Expand Up @@ -405,6 +403,7 @@ class TestClient(TestBaseClient):
client: Client

def setUp(self) -> None:
pytest.importorskip("requests")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover missing-dependency behavior instead of only skipping it.

importorskip keeps core-only runs green, but skips every test that could exercise the new actionable ImportError path. Add focused tests that simulate missing aiohttp or requests and assert the installation guidance, while retaining these skips for HTTP integration tests.

Also applies to: 420-420

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/webservice_test.py` at line 406, Add focused tests in the relevant
webservice test cases to simulate missing aiohttp and requests imports, then
assert that the resulting ImportError contains the actionable installation
guidance. Keep the existing pytest.importorskip calls in the HTTP integration
tests so core-only environments continue to skip those tests.

self.client_class = Client
self.client = Client(42, "abcdef123456")
self.client._base_uri = self.httpserver.url_for("/geoip/v2.1") # noqa: SLF001
Expand All @@ -418,6 +417,7 @@ class TestAsyncClient(TestBaseClient):
client: AsyncClient

def setUp(self) -> None:
pytest.importorskip("aiohttp")
self._loop = asyncio.new_event_loop()
self.client_class = AsyncClient
self.client = AsyncClient(42, "abcdef123456")
Expand Down
13 changes: 10 additions & 3 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading