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
4 changes: 4 additions & 0 deletions docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 2 additions & 4 deletions src/crawlee/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
5 changes: 3 additions & 2 deletions src/crawlee/_utils/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
25 changes: 25 additions & 0 deletions tests/integration/http_clients/test_http_clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -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''
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/_utils/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'})
Expand Down
8 changes: 7 additions & 1 deletion tests/unit/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest

from crawlee import ConcurrencySettings
from crawlee import ConcurrencySettings, HttpHeaders


@pytest.mark.parametrize(
Expand Down Expand Up @@ -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']
Loading