Raibek/requests-github-issues huggingface dataset:
catch FileNotFoundError if there aren't any certificates

<!-- Summary. -->
I set verify to False, but it still need cerfiticate.
As we have catched ImportError, why not catch FileNotFoundError together?
## Expected Result
won't Traceback
<!-- What you expected. -->

## Actual Result
```
[root@localhost requests]# ./test-requests.py
Traceback (most recent call last):
  File "/root/test/requests/./test-requests.py", line 2, in <module>
    import requests
  File "/usr/lib/python3.9/site-packages/requests/__init__.py", line 136, in <module>
    from .api import request, get, head, post, patch, put, delete, options
  File "/usr/lib/python3.9/site-packages/requests/api.py", line 13, in <module>
    from . import sessions
  File "/usr/lib/python3.9/site-packages/requests/sessions.py", line 28, in <module>
    from .adapters import HTTPAdapter
  File "/usr/lib/python3.9/site-packages/requests/adapters.py", line 65, in <module>
    _preloaded_ssl_context.load_verify_locations(
FileNotFoundError: [Errno 2] No such file or directory
```
<!-- What happened instead. -->

## Reproduction Steps
```
#!/usr/bin/python3
import requests
r = requests.get("http://127.0.0.1",verify=False)
print(r.text)
```


<!-- This command is only available on Requests v2.16.4 and greater. Otherwise,
please provide some basic information about your system (Python version,
operating system, &c). -->


Hi @eaglegai, `certifi` is a [declared dependency](https://github.com/psf/requests/blob/0e322af87745eff34caffe4df68456ebc20d9068/setup.py#L65) of Requests. This should be available in all installations. We derive the the [`DEFAULT_CA_BUNDLE_PATH`](https://github.com/psf/requests/blob/0e322af87745eff34caffe4df68456ebc20d9068/src/requests/utils.py#L63) being used in this line from `requests.certs.where()`.

Can you confirm you 1.) have `certifi` installed and 2.) the value of `import requests; requests.certs.where()`?

Hi @nateprewitt , we build a mini environment which cut off the unnecessary packages,
and in this env, we just `import requests `for `http://` and `verify is false` is enough.
It's not reasonable to force to load the certificates by default, because it's not necessary in the case that verify is false.

As we consider the case that isn't built with the ssl module, why not consider the situation that 'verify is false' needn't certificates.
Unclear file handling in documentation examples

