Skip to content

Stop calling the deprecated Headers.to_unicode_dict() - #405

Open
viren-ramani wants to merge 1 commit into
scrapy-plugins:mainfrom
viren-ramani:stop-deprecated-to-unicode-dict
Open

viren-ramani wants to merge 1 commit into
scrapy-plugins:mainfrom
viren-ramani:stop-deprecated-to-unicode-dict

Conversation

@viren-ramani

Copy link
Copy Markdown

Scrapy 2.20 deprecated Headers.to_unicode_dict() in favour of to_tuple_list(). use_scrapy_headers() calls it for every request, so with Scrapy 2.20+ each request logs:

ScrapyDeprecationWarning: Headers.to_unicode_dict() is deprecated, use to_tuple_list() instead.

to_tuple_list() was added in Scrapy 2.15, so it is used from 2.15 on, and older versions keep calling to_unicode_dict(), which does not warn there.

to_tuple_list() is not a drop-in replacement, so the dict is rebuilt to match what to_unicode_dict() returned:

  • Repeated headers are joined into one value with ,.
  • Lookups are case-insensitive. The function looks up user-agent, referer and host, while Scrapy stores User-Agent and so on. Scrapy's CaseInsensitiveDict cannot be reused because scrapy.utils.datatypes is deprecated in 2.20 too, so headers.py has a small private equivalent.
  • Headers without values are kept with an empty value. to_tuple_list() skips them, which would change what is sent for headers={"User-Agent": None}: Chromium currently gets an empty User-Agent, and would get the browser's one instead.

The new tests call use_scrapy_headers() directly. test_no_deprecation_warning turns ScrapyDeprecationWarning into an error and fails without the change, with the warning above. The others cover merging, case-insensitive lookups, headers without values and header order, and pass both before and after the change.

Verified locally with Python 3.11 on macOS arm64:

  • tox -e py (Scrapy 2.20): 158 passed, 10 skipped, 2 failed. The 2 failures (TestBodyEncoding, 'gbk' == 'gb18030' with w3lib 2.6.0) also fail on main.
  • tox -e py-pinned (Scrapy 2.7): the new tests pass, and the other results match main.
  • black, flake8, typing and bandit are clean. pylint only reports the existing test_extensions.py:75 E1101, which main has too.

Scrapy 2.20 deprecated Headers.to_unicode_dict() in favour of
to_tuple_list(), so use_scrapy_headers() logged a
ScrapyDeprecationWarning for every request.

On Scrapy 2.15+, where to_tuple_list() exists, build the same
case-insensitive dict from it; older versions keep using
to_unicode_dict(), which does not warn there. Behaviour is unchanged:
repeated headers are still joined with ",", headers without values
(e.g. User-Agent: None) are still kept as empty strings, and header
order is preserved.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant