different header handling
There is a difference between the requests.Request.prepare() call and the requests.Session().send() call. I would like to explain a little:
When a requests.Session() is initialized, different default_headers are set ('Accept-Encoding', 'Accept' and 'Connection'). Such a session is also initialized by requests.get(). Then the custom_headers are merged with the default_headers. For the query of my URL it is important that 'Accept' and 'Connection' are set. However, calling Request.prepare() does not set these default_headers and calling requests.Session().send() overwrites any values already set (including the default_headers).
Expected Result
requests.Session() and requests.get() have the same headers
Actual Result
The default_headers are overwritten by requests.Session().send()
Reproduction Steps
import requests
resource = 'https://www.accuweather.com/en/de/hamburg/20095/biking-weather/178556'
method = 'GET'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
}
verify_ssl = True
timeout = 10
# this works fine
response = requests.get(resource, headers=headers, timeout=timeout)
# that causes an requests.exceptions.ReadTimeout
request = requests.Request(method, resource, headers=headers, auth=None, data=None).prepare()
with requests.Session() as sess:
response = sess.send(request, timeout=timeout, verify=verify_ssl)
# now this works fine again
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
'Accept': '*/*',
'Connection': 'keep-alive',
}
request = requests.Request(method, resource, headers=headers, auth=None, data=None).prepare()
with requests.Session() as sess:
response = sess.send(request, timeout=timeout, verify=verify_ssl)
System Information
$ python -m requests.help
{
"chardet": {
"version": "3.0.4"
},
"cryptography": {
"version": ""
},
"idna": {
"version": "2.6"
},
"implementation": {
"name": "CPython",
"version": "3.7.3"
},
"platform": {
"release": "5.0.0-27-generic",
"system": "Linux"
},
"pyOpenSSL": {
"openssl_version": "",
"version": null
},
"requests": {
"version": "2.21.0"
},
"system_ssl": {
"version": "1010102f"
},
"urllib3": {
"version": "1.24.1"
},
"using_pyopenssl": false
}
https://github.com/psf/requests/issues/5833 ended up being a more thorough discussion of this issue.