In the Requests documentation section on posting multiple multipart-encoded files (https://requests.readthedocs.io/en/latest/user/advanced/#post-multiple-multipart-encoded-files), the files are opened but not explicitly closed:

```
url = 'https://httpbin.org/post'

multiple_files = [

    ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),

    ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]

r = requests.post(url, files=multiple_files)

r.text
{
  ...
  'files': {'images': 'data:image/png;base64,iVBORw ....'}
  'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',
  ...
}
```

Does the library internally close the file handle during the post request? 

After trying some simple examples, I found that the file does not close automatically. Would it be worth considering a mention in the documentation that users should close the file, or perhaps updating the example to demonstrate this scenario?

Is it necessary to mention every possible best practice a person must follow when writing python in any section of the documentation? I really don't believe we must explain that as people should already be able to understand best practices around managing open files.

What made you assume requests would close the file for you? Why did that seem like a reasonable assumption? 

When I was reading the documentation, it wasn't clear to me what the library exactly did with the file after passing it. After testing it out, I understood better and felt this might be a question other developers would ask too. I do get that this could make the examples a bit less straightforward, though. Thanks for taking the time to respond to me.
ValueError: Timeout value connect was <object object at 0x7c6b5e484a80>, but it must be an int, float or None.

I use google-cloud-bigquery==3.12.0 which uses requests.
requests and urllib3 are pined.
requests==2.31.0
urllib3==1.26.18

I get this problem:
```
  File "/usr/local/lib/python3.10/site-packages/google/api_core/future/polling.py", line 282, in exception
    self._blocking_poll(timeout=timeout)
  File "/usr/local/lib/python3.10/site-packages/google/cloud/bigquery/job/query.py", line 1318, in _blocking_poll
    super(QueryJob, self)._blocking_poll(timeout=timeout, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/google/api_core/future/polling.py", line 137, in _blocking_poll
    polling(self._done_or_raise)(retry=retry)
  File "/usr/local/lib/python3.10/site-packages/google/api_core/retry.py", line 366, in retry_wrapped_func
    return retry_target(
  File "/usr/local/lib/python3.10/site-packages/google/api_core/retry.py", line 204, in retry_target
    return target()
  File "/usr/local/lib/python3.10/site-packages/google/cloud/bigquery/job/query.py", line 1460, in _done_or_raise
    self.reload(retry=retry, timeout=transport_timeout)
  File "/usr/local/lib/python3.10/site-packages/google/cloud/bigquery/job/base.py", line 781, in reload
    api_response = client._call_api(
  File "/usr/local/lib/python3.10/site-packages/google/cloud/bigquery/client.py", line 816, in _call_api
    return call()
  File "/usr/local/lib/python3.10/site-packages/google/cloud/_http/__init__.py", line 482, in api_request
    response = self._make_request(
  File "/usr/local/lib/python3.10/site-packages/google/cloud/_http/__init__.py", line 341, in _make_request
    return self._do_request(
  File "/usr/local/lib/python3.10/site-packages/google/cloud/_http/__init__.py", line 379, in _do_request
    return self.http.request(
  File "/usr/local/lib/python3.10/site-packages/google/auth/transport/requests.py", line 542, in request
    response = super(AuthorizedSession, self).request(
  File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.10/site-packages/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/requests/adapters.py", line 483, in send
    timeout = TimeoutSauce(connect=timeout, read=timeout)
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/timeout.py", line 102, in __init__
    self._connect = self._validate_timeout(connect, "connect")
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/timeout.py", line 147, in _validate_timeout
    raise ValueError(
ValueError: Timeout value connect was <object object at 0x7c6b5e484a80>, but it must be an int, float or None.
```


This seems to be an issue with what the Google libraries are passing into requests and which we then pass on to urllib3. Raise a bug with Google.
requests library seems to ignore "Transfer-Encoding" header

I want to send a request with "Transfer-Encoding:chunked" but somehow the header is never set.
Below is my code for testing and the corresponding captured request.
```
import requests

url = 'http://[replaced]/test.php'

def data_chunks():
    yield b'8\r\n'
    yield b'search=1\r\n'
    yield b'0\r\n'

response = requests.post(url,data=data_chunks(), headers={"Content-Type":"application/x-www-form-urlencoded","Transfer-Encoding":"chunked"}, proxies={"http":"http://127.0.0.1:8080"})
```

> POST /test.php HTTP/1.1
> Host: [replaced]
> User-Agent: python-requests/2.28.1
> Accept-Encoding: gzip, deflate
> Accept: */*
> Connection: close
> Content-Type: application/x-www-form-urlencoded
> Content-Length: 16
> 
> 8
> search=1
> 0

If I do not set the "Transfer-Encoding" header it is not used and even if I explicitly set the "Transfer-Encoding" header it is not used. The requests library always seems to put a "Content-Length" instead. 
What am I supposed to do?

As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)
inconsistent handling of verify and REQUESTS_CA_BUNDLE

The interaction between the `verify`  parameter and REQUESTS_CA_BUNDLE is inconsistent when using a `Session`. 

Assuming the REQUESTS_CA_BUNDLE  environment variable is set.

will NOT result in ssl verification:
```
sess = requests.Session()
sess.get("https://illegalcert.com", verify=False)
```
will verify the ssl verification:
```
sess = requests.Session()
sess.verify = False
sess.get("https://illegalcert.com")
```

## Expected Result
I would expect both scenario's not to verify the ssl certificate. 

## Actual Result
When session.verify is set to False, it is overruled by the existence of the REQUESTS_CA_BUNDLE environment variable. 

## Reproduction Steps

export REQUESTS_CA_BUNDLE=/path/to/ca
```python
sess = requests.Session()

# Will not verify the ssl certificate
sess.get("https://illegalcert.com", verify=False)

# will verify the ssl certificate
sess.verify = False
sess.get("https://illegalcert.com")
```

This is governed by:  https://github.com/psf/requests/blob/0e322af87745eff34caffe4df68456ebc20d9068/src/requests/sessions.py#L766

## System Information

    $ python -m requests.help

```json
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.3.2"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.6"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.11.6"
  },
  "platform": {
    "release": "5.15.146.1-microsoft-standard-WSL2",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.31.0"
  },
  "system_ssl": {
    "version": "30000020"
  },
  "urllib3": {
    "version": "2.2.1"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}
```



In the future, please search **closed and** open issues before creating new ones that are duplicates.
auth headers lost when requests process redirected requests

auth headers lost when requests process redirected requests
```python
def print_request_info(response, *args, **kwargs):
    request = response.request
    print(f"Request URL: {request.url}")
    print(f"Request Headers: {request.headers}")
    print(f"Request Data: {request.body}")
    print(f"Response Status Code: {response.status_code}")
    print(f"Response Headers: {response.headers}")
    print(f"Response Text: {response.text}")

response = requests.put(
                self.url,
                headers=headers,
                data=json_data,
                auth=self.auth,
                timeout=100,
                hooks={"response": print_request_info},
            )
```

## Expected Result
request headers
```python
{'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'format': 'json', 'Expect': '100-continue', 'strip_outer_array': 'true', 'Content-Length': '2305', 'Authorization': 'Basic xxxxx'}
```
Response Status Code: 307

redirected headers
```python
{'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'format': 'json', 'Expect': '100-continue', 'strip_outer_array': 'true', 'Content-Length': '2305'}
```

## Actual Result
redirected headers contains `Authorization`

## Reproduction Steps

```python
import requests

```

## System Information

    $ python -m requests.help

```json
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "2.0.12"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.3"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.6.8"
  },
  "platform": {
    "release": "5.4.119-1-tlinux4-0010.1",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.27.1"
  },
  "system_ssl": {
    "version": "100020bf"
  },
  "urllib3": {
    "version": "1.26.9"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}
```

<!-- This command is only available on Requests v2.16.4 and greater. Otherwise,
please provide some basic information about your system (Python version,
operating system, &c). -->


Hi @dengshaochun, this is intended behavior. Requests will not forward potentially sensitive auth tokens to redirected hosts. This is to prevent leaking auth information to unintended endpoints. The best course of action in this case is to fix the URI provided to Requests to prevent redirection.
Feature Request: `safe_json()` Method for Requests Library

# Description
I would like to propose the addition of a `safe_json()` method to the `requests.Response` object. This method would attempt to return the response content as JSON if it is JSON. If the response content is not JSON, it would return the text content. If the response content is neither JSON nor text, it would return `None`.

## Rationale
When working with HTTP responses, it is common to handle different content types. A response might contain JSON, plain text, or even be empty. Currently, developers have to manually write error handling to safely parse JSON responses while falling back to text if JSON parsing fails. This can lead to repetitive boilerplate code and potential bugs.

```python
try:
    content = response.json()
except ValueError:
    content = response.text if response.text else None
```

A `safe_json()` method would streamline this process, providing a convenient and reliable way to handle different response content types. This would enhance the usability of the `requests` library and improve developer productivity.

## Proposed Solution
```python
from typing import Any, Union, Optional

class Response:
    # Existing methods...

    def safe_json(self) -> Optional[Union[dict, list, str]]:
        """
        Attempt to parse the response content as JSON.

        Returns:
            Optional[Union[dict, list, str]]: The parsed JSON content if the response is JSON.
            The text content if the response is not JSON.
            None if the response content is neither JSON nor text.
        """
        try:
            return self.json()
        except ValueError:
            if self.text:
                return self.text
            return None

```

## Possible Benefits:

- Reduction in boilerplate code for error handling when parsing JSON.
- Provides a clear and consistent way to handle different types of response content.
- Improves code readability and maintainability.

Thank you for considering this feature request

As described in the template, Requests is not accepting feature requests
Update setup.py in order to fix CVE-2023-37920

CVE-2023-37920 link:
https://nvd.nist.gov/vuln/detail/CVE-2023-37920

Certifi is a curated collection of Root Certificates for validating the trustworthiness of SSL certificates while verifying the identity of TLS hosts. Certifi prior to version 2023.07.22 recognizes "e-Tugra" root certificates. e-Tugra's root certificates were subject to an investigation prompted by reporting of security issues in their systems. Certifi 2023.07.22 removes root certificates from "e-Tugra" from the root store.

Hi @pablospe, please check open and closed issues/PRs before filing new ones. You can see our previous response [here](https://github.com/psf/requests/pull/6494#issuecomment-1668101497).
GET请求，我希望传递% 但是requests会默认帮我编码为%25，如何解决？

Please refer to our [Stack Overflow tag](https://stackoverflow.com/questions/tagged/python-requests) for guidance.
GET请求，我希望传递% 但是requests会默认帮我编码为%25，如何解决？

As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)
Deprecated `HTTPAdapter.get_connection()` method is never called, causing breakage without deprecation warnings

After upgrading several of certbot's packages, including `requests` to 2.32.3, we suddenly started experiencing confusing DNS resolution errors with no clear cause. Only after bisecting the changed packages and isolating `requests` as the source of the trouble did we see that 2.32.2 deprecated the `HTTPAdapter.get_connection()` method we used.

Unfortunately, the change which deprecated `get_connection()` also causes it never to be called by `Session`, so the `DeprecationWarning` added in https://github.com/psf/requests/pull/6710 will never be printed. If `Session` perhaps checked if `get_connection()` was defined and called it, the warning would've printed and would've saved us quite a lot of time tracking down the issue.

I also generally wouldn't expect a minor version upgrade in a dependency to cause a breaking change, so this result was extra confusing.

## Expected Result

`HTTPAdapter.get_connection()` to still be called, resulting in no breaking changes and giving users the deprecation warning. Or at the very least, check if `get_connection` is defined and print the deprecation warning then.

## Actual Result

`HTTPAdapter.get_connection()` is silently left uncalled, causing a breakage.

Hi @wgreenberg, the commit you linked appears to be part way through the issue. #6710 was to provide a public API for users who were overriding `get_connection`. The initial breakage came from #6655 to address CVE-2024-35195.

While we don't generally make breaking changes in minor patch versions, users were unknowingly exposing data over unverified connections. We chose to patch the API but it appears docker and certbot are two cases that were negatively impacted.

There were a few misses in messaging around this change because impact wasn't assessed completely prior to releasing 2.32.0. The workaround provided in #6710 will be the backwards compatible middle ground to keep adapters using a custom `get_connection` working with the least amount of work going forward.

I'm going to resolve this since we haven't heard back anything else. Let us know if you have any other questions.
Rename lock-issues.yml to 90daylock-issues

d31a23b10d2c721f9ddab7baaafd5869406b1f83

Thanks for the PR, @Devante7. It doesn't look like this is a necessary change though. The title is clear on the workflow intention and the specific values are available in the file. Having to rename the file every time a value changes would be unintuitive/disruptive.
Address certificate loading regression

## Overview
This PR is intended to address two distinct issues introduced with the default cert optimizations originally introduced in 2.32.0. While we continue to refine the settings considered when opting into our optimized context, we'll no longer use the new default if any custom cert values are supplied. This addresses the concurrency issues raised in #6726.

The second piece of this will be ensuring that when opting out of the default SSLContext, we're still supplying to the default CA Cert bundle correctly. This addresses the problems noticed in https://github.com/psf/requests/pull/6710#issuecomment-2137802782 and #6730.

## Considerations

We're now duplicating a decent chunk of the [logic from cert_verify](https://github.com/psf/requests/blob/0e322af87745eff34caffe4df68456ebc20d9068/src/requests/adapters.py#L324-L357) inside [_urllib3_request_context](https://github.com/psf/requests/blob/0e322af87745eff34caffe4df68456ebc20d9068/src/requests/adapters.py#L115-L128) but without our validation exceptions. That's a potential vector for behavioral shifts in the future. We _could_ consolidate some of this behavior in one place but it's going to require constructing a dict and using `setattr` on our `conn` in `cert_verify` while setting `pool_kwargs` in `_urllib3_request_context`. I started writing that up but it feels clunky. This is probably going to be a tradeoff of risking drift like we have with Session settings and binding the two behaviors together too tightly.

## Testing
I'd like to codify the issues we've encountered through the whole 2.32.x saga in tests to hopefully avoid this in the future. Doing it cleanly without relying on external endpoints is proving to be a bit more involved than I'd like. I think we can harness some of the infrastructure added in #6662, but I haven't had a chance to really dig into that.

Is there an ETA for this change or a similar change? 2.32.3 doesn't work for us, as it broke our usage of `requests_pkcs12`. It looks like that package was updated with a temporary change [here](https://github.com/m-click/requests_pkcs12/issues/55#issuecomment-2154946453), so if a "proper" fix is not intended to be released anytime soon then we can try that. However I'd be keen to take a proper fix for both if that's expected soon!

The regression is there for some time and the PR is still in draft. Is there some way to move this forward?

Maintainers, is there any update here? The latest version of HTTPie is mostly non-functional due to this issue, and we will need to drop it and migrate to other tools if this cannot be addressed.

There does not seem to be any blocking feedback on this PR - can any clarity be provided about what is currently preventing a merge? Is additional contribution required from the community?

A friendly reminder that this issue has been stagnant for 4 months already.

Hi @sigmavirus24  you're listed as reviewer for this. Would you like to review this or assign someone else to do so?
ssl certificate validation of requests was ignored but the ssl certificate still reported an error

## Problem recurrence
Please refer to our [Stack Overflow tag](https://stackoverflow.com/questions/tagged/python-requests) for guidance.
Testing on different operating systems, I found it was Caused by SSLError(SSLError(1, '[SSL:) caused by SSLerror (SSLError(1, '[SSL:) SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1006)')) error, but I did not have a validation problem during one of the validations
<img width="1047" alt="image" src="https://github.com/psf/requests/assets/64049774/704c0306-c304-41c5-8805-7e068fd14000">
Testing on my mac air m2 machine produced the above error, but my demonstration in kali did not have this problem
<img width="848" alt="image" src="https://github.com/psf/requests/assets/64049774/3d9a7ffb-01a6-491f-b642-64fde6a0b6c2">
But I tested it with the default python version on ubuntu 22.04 and got the same error message as on my mac
<img width="1178" alt="image" src="https://github.com/psf/requests/assets/64049774/955bd57a-0985-469a-96b1-e8e935b81082">
## Environment version
<img width="647" alt="image" src="https://github.com/psf/requests/assets/64049774/bd22f860-3ecc-4ac8-ae44-eb915aad1571">
<img width="896" alt="image" src="https://github.com/psf/requests/assets/64049774/c31ecb21-18bc-4635-9130-b52f37cc439e">
<img width="1047" alt="image" src="https://github.com/psf/requests/assets/64049774/beaa348f-7000-4966-9760-eec9e02407d8">

## Recurring environment

```python
import requests
response = requests.get(url="https://183.237.161.98:4433/favicon.ico", verify=False, allow_redirects=False)
```

As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)
Don't create default SSLContext if ssl module isn't present

This PR is to address a [recent regression in Emscripten support for urllib3](https://github.com/urllib3/urllib3/actions/runs/9253144050/job/25452248794). We began unilaterally creating an SSLContext without consideration for Python versions built without an ssl module. This is handled in urllib3 but missed in our usage of `create_urllib3_context`.

This PR expands on the fix in #6716 by also evaluating both the presence of the `ssl` module before creating and setting the default SSLContext.

We also need to do this for `FileNotFoundError`, which is raised if `DEFAULT_CA_BUNDLE_PATH` isn't there. Sent as https://github.com/psf/requests/pull/6781 .
Different default values for "allow_redirects" for HEAD http method


A HEAD request can be performed in two ways. Using the `requests.head` method or the `requests.request` method. But both have different default values for "allow_redirects".
## Expected Result
Both ways of performing HEAD requests have the same default behavior.
## Actual Result
`requests.head(url)` has allow_redirects disabled by default.
`requests.request("HEAD", url)` has allow_redirects enabled by default.
<!-- What happened instead. -->

## Reproduction Steps

```python
import requests

# HEAD request with default allow_redirects False
r = requests.head("http://test_site.com")

# HEAD request with default allow_redirects True
r = requests.request("HEAD", "http://test_site.com")

```

## System Information

    $ python -m requests.help

```json
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.3.2"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.7"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.12.2"
  },
  "platform": {
    "release": "6.8.2-gentoo",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.31.0"
  },
  "system_ssl": {
    "version": "300000d0"
  },
  "urllib3": {
    "version": "2.2.1"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}
```

<!-- This command is only available on Requests v2.16.4 and greater. Otherwise,
please provide some basic information about your system (Python version,
operating system, &c). -->


This is expected. The request method means you want to explicitly do things differently so you don't get the per-method behaviors otherwise defined

@sigmavirus24 thanks! The reason i  have to use `requests.request` is because there are no methods to perform TRACE and CONNECT http requests. For instance fir a GET request there is `requests.get`. For PUT there is `requests.put`. No such method exists for CONNECT and TRACE. Is this also intentional?

Yes. These have all been discussed at I've point it another in various issues that are all closed

https://github.com/psf/requests/pull/6209
Enhance Error Messaging for Connection Failures

When making an HTTP request using the requests library, I encountered a connection failure. The error message provided was not very clear or actionable, especially for someone new to the library. Enhancing these error messages to provide more detailed and actionable information would significantly improve the developer experience.

## Expected Result

I expected the error message to include more detailed information about the potential causes of the connection failure and suggestions for troubleshooting steps.

## Actual Result

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='osudle.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001A9F6DB93C0>: Failed to establish a new connection: [WinError 10051] A socket operation was related to an unavailable network'))

## Reproduction Steps

```python
import requests

r = requests.get("http://osudle.com', timeout=20)

print(r.status_code)
```

## System Information

    $ python -m requests.help

```
python -m requests.help
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "2.0.12"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.4"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.10.4"
  },
  "platform": {
    "release": "10",
    "system": "Windows"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.32.2"
  },
  "system_ssl": {
    "version": "101010ef"
  },
  "urllib3": {
    "version": "1.26.18"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}
```

This command is only available on Requests v2.16.4 and greater. Otherwise,
please provide some basic information about your system (Python version,
operating system, &c).


What extra information would you have liked in the error which you think would be actionable? Can you share some examples?
v2.32.3

2.32.3 (2024-05-29)
-------------------

**Bugfixes**
- Fixed bug breaking the ability to specify custom SSLContexts in sub-classes of
  HTTPAdapter. (#6716)
- Fixed issue where Requests started failing to run on Python versions compiled
  without the `ssl` module. (#6724)

@sigmavirus24 @sethmlarson Anything else preventing this release, scheduled for today?

Hi @gesslerpd, we have some other changes being worked on. You can monitor this PR being merged for when the next release goes out.
Start testing on 3.13 beta

It looks like we're currently blocked on wheels for a few testing dependencies so this isn't mergable currently but we'll use this PR to monitor upstream support from other projects. Once those blockers are moved, we can merge this into our CI to prepare for the upcoming release candidates.

Currently it looks like `flsgger` and `greenlet` are having issues from httpbin. I think we have an open proposal/request to make `flsgger` optional which seems fine. `greenlet` currently has a proposed patch from Victor Stinner so I would assume that's resolved sooner than later.

Looks like we're still blocked on https://github.com/python-greenlet/greenlet/issues/392. Victor Stinner's patch which appears to fix the issue has been stalled for a couple months. We'll continue to keep an eye on that as we get closer to 3.13 release on October 1st, 2024.

@nateprewitt Is greenlet only needed for the gunicorn worker? Could we drop that as well in httpbin in favor of some other worker type? Or some other WSGI implementation?

Yeah, we definitely have options in httpbin to resolve the issue. I was going to wait until we're close to 3.13 release before we started pursuing changes there. We honestly don't even need flasgger there, it was a very late add to the project before development stopped. I would bias towards us just moving that to an optional dependency.

@nateprewitt greenlet is only needed as a dependency of gevent, it shouldn't be a direct dep https://github.com/psf/httpbin/pull/51

It's currently blocking pytest-httpbin 3.13 support: https://github.com/kevin1024/pytest-httpbin/pull/90
ERROR - Cannot set verify_mode to CERT_NONE when check_hostname is enabled

<!-- Summary. -->
I'm working with the exchangelib (v5.4) library. 
A couple of days ago I noticed that in the Docker container exchangelib started complaining with an error `ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled`.

Exchangelib tries to connect to a local server with a low security level via a custom adapter with this lines

```python
from requests.adapters import HTTPAdapter


class CustomHttpAdapter(HTTPAdapter):
    """Transport adapter that allows us to use custom ssl_context."""

    def __init__(self, ssl_context=None, **kwargs):
        self.ssl_context = ssl_context
        super().__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False, **kwargs):
        self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        self.ssl_context.set_ciphers('DEFAULT:@SECLEVEL=0')
        self.ssl_context.check_hostname = False

        self.poolmanager = urllib3.poolmanager.PoolManager(
            num_pools=connections, maxsize=maxsize,
            block=block, ssl_context=self.ssl_context, ssl_version=ssl.PROTOCOL_TLSv1)
```
With this exchangelib shows an error:
```
File "/usr/local/lib/python3.11/site-packages/cached_property.py", line 70, in __get__
2024-05-23T11:53:23.558367392Z     return obj_dict[name]
2024-05-23T11:53:23.558368832Z            ~~~~~~~~^^^^^^
2024-05-23T11:53:23.558370213Z KeyError: \'calendar\'
```

But if I change the version of requests package from 2.32.0 to 2.31.0, connection and information exchange occurs normally.


## System Information

```json
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.3.2"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.7"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.11.9"
  },
  "platform": {
    "release": "6.5.0-35-generic",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.32.0"
  },
  "system_ssl": {
    "version": "300000b0"
  },
  "urllib3": {
    "version": "2.2.1"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}
```

<!-- This command is only available on Requests v2.16.4 and greater. Otherwise,
please provide some basic information about your system (Python version,
operating system, &c). -->


In the future, please search **closed and** open issues before creating new ones that are duplicates.
Prefer charset_normalizer for char detection

`charset_normalizer` is a dependency for requests, while `chardet` is not, so it is more likely to be found.

For vendored requests this would still load whatever is available.

The reason I noticed this memory profiling in case both libraries are present and `charset_normalizer` has way lower memory footprint than `chardet`.

Just don't install chardet

I'd love to, but it's a dependency for a third-party library (https://github.com/otsaloma/gaupol/issues/222).

What is actually the reason for trying `chardet` first when it's not dependency for requests? It's just an extra import that is very likely to fail.
v2.32.2

2.32.2 (2024-05-21)
-------------------

**Deprecations**
- To provide a more stable migration for custom HTTPAdapters impacted
  by the CVE changes in 2.32.0, we've renamed `_get_connection` to
  a new public API, `get_connection_with_tls_context`. Existing custom
  HTTPAdapters will need to migrate their code to use this new API with
  Requests>2.32.0.

  A minimal (2-line) example has been provided in the linked PR to ease
  migration, but we strongly urge users to evaluate if their custom adapter
  is subject to the same issue described in CVE-2024-35195. (#6710)
Add default timeout

This adds a default connect and read timeout value for all usage of Requests. This is to solve a long-standing issue where some systems do not have a sufficiently low default value.

Personally, I'd want these values to be much lower, but a 10 second connection timeout and a 30 second read timeout seem like they should be enough to avoid problems for the edge cases of users while also not being so large that they're basically ineffective.

Closes #3070

If you add a default timeout it may break existing code bases.

For example, if I am using a GET request to download a 1 GB file then I would have to adjust timeout to make my code compatible with this proposed change.

> If you add a default timeout it may break existing code bases.
> 
> For example, if I am using a GET request to download a 1 GB file then I would have to adjust timeout to make my code compatible with this proposed change.

You don't understand timeouts in Python. Please go read any number of past issues and blog posts about this issue before spreading FUD. 

Consider also adding -1 as timeout value such that it retains wait till infinity as requests currently behaves. That behaviour is desirable
`
ValueError: Attempted to set connect timeout to -1, but the timeout cannot be set to a value less than or equal to 0.
`
```
if timeout is None:
   timeout = _DEFAULT_TIMEOUT
if timeout == -1:
   timeout = None
# causes default timeout if not passed, if -1 is passed it becomes None, else if any other number is passed it becomes timeout after that much seconds
```
v2.32.0

2.32.0 (2024-05-20)
-------------------

**Security**
- Fixed an issue where setting `verify=False` on the first request from a
  Session will cause subsequent requests to the _same origin_ to also ignore
  cert verification, regardless of the value of `verify`.
  (https://github.com/psf/requests/security/advisories/GHSA-9wx4-h78v-vm56)

**Improvements**
- `verify=True` now reuses a global SSLContext which should improve
  request time variance between first and subsequent requests. It should
  also minimize certificate load time on Windows systems when using a Python
  version built with OpenSSL 3.x. (#6667)
- Requests now supports optional use of character detection
  (`chardet` or `charset_normalizer`) when repackaged or vendored.
  This enables `pip` and other projects to minimize their vendoring
  surface area. The `Response.text()` and `apparent_encoding` APIs
  will default to `utf-8` if neither library is present. (#6702)

**Bugfixes**
- Fixed bug in length detection where emoji length was incorrectly
  calculated in the request content-length. (#6589)
- Fixed deserialization bug in JSONDecodeError. (#6629)
- Fixed bug where an extra leading `/` (path separator) could lead
  urllib3 to unnecessarily reparse the request URI. (#6644)

**Deprecations**

- Requests has officially added support for CPython 3.12 (#6503)
- Requests has officially added support for PyPy 3.9 and 3.10 (#6641)
- Requests has officially dropped support for CPython 3.7 (#6642)
- Requests has officially dropped support for PyPy 3.7 and 3.8 (#6641)

**Documentation**
- Various typo fixes and doc improvements.

**Packaging**
- Requests has started adopting some modern packaging practices.
  The source files for the projects (formerly `requests`) is now located
  in `src/requests` in the Requests sdist. (#6506)
- Starting in Requests 2.33.0, Requests will migrate to a PEP 517 build system
  using `hatchling`. This should not impact the average user, but extremely old
  versions of packaging utilities may have issues with the new packaging format.
Requests roadmap 

Since the PSF took over management of 'requests' I am wondering what the road map is for this library?  Is it posted anywhere?  Is v3 totally dead?  Is the package just in maintenance mode? 

I know a few years ago things were very chaotic, but being removed from those bad times, where is the package going? 




It's still just Nate and me. There isn't really any more time we can commit to the project than we already do. V3 as described to raise lots of money that didn't actually end up benefitting the project is still something desirable but will never be called V3 as none of those goals are recoverable from that website. So if we ever do have enough time to spend in a larger overhaul it will likely be named something else entirely. 

The project hasn't had any notable form of roadmap since the early releases of Requests 2.x. Almost all work on Requests 3.x stopped in 2017, so that's not a recent development. I think urllib3 2.0 has laid a path for a more gradual shift on improvements/minor breakages that we may be able to follow but there aren't any immediate plans as Ian noted. Requests is considered largely feature complete for its original purpose.

We'll continue to release bugfixes and general maintenance changes as we have, and if there is a point we have something that makes sense to add, we may consider it. Adding features for the sake of features though has never been a goal for Requests, so that's unlikely to change.

Is the PSF funding the project in anyway? Or just hosting it? 

Neither Nate nor I can accept any funding due to our employers 

Thank you, I appreciate both your work.
Allow optional char detection dependencies in post-packaging

This PR is a proposal to relax our requirement to have a character detection library present with all installations of Requests. While we cannot remove our reliance on `charset_normalizer` or `chardet`, there are use cases where Requests is repackaged in applications or other tools that do not need our character detection behavior. These changes will enable them to remove those dependencies from their installation.

The current use case for this shift is to allow `pip` to remove these dependencies entirely. That should slim the package ~2MB in 24.1.0 and avoid the overhead of importing the unneeded dependency.
Connection problems

Hello,
i´m pretty new in Python programming.
I have python3 and i installed requests via pip.

I cant connect to any site with .get...

my code: 
import requests

r = requests.get('http://google.com', timeout=20)

print(r.status_code)

Output: see file Output.txt 
[Output.txt](https://github.com/psf/requests/files/15305796/Output.txt)


If i try to catch exeptions: 
Code:
import requests

try:
    response = requests.get('https://google.com',timeout=20)
    if response.status_code == 200:
        print (response.json())
    else:
        print(f"Fehler beim Abrufen der Daten. Statuscode: {response.status_code}")
except Exception as e:
    print(f"Fehler: {str(e)}")

Output: 
Fehler: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000215B98DE900>: Failed to establish a new connection: [WinError 10051] A socket operation was related to an unavailable network'))

Is it a firewall or some connection problems ? I´m clueless

As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)
Use an invalid URI that will not cause httpbin to throw 500

Context in https://github.com/urllib3/urllib3/issues/3392

Urllib3's CI started failing due to the requests `test_redirecting_to_bad_url` failing. The test started failing, beacuse httpbin started returning 500 on initial request, instead of a 302. I think this would break requests CI as well if it were run now.

Modified the redirect to URI to something that will not cause httpbin to throw a 500, but is still an invalid URI.
Can't access trailers with the Request library

<!-- Summary. -->

Requests doesn't seem to support processing [Trailer](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Trailer) response headers.  While I know that Trailer support has been [discussed](https://github.com/psf/requests/issues/3613) [previously](https://github.com/psf/requests/issues/2281), some time has passed since then and I hope the issue can be reconsidered. 

The desired use case is to add Trailer header to API responses but we cannot read them using the Request library.
Other frameworks in other languages ([Vert.x](https://vertx.io/docs/vertx-core/java/#_chunked_http_responses_and_trailers) for example) support Trailers, but not Python Requests.

## Expected Result
A Trailer response header has been added to a response, which is then read using Requests, the Trailer should be accessible.

<!-- What you expected. -->

## Actual Result
There is no way to access the Trailer in the response using Requests.

<!-- What happened instead. -->




Nothing has changed since that thread. We still rely on httplib and httplib (or now http.client) does not support trailers for HTTP/1.1. i suspect some other http clients may be able to support this as they are built on h11 but whether they do or don't I couldn't tell you
Docs update: warn that Session.verify is ignored if REQUESTS_CA_BUNDLE is set

Issue #3829 tracks that Session.verify is ignored whenever `REQUESTS_CA_BUNDLES` or `CURL_CA_BUNDLES` is set. The underlying behavior will apparently be changed in 3.x, but in the meantime it would be helpful to call out the behavior in the docs to avoid catching people out (the issue has been locked due to a large number of comments).

I'm happy to rework this PR as needed, but it'd be great to get something in the docs about this in one form or another to help prevent people hitting this.

Thanks in advance for your thoughts!

---

## Change Details

* Added a `warning::` callout to the relevant section of the docs.

## Alternate Approaches Considered

I initially wrote out a longer section detailing the semantics for how the various options interact — but all the other interactions are very intuitive, so this felt like overkill. Let me know if you'd prefer that approach.

This section of the docs is also a bit callout heavy, so I'm happy to inline the text rather than put it in a callout, if you prefer.
Support usage of PKCS#11 Hardware Security Modules where applicable

Although "requests is not accepting feature requests at this time" I can't find any other way/place to pen a discussion about this.

In the application I am working on, we'd like to add support for using HSMs in the future. It's not obvious how to do that effectively, however, unless support for it is included in `requests`.

Are there any plans to try to add support for HSMs?


As described in the template, Requests is not accepting feature requests
fix: enviroment variable PYTHONHTTPSVERIFY isn't take in consideration on https requests.

In case of the ssl certificate of destination host has expired isn't possible to ignore the cert validation using env PYTHONHTTPSVERIFY=0.

We have never supported this: https://requests.readthedocs.io/en/latest/search/?q=PYTHONHTTPSVERIFY

- @sigmavirus24: 

If packages that depend on the "request" package encapsulate the get() method in a way that does not give the user the option of determining whether or not to perform SSL validation, this makes it impossible to use the target endpoint if its certificate is expired. An example of this is the hugging face package. Because of this, I advocate the need to empower the user to be able to bypass the SSL check if the package they use does not provide this capability. As it stands, if the package used does not support bypassing validation and the certificate has expired, the project being built stops working until the external endpoint has its certificate updated (if it is updated). Because of this I understand that it would be a case of fixing.

If we agree that this need is valid, we then move on to the strategy of how this should be done in terms of implementation (since in terms of bureaucratic process I am still a noob in the python project, I only have 3 months in this universe). I advocate the use of the PYTHONHTTPSVERIFY environment variable because it has already been used within the Python ecosystem to signal, for example, that pip ignores SSL validation in previous versions.

I suggest using this environment variable for the sake of uniformity but I am open to suggestions.
requests.request does not check method parameter


```
res = requests.request(method='155661', url='https...')
```
doesn't raise any error (warning) for totally unreasonable value for **method** parameter.

It leads to bugs.

Hi @Michal-Martinek, this is intentional design. There are many verbs we do not support directly, but may be used such as WebDAV. We don't intend to enumerate all possible options in our library, so it is left to the end user to determine their needs.

You'll find you can successfully send your request to well-functioning web servers, so I don't think we intend to change the existing behavior. We should be clear about what "bug" means in this case. If there is unexpected behavior in Requests, can you please provide an exact stacktrace or behavior issue? If the problem is the web server returns a non-200 response, I'd propose we close this as working as intended.
not support HTTP2 header

not support http2 header

example:
```
import requests
from hyper.contrib import HTTP20Adapter

headers={':path': '/hello}'

s = requests.Session()
s.mount('https://http2bin.org', HTTP20Adapter())
r = s.get('https://http2bin.org/get', headers=headers)
print(r.status_code)

# raise Invalid leading whitespace, reserved character(s), or return character(s) in header name: ':path'
```


This is a duplicate