diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index 32458e2838..cbb5447a64 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -980,6 +980,10 @@ In v1, `ImpitHttpClient` and `CurlImpersonateHttpClient` disabled the timeout wh The `headers` argument of a client still applies to every request. Its `Authorization`, `Proxy-Authorization` and `Cookie` headers are dropped when a redirect leaves the origin, the same as the headers passed with a request. With `HttpxHttpClient`, the headers of the client now win over the generated browser headers. In v1, the generated browser headers replaced them. +### Headers keep their order + +`HttpHeaders` keeps the headers in the order they were passed. In v1, it sorted them by name. `HttpxHttpClient` sends the headers passed with a request in that order after the generated browser headers, and a passed header that is also generated keeps the generated header's position. `CurlImpersonateHttpClient` sends them in that order after the headers of the impersonated browser, and a passed header that the browser also sends keeps the browser's position. `ImpitHttpClient` sends the passed headers in an order of its own. + ### A `Cookie` header is merged with the session cookies A `Cookie` header passed with a request or set on the client is merged with the session cookies while the redirect chain stays on its origin. A cookie in the header wins over a session cookie of the same name and isn't stored in the session. In v1, a `Cookie` header passed with a request replaced the session cookies with `ImpitHttpClient`, `HttpxHttpClient` and `context.send_request` of `PlaywrightCrawler`, so an empty `Cookie` header kept them out. `CurlImpersonateHttpClient` sent the session cookies in a second `Cookie` header. diff --git a/src/crawlee/_types.py b/src/crawlee/_types.py index bc69c1d8a7..e4bbaac998 100644 --- a/src/crawlee/_types.py +++ b/src/crawlee/_types.py @@ -51,10 +51,8 @@ def _normalize_headers(headers: Mapping[str, str]) -> dict[str, str]: - """Convert all header keys to lowercase, strips whitespace, and returns them sorted by key.""" - normalized_headers = {k.lower().strip(): v.strip() for k, v in headers.items()} - sorted_headers = sorted(normalized_headers.items()) - return dict(sorted_headers) + """Convert all header keys to lowercase and strip whitespace, keeping the order of the headers.""" + return {k.lower().strip(): v.strip() for k, v in headers.items()} @docs_group('Other') diff --git a/src/crawlee/_utils/requests.py b/src/crawlee/_utils/requests.py index 39d3fdcea5..67e2f5bd40 100644 --- a/src/crawlee/_utils/requests.py +++ b/src/crawlee/_utils/requests.py @@ -127,7 +127,8 @@ def _get_headers_hash(headers: HttpHeaders | None) -> str: if headers is None: normalized_headers = b'' else: - filtered_headers = {key: value for key, value in headers.items() if key in whitelisted_headers} - normalized_headers = '|'.join(f'{k}:{v}' for k, v in filtered_headers.items()).encode('utf-8') + # Sorted, so that the same headers in a different order give the same unique key. + filtered_headers = sorted((key, value) for key, value in headers.items() if key in whitelisted_headers) + normalized_headers = '|'.join(f'{k}:{v}' for k, v in filtered_headers).encode('utf-8') return compute_short_hash(normalized_headers) diff --git a/tests/integration/http_clients/test_http_clients.py b/tests/integration/http_clients/test_http_clients.py index cea01f0915..0300592b71 100644 --- a/tests/integration/http_clients/test_http_clients.py +++ b/tests/integration/http_clients/test_http_clients.py @@ -247,6 +247,31 @@ async def test_body_headers_dropped(http_client: HttpClient, server_url: URL) -> assert headers['x-custom'] == 'kept' +@pytest.mark.parametrize( + 'http_client', + [ + pytest.param('httpx', id='httpx'), + pytest.param('curl', id='curl'), + pytest.param( + 'impit', + id='impit', + marks=pytest.mark.skip(reason='`impit` sends the passed headers in a random order of its own.'), + ), + ], + indirect=True, +) +async def test_headers_sent_in_given_order(http_client: HttpClient, server_url: URL) -> None: + """Test that the client sends custom headers in the order they were given.""" + async with await http_client.send_request( + str(server_url / 'headers'), + headers={'x-zeta': '1', 'x-alpha': '2', 'x-mid': '3'}, + ) as response: + headers = await read_json(response) + + custom_headers = [name for name in headers if name.startswith('x-')] + assert custom_headers == ['x-zeta', 'x-alpha', 'x-mid'] + + async def test_read_stream(http_client: HttpClient, server_url: URL) -> None: """Test that `read_stream` yields the whole body.""" content_body: bytes = b'' diff --git a/tests/unit/_utils/test_requests.py b/tests/unit/_utils/test_requests.py index d93e10696d..909bca5c47 100644 --- a/tests/unit/_utils/test_requests.py +++ b/tests/unit/_utils/test_requests.py @@ -141,6 +141,17 @@ def test_compute_unique_key_handles_headers() -> None: assert uk == extended_uk_expected +def test_compute_unique_key_ignores_header_order() -> None: + """Test that the extended unique key doesn't depend on the order of the headers.""" + url = 'https://crawlee.dev' + headers = HttpHeaders({'Accept': '*/*', 'Content-Type': 'application/json'}) + reversed_headers = HttpHeaders({'Content-Type': 'application/json', 'Accept': '*/*'}) + + uk = compute_unique_key(url, headers=headers, use_extended_unique_key=True) + reversed_uk = compute_unique_key(url, headers=reversed_headers, use_extended_unique_key=True) + assert uk == reversed_uk + + def test_compute_unique_key_complex() -> None: url = 'https://crawlee.dev' headers = HttpHeaders({'Accept': '*/*', 'Content-Type': 'application/json'}) diff --git a/tests/unit/test_types.py b/tests/unit/test_types.py index c923c7e80a..3b28c6cb24 100644 --- a/tests/unit/test_types.py +++ b/tests/unit/test_types.py @@ -2,7 +2,7 @@ import pytest -from crawlee import ConcurrencySettings +from crawlee import ConcurrencySettings, HttpHeaders @pytest.mark.parametrize( @@ -41,3 +41,9 @@ def test_concurrency_settings_explicit_desired_concurrency_out_of_bounds(kwargs: """Test that an explicitly passed `desired_concurrency` outside the min/max bounds raises `ValueError`.""" with pytest.raises(ValueError, match=match): ConcurrencySettings(**kwargs) + + +def test_http_headers_keep_insertion_order() -> None: + """Test that `HttpHeaders` keeps the headers in the order they were passed.""" + headers = HttpHeaders({'User-Agent': 'agent', 'Accept': '*/*', 'Cookie': 'a=1'}) + assert list(headers) == ['user-agent', 'accept', 'cookie']