Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid override of headers by urllib3 when unset #1502

Merged
merged 3 commits into from
May 19, 2023
Merged
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
5 changes: 5 additions & 0 deletions httpie/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import requests
# noinspection PyPackageRequirements
import urllib3
from urllib3.util import SKIP_HEADER, SKIPPABLE_HEADERS

from . import __version__
from .adapters import HTTPieHTTPAdapter
Expand Down Expand Up @@ -200,6 +201,10 @@ def finalize_headers(headers: HTTPHeadersDict) -> HTTPHeadersDict:
if isinstance(value, str):
# See <https://github.com/httpie/httpie/issues/212>
value = value.encode()
elif name.lower() in SKIPPABLE_HEADERS:
# Some headers get overwritten by urllib3 when set to `None`
# and should be replaced with the `SKIP_HEADER` constant.
value = SKIP_HEADER
final_headers.add(name, value)
return final_headers

Expand Down
2 changes: 2 additions & 0 deletions httpie/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from time import monotonic

import requests
from urllib3.util import SKIP_HEADER, SKIPPABLE_HEADERS

from enum import Enum, auto
from typing import Iterable, Union, NamedTuple
Expand Down Expand Up @@ -152,6 +153,7 @@ def headers(self):
headers = [
f'{name}: {value if isinstance(value, str) else value.decode()}'
for name, value in headers.items()
if not (name.lower() in SKIPPABLE_HEADERS and value == SKIP_HEADER)
]

headers.insert(0, request_line)
Expand Down
8 changes: 8 additions & 0 deletions tests/test_httpie.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,14 @@ def test_unset_host_header(httpbin_both):
assert 'Host' not in r.json['headers'] # default Host unset


def test_unset_useragent_header(httpbin_both):
r = http('GET', httpbin_both + '/headers')
assert 'User-Agent' in r.json['headers'] # default User-Agent present

r = http('GET', httpbin_both + '/headers', 'User-Agent:')
assert 'User-Agent' not in r.json['headers'] # default User-Agent unset


def test_headers_empty_value(httpbin_both):
r = http('GET', httpbin_both + '/headers')
assert r.json['headers']['Accept'] # default Accept has value
Expand Down