Raibek/requests-github-issues huggingface dataset:
Consider not using single char variables in docs

**Summary.**

I was debugging a requests example from the website here (http://docs.python-requests.org/en/master/) and was in a PDB session.  Went to inspect "r" by typing "r" and <enter> it did not reference the variable "r".

**What you expected.**

I expected that it would return the object R

**What happened instead.**

It returned to the next method, because PDB uses hotkeys.

```python
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
import pdb; pdb.set_trace()
```
Then type 'r' in PDB session, will return instead of instance of 'r'.

**Suggestion.**

Update the docs to not use single-char variables.  I would have sent a PR, but wanted to start here, as it's more emergent behavior of using PDB and single char vars then a direct requests issue, but is reflected in your examples.


Hi @claudijd, thanks for starting the conversation. While we want to make sure the documentation is easily accessible, I’m not sure this warrants a change. PDB has specifically added syntax to handle this issue. Whenever you’re printing a variable in the console, you should be prefixing it with an ! (e.g. !r) to avoid conflicts.

Given that we cannot control how other tools behave, the new variable could fail elsewhere and we’ll have to continue changing it. For those reasons, I think we’ll pass on this.

Thanks @nateprewitt 

@nateprewitt just for the sake of argument, should the docs then use the "!r" syntax as you suggest?

You'll end up with collisions with 'r.status_code' as well.

>>> import requests
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> import pdb; pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) r
>>> r.status_code
--Call--
> <stdin>(1)<module>()->None
(Pdb) exit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/bdb.py", line 50, in trace_dispatch
    return self.dispatch_call(frame, arg)
  File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/bdb.py", line 83, in dispatch_call
    if self.quitting: raise BdbQuit
bdb.BdbQuit


@claudijd no it shouldn't. The examples are (mostly) shown as if you've opened a python prompt, e.g., 

```
$ python
>>> import requests
>>> r = requests.get('https://httpbin.org/get')
>>> r
```

Not PDB
Improve parsing of header Digest

If this header is multiline we can found 'Digest\r\n  realm="..."\r\n ' instead of "Digest ".

Let's discuss about it :p

# [Codecov](https://codecov.io/gh/requests/requests/pull/4798?src=pr&el=h1) Report
> Merging [#4798](https://codecov.io/gh/requests/requests/pull/4798?src=pr&el=desc) into [master](https://codecov.io/gh/requests/requests/commit/d26f6314ab07eb8ea42ffb0a96e28deebf61ed18?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `100%`.

[![Impacted file tree graph](https://codecov.io/gh/requests/requests/pull/4798/graphs/tree.svg?width=650&token=mZGswIiXLa&height=150&src=pr)](https://codecov.io/gh/requests/requests/pull/4798?src=pr&el=tree)

```diff
@@           Coverage Diff           @@
##           master    #4798   +/-   ##
=======================================
  Coverage   66.77%   66.77%           
=======================================
  Files          15       15           
  Lines        1568     1568           
=======================================
  Hits         1047     1047           
  Misses        521      521
```


| [Impacted Files](https://codecov.io/gh/requests/requests/pull/4798?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [requests/auth.py](https://codecov.io/gh/requests/requests/pull/4798/diff?src=pr&el=tree#diff-cmVxdWVzdHMvYXV0aC5weQ==) | `68.96% <100%> (ø)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/requests/requests/pull/4798?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/requests/requests/pull/4798?src=pr&el=footer). Last update [d26f631...a80148b](https://codecov.io/gh/requests/requests/pull/4798?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


No. See what @Lukasa told you in your issue
Not supported proxy scheme error

I am conecting to the internet through a proxy server. I used the below code to send a HTTP GET request using _requests_ library in python.


   ```
 import requests
    from requests.auth import HTTPProxyAuth
    
    url = "http://httpbin.org/get" 
    proxies = {"http":"my-proxy-server: port"}
    auth = HTTPProxyAuth("username", "password")
    r = requests.get(url, proxies=proxies, auth=auth)
    print r
```

but It gives me the following error

   ```
 Traceback (most recent call last):
      File "D:\python_http_req.py", line 7, in <module>
        r = requests.get(url, proxies=proxies, auth=auth)
      File "C:\Python27\lib\site-packages\requests\api.py", line 72, in get
        return request('get', url, params=params, **kwargs)
      File "C:\Python27\lib\site-packages\requests\api.py", line 58, in request
        return session.request(method=method, url=url, **kwargs)
      File "C:\Python27\lib\site-packages\requests\sessions.py", line 512, in request
        resp = self.send(prep, **send_kwargs)
      File "C:\Python27\lib\site-packages\requests\sessions.py", line 622, in send
        r = adapter.send(request, **kwargs)
      File "C:\Python27\lib\site-packages\requests\adapters.py", line 410, in send
        conn = self.get_connection(request.url, proxies)
      File "C:\Python27\lib\site-packages\requests\adapters.py", line 308, in get_connection
        proxy_manager = self.proxy_manager_for(proxy)
      File "C:\Python27\lib\site-packages\requests\adapters.py", line 198, in proxy_manager_for
        **proxy_kwargs)
      File "C:\Python27\lib\site-packages\urllib3\poolmanager.py", line 449, in proxy_from_url
        return ProxyManager(proxy_url=url, **kw)
      File "C:\Python27\lib\site-packages\urllib3\poolmanager.py", line 400, in __init__
        raise ProxySchemeUnknown(proxy.scheme)
    ProxySchemeUnknown: Not supported proxy scheme my-proxy-server

```
can anybody help me to resolve this error?


It was a issue in my proxy server

i too have this issue..can you please share me how did you resolve it?

i too have this issue..can you please share me how did you resolve it?

from requests.auth import HTTPProxyAuth
proxyDict = {
          'http'  : 'http://138.197.222.35:80',
          'https' : 'http://1138.197.222.35:8080'
        }
        #auth = HTTPProxyAuth('username', 'mypassword')
        r = requests.get('http://httpbin.org/ip', proxies=proxyDict)
        print (r)

@oshadaamila This issue is resolved with solution by @samiashton1989 Consider it closing.
multiline header should be supported!

Hi everybody.
Yes I read it #4216 

It ends with @Lukasa quoting specification.
But if we read this [specification](https://tools.ietf.org/html/rfc7230#section-3.2.4) a bit further:

> A user agent that receives an obs-fold in a response message that is
> not within a message/http container MUST replace each received
> obs-fold with one or more SP octets prior to interpreting the field
> value.

So it MUST be supported, no?

Regards


No.

*Receiving* them is a MUST, emitting them is a MUST NOT.
Proxy headersAllow headers to be passed to proxy

Adding a header field to proxies will pass any headers to the proxy connection.

Hi @zulrang, thanks for trying to help move this issue forward. Unfortunately, I don't think we'll be likely to take this approach. Adding a special cased "headers" entry to proxies is going to cause weird behaviour. Both because it's not a proxy, and because this is a hard thing to document and get people to use properly.

As Lukasa said in the original issue, I'm not sure if there's a clean interim solution right now. We can work towards implementing a fix in 3.0 but I don't think we want to implement a hacky solution that needs to be maintained until then.
Exceptions handling

Please see question here: https://stackoverflow.com/questions/52352118/local-variable-responsedata-referenced-before-assignment-using-requests-libra

```
            responsedata = requests.get(url, data=data, headers=self.hed, verify=False, timeout=120)
            responsedata.raise_for_status()

```
The library does not explain in which exceptions we can use the values from` raise_for_status()` as some exceptions are raised by the get before executing the raise_for_status()

The result is exceptions of referencing variable before assignment. 

What I wanted is:


```
        except (Exceptions that **can not use**  raise_for_status ) as e:
            print ("Thread {3} page #{0} run #{1} failed. Msg: {2}. Retry.".format(page, n, sys.exc_info()[0], thread_name))
            continue

        except (Exceptions that **can use**  raise_for_status ) as e:
            print ("Thread {5} page #{0} run #{1} failed. Returned status code {2}. Reason: {3}. Msg: {4}. Retry.".format(page, n, responsedata.status_code, responsedata.reason, sys.exc_info()[0], thread_name))
            _handle_exception(e, tries, n, page, thread_name)
            continue
```

The library does not specify information for this.
Requests timeout not working as expected

Please refer to our [Stack Overflow tag](https://stackoverflow.com/questions/tagged/python-requests) for guidance.
`
requests.get('http://www.google.co.in', timeout=0.001)`

Using above on one server works fine but on another server where probably outside access is not allowed requests doesn't timeout the request and only fails after few seconds with below error. 
```
Traceback (most recent call last):
  File "/home/utrade/utradeENV/lib/python3.6/site-packages/urllib3/connection.py", line 141, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/home/utrade/utradeENV/lib/python3.6/site-packages/urllib3/util/connection.py", line 60, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/home/utrade/python3.6_optimized/lib/python3.6/socket.py", line 743, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/utrade/utradeENV/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/home/utrade/utradeENV/lib/python3.6/site-packages/urllib3/connectionpool.py", line 356, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/home/utrade/python3.6_optimized/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/home/utrade/python3.6_optimized/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/home/utrade/python3.6_optimized/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/home/utrade/python3.6_optimized/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/home/utrade/python3.6_optimized/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/home/utrade/utradeENV/lib/python3.6/site-packages/urllib3/connection.py", line 166, in connect
    conn = self._new_conn()
  File "/home/utrade/utradeENV/lib/python3.6/site-packages/urllib3/connection.py", line 150, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f9342c32f98>: Failed to establish a new connection: [Errno -2] Name or service
 not known
```

What am I doing wrong or how can I make it timeout? 

This is because name resolution doesn't take the timeout into account. This is a lower-level issue than requests, see urllib3/urllib3#1334.

ok, thanks. I will try using python `signal`.
Can't set ipv6 proxy

I'm trying to use ipv6 proxy with requests but I can't

What I'm doing is :

```
import requests

resp = requests.get('https://instagram.com', proxies=dict(http='https://xxxxxx:xxxxxx@[2604:0180:2:99b:fc3d:a70b:a7f2:7a2a]:17684', https='https://xxxxxx:xxxxxx@[2604:0180:2:99b:fc3d:a70b:a7f2:7a2a]:17684'))
```


Hi @deounix, we’re going to need more information to look into this.

Please provide answers to the questions originally asked in the issue template, an explanation of what you’re experiencing vs what you’re expecting, and a stack trace if applicable. Thanks!

Hi @nateprewitt, There is no issue template just link to stackoverflow site.

I just need to know how can I set ipv6 proxy in requests. so I can do simple HTTP requests.

@deounix, the "Request for Help" template is asking for you to pose usage questions on Stackoverflow first, rather than posting them on the issue tracker. We’ll review the template and try to make that clearer.

The other issue template for reporting a bug has a series of questions. Without that information, it’ll be difficult to accurately diagnose why the ipv6 proxy setup may not be working.

Can you please also verify your proxy is working with curl or some other http client?

@nateprewitt Thank u I think curl help me to find the problem. Instagram didn't accept the connection but google, fb ... etc accept don't know why but I think this issue located to instagram.
Support for HTTP reason phrases

This could arguably be classified as a bug rather than a feature request.

Requests doesn't, as far as I can see, supply an API to return the server's HTTP reason phrase. What it instead supplies is an API that will return its own stringification of the server's HTTP status code.

While in many cases these will probably be the same, I am writing a reverse proxy, so I want to return to my client **exactly** what the origin server supplied to me.
For example, if the origin server said "200 Everything Is Awesome" instead of the more common "200 OK", then I want to return precisely "Everything Is Awesome" (not "OK") to my client in my reason phrase.

Note that the HTTP RFCs permit origin servers to supply custom reason phrases:

> The reason phrases listed here are only
>    recommendations -- they MAY be replaced by local equivalents without
>    affecting the protocol.

By my reading, the HTTP RFCs permit anyone to supply any bytes they like other than CR and LF in this 'reason phrase', and still comply with HTTP.

My point in that last paragraph is that I don't see a way in the RFCs for the server to specify a character set or encoding for its "reason phrase", yet arbitrary bytes seem to be permitted, so either this should be exposed as Python bytes not a Python string, or perhaps there should be a documented WONTFIX bug that the encoding is always assumed to be ASCII-7, or one of the ISO8859 extended ASCIIs, or maybe UTF-8.

We pull the `Response.reason` attribute from urllib3's Response. That said,

> Requests doesn't, as far as I can see, supply an API to return the server's HTTP reason phrase.

Is clearly wrong.

```py
Python 3.6.5 (default, Mar 29 2018, 18:20:46) 
[GCC 8.0.1 20180317 (Red Hat 8.0.1-0.19)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> requests.get("https://httpbin.org/status/418").reason
"I'M A TEAPOT"
```

And I can assure you that's not a standard reason. You can also access the original reason phrase from urllib3:

```py
>>> requests.get("https://httpbin.org/status/418").raw.reason
"I'M A TEAPOT"
>>> 
```
Fix a typo in a test docstring


# [Codecov](https://codecov.io/gh/requests/requests/pull/4785?src=pr&el=h1) Report
> Merging [#4785](https://codecov.io/gh/requests/requests/pull/4785?src=pr&el=desc) into [master](https://codecov.io/gh/requests/requests/commit/8472dbd13408e35611a38d58f32eb531ce0ffe1e?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `n/a`.

[![Impacted file tree graph](https://codecov.io/gh/requests/requests/pull/4785/graphs/tree.svg?width=650&token=mZGswIiXLa&height=150&src=pr)](https://codecov.io/gh/requests/requests/pull/4785?src=pr&el=tree)

```diff
@@           Coverage Diff           @@
##           master    #4785   +/-   ##
=======================================
  Coverage   66.79%   66.79%           
=======================================
  Files          15       15           
  Lines        1563     1563           
=======================================
  Hits         1044     1044           
  Misses        519      519
```



------

[Continue to review full report at Codecov](https://codecov.io/gh/requests/requests/pull/4785?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/requests/requests/pull/4785?src=pr&el=footer). Last update [8472dbd...d1fab0b](https://codecov.io/gh/requests/requests/pull/4785?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
SSLError propagets urllib3 SSLError exception object as message

Summary.
On adapter.py [link](https://github.com/requests/requests/blob/8472dbd13408e35611a38d58f32eb531ce0ffe1e/requests/adapters.py#L524) we pass as the first parameter of the error an SSLError exception object. this has a result if you catch the error e.message is an object and not a string. Is this intented?

Maybe we need to pass 

```python
        except (_SSLError, _HTTPError) as e:
            if isinstance(e, _SSLError):
                # This branch is for urllib3 versions earlier than v1.22
                raise SSLError(e.message, request=request)
```

## Expected Result

```
from requests.exceptions import SSLError
from urllib3.exceptions import SSLError as _SSLError

a = SSLError(_SSLError, request="TEST")

print a.message


```

What you expected.

> "An SSL error occured"

## Actual Result

What happened instead.

> <class 'urllib3.exceptions.SSLError'>

## Reproduction Steps

```python
import requests
from requests.exceptions import SSLError
from urllib3.exceptions import SSLError as _SSLError

a = SSLError(_SSLError, request="TEST")

print a.message

```

## System Information

    $ python -m requests.help

```
{
  "chardet": {
    "version": "3.0.4"
  }, 
  "cryptography": {
    "version": "2.2.2"
  }, 
  "idna": {
    "version": "2.6"
  }, 
  "implementation": {
    "name": "CPython", 
    "version": "2.7.12"
  }, 
  "platform": {
    "release": "4.15.0-33-generic", 
    "system": "Linux"
  }, 
  "pyOpenSSL": {
    "openssl_version": "1010008f", 
    "version": "18.0.0"
  }, 
  "requests": {
    "version": "2.18.4"
  }, 
  "system_ssl": {
    "version": "1000207f"
  }, 
  "urllib3": {
    "version": "1.22"
  }, 
  "using_pyopenssl": true
}

```

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 @NikosVlagoidis, I'm a little confused about what we're expecting here. All of our wrapped exceptions should return an instantiation of the exception that we're wrapped which is represented by the `e` variable in the code your referenced. When that exception is returned, you should be able to call the `message` attribute on it and get what you want.

The reproduction code you've provided is wrapping an exception with the SSLError **class** rather than an SSLError **object** instantiation. I think we'd expect the output to be the class reference at that point which matches your observed behaviour.

I'm going to close this out for now since it doesn't seem there's an issue here. If you have more information, please feel free to provide it hear and reopen the issue. Thanks!
ConnectionResetError: [Errno 104] Connection reset by peer

`Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.5/site-packages/urllib3/response.py", line 331, in _error_catcher
    yield
  File "/home/ubuntu/.local/lib/python3.5/site-packages/urllib3/response.py", line 640, in read_chunked
    chunk = self._handle_chunk(amt)
  File "/home/ubuntu/.local/lib/python3.5/site-packages/urllib3/response.py", line 595, in _handle_chunk
    returned_chunk = self._fp._safe_read(self.chunk_left)
  File "/usr/lib/python3.5/http/client.py", line 607, in _safe_read
    chunk = self.fp.read(min(amt, MAXAMOUNT))
  File "/usr/lib/python3.5/socket.py", line 575, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer` 

exception is not catched using:

`except requests.exceptions.RequestException as e:`


See stack overflow for more details.
https://stackoverflow.com/questions/52181161/handling-exceptions-from-python-requests

Based on your traceback, this doesn't actually involve Requests. Something else is using urllib3 directly. If you're using urllib3 directly, you can't use Requests to catch exceptions.

@sigmavirus24  I'm not using urlib3 directly. Only requests

@ron819 Then you've modified your traceback to the extent with which we cannot do anything. Your traceback includes nothing from requests. Is it possible you're using another library that uses urllib3 directly?
POST, PUT and PATCH on 301 redirect re-POST without body

Summary.

If ``allow_redirects = True`` and if redirect response 301 is returned, then POST, PUT and PATCH requests should save body.
Similar [issue 1084](https://github.com/requests/requests/issues/1084) was satisfied  for 307 responses.
[RFC](http://www.faqs.org/rfcs/rfc2616.html) says the same thing about 307 and 301 responses.

Actual result - body is cleaned on 301 response.

Requests version 
```
requests==2.19.1
```


Hi @skybobbi, the RFC linked is quite outdated. I believe you may have meant RFC 7231 section 6.4.2, which discusses changing POST to GET on redirect.

This behavior was implemented in Requests quite a while ago and is intentional. There is potential for malicious redirects to capture the contents of what you’re trying to send to another server. You’ll find this is implemented by every major browser and many http-related tools.

That said, we did revisit this a year or two ago and decided we’d scope the body stripping down to only POST requests per the RFC. This code is merged into the current 3.0 branch but won’t be released in the 2.X series due to it being a breaking change.

Thanks. 
As I understood, all request types except POST will save body on 301 redirects since 3.* version of requests. Am i right?

@skybobbi 3.0 has not been released yet, but yes, that is the functionality that is currently implemented on that branch.

If you need to handle this in the interim, you’ll need to handle the redirecting in your code. I would suggest looking at the SessionRedirectMixin in sessions.py

Thank you!
ChunkedEncodingError isn't explained properly

The [docs ](http://docs.python-requests.org/en/master/_modules/requests/exceptions/) says about `ChunkedEncodingError`:
```
class ChunkedEncodingError(RequestException):
    """The server declared chunked encoding but sent an invalid chunk."""
```

While this true it's highly confusing. What actually happens is that the server did not respond in time so the connection was closed. The solution is to retry the code and attempt again:

```
    def get(tries=5):
        for n in range(tries):
            try:
                GET call
                return whatever
            except ChunkedEncodingError as e:
                if n == tries - 1:
                    raise e
```


This has been asked many time over the internet including even here: https://github.com/requests/requests/issues/4484

I recommend adding an **optional**  argument for the `GET `call which will specify the tries number and that will be handled by the get call itself. This will avoid this problem and allow the user more control. 
meaning that the GET will return the exception only when the max retries has been reached.

If my suggestion is not accepted at least edit the docs and suggest the template of the solution to avoid the problem. 

Hi @ron819, while the exception we're wrapping isn't the clearest, it does convey the connection has been broken with the server. The cause of that could be a multitude of things, but is likely the server forcing the connection closed.
```
requests.exceptions.ChunkedEncodingError: ("Connection broken: error(10054, '')", error(10054, ''))
```

I don't think it's clear that most users would want to retry in the case of a misbehaving server. Our API for Requests is currently frozen, so changes to the `get` method are unlikely unless there's significant oversight in functionality. Your example shows this should be easily implementable in 10-15 lines of code in your application, giving your complete control over how it will work. For those reasons, I don't think we'll be adding anything new to the Requests code base at this time.
HTTPSConnectionPool, SOCKSHTTPSConnectionPool errors

Using this code a long time, but few month ago, it started to craching with error
--------------------------------------
```
import requests

def get_tor_session():
	session = requests.session()
	session.proxies = {'http':  'socks5://127.0.0.1:9150',
					   'https': 'socks5://127.0.0.1:9150'}
	return session

requests.packages.urllib3.disable_warnings()
session = get_tor_session()
IpUrl = 'https://api.ipify.org'
TorResponse  = session.get(IpUrl)
print('tor ip: {}'.format(TorResponse.text.strip()))
```
--------------------------------------------------------------

Error:

`HTTPSConnectionPool(host='', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', error(10053, 'An established connection was aborted by the software in your host machine')))`
----------------------------
if clear all proxy fields in internet explorer options, got another error:

`SOCKSHTTPSConnectionPool(host='', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x0383A1F0>: Failed to establish a new connection: 0x05: Connection refused',))`
-----------------------------

changing socks5:// to socks5h:// make error:
`ValueError: Unable to determine SOCKS version from socks5h://127.0.0.1:9150`

------------------------

`c:\Python27>pip show requests
Name: requests
Version: 2.19.1
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.org
License: Apache 2.0
Location: c:\python36\lib\site-packages
Requires: idna, chardet, urllib3, certifi
You are using pip version 9.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

c:\Python27>pip show urllib3
Name: urllib3
Version: 1.23
Summary: HTTP library with thread-safe connection pooling, file post, and more.
Home-page: https://urllib3.readthedocs.io/
Author: Andrey Petrov
Author-email: andrey.petrov@shazow.net
License: MIT
Location: c:\python36\lib\site-packages
Requires:
You are using pip version 9.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.`

Installed requests[socks], ssl and everithig else available in internet
Directly in Tor browser all site links opening ok
------------------------------

How to solve problem?

Hi @JonhSilver, this appears to be a request for help. The information provided points towards a possible issue with your proxy which is outside of the scope of Requests. These kinds of questions for specific setups should be directed to [StackOverflow](https://stackoverflow.com) since we reserve the use of this issue tracker for defects in Requests.

If you can provide an isolated example of this issue and which version of Requests it breaks between, we may be able to investigate more. Until then I'm going to close this out. Thank you!
Docs: Requests 3 info link at top of main page points to a 404

The link that states "Requests 3.0 development is underway, and your financial help is appreciated!"
at the top of every doc page (eg: http://docs.python-requests.org/en/master/), currently points to the url:

https://www.kennethreitz.org/requests3

Which, at the time of writing is a "404 not found" page.

I'd like to learn about requests 3, so this should point somewhere useful :) (or be removed temporarily)

Just noticed the same. Looks like it's been down a while according to Internet Archive but https://web.archive.org/web/20180701201816/https://www.kennethreitz.org/requests3 should work for the moment, @joshstaiger =)

Duplicate of https://github.com/requests/requests/issues/4743

In the future, please search **closed and** open issues before creating new ones that are duplicates.
Fix several ResourceWarnings in test_requests.py

Hello,

I do not know if you are interested in fixing `ResourceWarning`s in tests, but I will take my chance :)
There was 10 unclosed files in `test_requests.py`.

# [Codecov](https://codecov.io/gh/requests/requests/pull/4766?src=pr&el=h1) Report
> Merging [#4766](https://codecov.io/gh/requests/requests/pull/4766?src=pr&el=desc) into [master](https://codecov.io/gh/requests/requests/commit/5c1f72e80a7d7ac129631ea5b0c34c7876bc6ed7?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `n/a`.

[![Impacted file tree graph](https://codecov.io/gh/requests/requests/pull/4766/graphs/tree.svg?width=650&token=mZGswIiXLa&height=150&src=pr)](https://codecov.io/gh/requests/requests/pull/4766?src=pr&el=tree)

```diff
@@           Coverage Diff           @@
##           master    #4766   +/-   ##
=======================================
  Coverage   66.89%   66.89%           
=======================================
  Files          15       15           
  Lines        1577     1577           
=======================================
  Hits         1055     1055           
  Misses        522      522
```



------

[Continue to review full report at Codecov](https://codecov.io/gh/requests/requests/pull/4766?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/requests/requests/pull/4766?src=pr&el=footer). Last update [5c1f72e...fdab4fb](https://codecov.io/gh/requests/requests/pull/4766?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


@nateprewitt, thanks for the review. You are totally right and I applied changes + rebase on master :)

We only need to keep `r.prepare*()` at the same indentation level as the definition of `r` to prevent `models.py:159: ValueError: read of closed file`.

What is the status of the PR? Would you mind trigger the request-CI job?

Ping :)
wrap url parsing exceptions from urllib3's PoolManager

This should address #4746 by catching and wrapping all `LocationValueError`s and rewrapping them under the Requests namespace as `InvalidURL`.

# [Codecov](https://codecov.io/gh/requests/requests/pull/4765?src=pr&el=h1) Report
> Merging [#4765](https://codecov.io/gh/requests/requests/pull/4765?src=pr&el=desc) into [master](https://codecov.io/gh/requests/requests/commit/8f20b7dc8f79046d0a1015b9605df5c30fa44197?src=pr&el=desc) will **increase** coverage by `0.02%`.
> The diff coverage is `80%`.

[![Impacted file tree graph](https://codecov.io/gh/requests/requests/pull/4765/graphs/tree.svg?width=650&token=mZGswIiXLa&height=150&src=pr)](https://codecov.io/gh/requests/requests/pull/4765?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master    #4765      +/-   ##
==========================================
+ Coverage   66.77%   66.79%   +0.02%     
==========================================
  Files          15       15              
  Lines        1568     1572       +4     
==========================================
+ Hits         1047     1050       +3     
- Misses        521      522       +1
```


| [Impacted Files](https://codecov.io/gh/requests/requests/pull/4765?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [requests/adapters.py](https://codecov.io/gh/requests/requests/pull/4765/diff?src=pr&el=tree#diff-cmVxdWVzdHMvYWRhcHRlcnMucHk=) | `70.27% <80%> (+0.08%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/requests/requests/pull/4765?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/requests/requests/pull/4765?src=pr&el=footer). Last update [8f20b7d...f3ec42f](https://codecov.io/gh/requests/requests/pull/4765?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
Closing response or session does not immediately terminate the response stream

I'm using `requests` to stream an SSE response. The actual streaming takes place on a separate thread:

```
import threading
import time

import requests
import sys

def read_response(resp):
    try:
        resp_iterator = resp.iter_content(decode_unicode=True)
        for ch in resp_iterator:
            sys.stdout.write(ch)
            sys.stdout.flush()
    except Exception as ex:
        print ex
    print 'Exited at:', time.time()

session = requests.Session()
headers = {}
headers['Cache-Control'] = 'no-cache'
headers['Accept'] = 'text/event-stream'
resp = session.get(my_url, headers=headers, stream=True)

# Kick off the stream in a different thread
thread = threading.Thread(target=read_response, args=[resp])
thread.start()

# Keep streaming for 5 seconds
time.sleep(5)

# Try to close the response
print 'Closing response...'
resp.close()
print 'Closing session...'
session.close()
print 'Closed at:', time.time()
thread.join()
```

In the above example I kick off the stream, wait for 5 seconds, and then close the response and the session. I expected the response iterator to end at this point (either normally or by throwing an exception). But it doesn't end for 25-30 additional seconds. Here's the output I get:

```
Closing response...
Closing session...
Closed at: 1533852042.74
('Connection broken: error("(9, \'EBADF\')",)', error("(9, 'EBADF')",))
Exited at: 1533852067.98
```

Notice the difference between `Closed at` and `Exited at` timestamps.

Any idea why this is? I assume it has something to do with the underlying socket remaining active for a period of time. Is there some way to force termination of the stream/iterator when the response is closed?

## System Information

    $ python -m requests.help

```
{
  "chardet": {
    "version": "3.0.4"
  }, 
  "cryptography": {
    "version": "2.1.4"
  }, 
  "idna": {
    "version": "2.7"
  }, 
  "implementation": {
    "name": "CPython", 
    "version": "2.7.13"
  }, 
  "platform": {
    "release": "4.9.0-6-amd64", 
    "system": "Linux"
  }, 
  "pyOpenSSL": {
    "openssl_version": "1010007f", 
    "version": "17.5.0"
  }, 
  "requests": {
    "version": "2.19.1"
  }, 
  "system_ssl": {
    "version": "1010008f"
  }, 
  "urllib3": {
    "version": "1.23"
  }, 
  "using_pyopenssl": true
}

```

Sessions and responses aren't thread-safe so the behaviour of calling `response.close()` and `session.close()` outside the thread is undefined.
JSON response has double-quotes replaced by single-quotes

I am trying to develop a Python3 script to query GitHub for data on specific repositories, using their v4 GraphQL API with results in JSON format. I took a sample query from the GitHub developer pages, and embedded it into the attached script "github-graphql-test.py" based on a (referenced) example found in a Web search.

The expected output is in the attached file "query-result.txt".

The script produces this result with output piped thru json.tool, but only if all single-quotes are replaced by double-quotes (see commented-out "print" at end of script). Otherwise json.tool gives the error

"Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"

Evidently the JSON formatting on the output is replacing double with single quotes. Is this possibly happening in the requests module, or in another part of the Python library?

[github-graphql-test.py.txt](https://github.com/requests/requests/files/2275998/github-graphql-test.py.txt)
[query-result.txt](https://github.com/requests/requests/files/2275999/query-result.txt)



Hi @DavidFriedmanAMD, the `json()` method is going to return a python representation of the JSON data (i.e. a dictionary) which won’t use double quotes. If you need a valid JSON string with double quotes, you would need to use the json module and call json.dumps, or simply pass the response.content which should be valid json.

Code showing how to convert the unbelievably wrongly named 'json' (because it is NOT LEGAL JSON) response into real, proper json?
requests.exceptions.SSLError: EOF occurred in violation of protocol (_ssl.c:645)

Please refer to our [Stack Overflow tag](https://stackoverflow.com/questions/tagged/python-requests) for guidance.
when i open 32 threads,requets raise this exception.

{
  "chardet": {
    "version": "3.0.4"
  },
  "cryptography": {
    "version": "2.2.2"
  },
  "idna": {
    "version": "2.7"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.5.2"
  },
  "platform": {
    "release": "4.15.0-29-generic",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "1010008f",
    "version": "18.0.0"
  },
  "requests": {
    "version": "2.19.1"
  },
  "system_ssl": {
    "version": "1000207f"
  },
  "urllib3": {
    "version": "1.23"
  },
  "using_pyopenssl": true
}


Hi @xiantang, it doesn't look like there is an obvious link to a specific stack overflow question. This issue tracker is specifically for defects in Requests. The error you're providing is related to a remote server closing the connection on us which we can't do anything about. It's likely you may be being forcibly throttled by the server due to the number of threads you're using.

I'm going to close this for now since we don't have anything suggesting a bug in Requests. If you'd like to leave a link to the StackOverflow question, we can look at following up over there. Thanks!
encoding double backslash

Summary.
Downloading files with \\ in query strings doesn't encode properly
## Expected Result  %5C%5C

## Actual Result %5C


@mharol it sounds like you're passing double backslashes as a string to Requests. Python's native strings are going to treat this as an escape character when passing it to urlencode which is why you're seeing the single %5C. You'll need to pass a raw string (`r'\\'`) with the backslashes if you want them to be interpreted literally.
TLSV1_ALERT_PROTOCOL_VERSION Error when requesting https sites

I get the error "**ssl.SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:598)**" when attempting to access https sites. This is the specific site I got the error on https://www.apartments.com/westhampton-court-apartment-homes-atlanta-ga/sqpw607/ I've been stuck on this issue for over a day at this point, please help.

## Expected Result
I expect to get the data from the URL, not get an error.

## Actual Result
I get the error specified above.

## Reproduction Steps
Try accessing any https site.
requests.get(url)

## System Information
I am on OSX Yosemite 10.10.5 (14F2511)

**python --version**: Python 3.7.0

**import ssl; pprint(ssl.OPENSSL_VERSION)**: 'OpenSSL 0.9.8zg 14 July 2015' (ran from my script)

**openssl version -a**: 
OpenSSL 1.0.2o  27 Mar 2018
built on: reproducible build, date unspecified
platform: darwin64-x86_64-cc
options:  bn(64,64) rc4(ptr,int) des(idx,cisc,16,int) idea(int) blowfish(idx) 
compiler: clang -I. -I.. -I../include  -fPIC -fno-common -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -arch x86_64 -O3 -DL_ENDIAN -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM
OPENSSLDIR: "/usr/local/etc/openssl"

**nano .bash_profile**: 
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH

export PATH="/opt/local/bin:/opt/local/sbin:$PATH"

export PATH="/usr/local/bin:$PATH"
export PATH="/usr/local/opt/openssl/bin:$PATH"
export PATH="/usr/local/opt/python/libexec/bin:$PATH"




Hi there! Thanks for opening this issue. Unfortunately, it seems this is a request for help instead of a report of a defect in the project. Please use [StackOverflow](https://stackoverflow.com) for general usage questions instead and only report defects here.

---

As an aside, your python is using openssl 0.9.8 which doesn't support anything over TLS v1.0 if I remember correctly and per [StackOverflow](http://stackoverflow.com/questions/44316292/ddg#44316583) the website wants to use a higher version of TLS which you're openssl does not support. Futhermore, 3.7.0 was supposed to require a more modern version of openssl so how you've compiled your python to use this ancient version is beyond me. Finally, you completely ignored the request for debugging information we have in the template. Further issues opened like this will be closed immediately.
Add return type on cookies.py

http://docs.python-requests.org/en/master/api/#api-cookies

# [Codecov](https://codecov.io/gh/requests/requests/pull/4755?src=pr&el=h1) Report
> Merging [#4755](https://codecov.io/gh/requests/requests/pull/4755?src=pr&el=desc) into [master](https://codecov.io/gh/requests/requests/commit/e4d214dd763caf9a59dba0b382106cbf9938aa51?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `n/a`.

[![Impacted file tree graph](https://codecov.io/gh/requests/requests/pull/4755/graphs/tree.svg?token=mZGswIiXLa&width=650&height=150&src=pr)](https://codecov.io/gh/requests/requests/pull/4755?src=pr&el=tree)

```diff
@@           Coverage Diff           @@
##           master    #4755   +/-   ##
=======================================
  Coverage   66.79%   66.79%           
=======================================
  Files          15       15           
  Lines        1563     1563           
=======================================
  Hits         1044     1044           
  Misses        519      519
```


| [Impacted Files](https://codecov.io/gh/requests/requests/pull/4755?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [requests/cookies.py](https://codecov.io/gh/requests/requests/pull/4755/diff?src=pr&el=tree#diff-cmVxdWVzdHMvY29va2llcy5weQ==) | `51.68% <ø> (ø)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/requests/requests/pull/4755?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/requests/requests/pull/4755?src=pr&el=footer). Last update [e4d214d...72d96a6](https://codecov.io/gh/requests/requests/pull/4755?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
error on "pip install requests" with chardet

Summary.
pip install requests
Collecting requests
  Using cached https://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69c4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl
Requirement already satisfied: idna<2.8,>=2.5 in /usr/local/lib/python2.7/dist-packages (from requests) (2.6)
Requirement already satisfied: urllib3<1.24,>=1.21.1 in /usr/local/lib/python2.7/dist-packages (from requests) (1.22)
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python2.7/dist-packages (from requests) (2017.11.5)
Installing collected packages: chardet, requests
  Found existing installation: chardet 2.0.1
Cannot uninstall 'chardet'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
## Expected Result

success install

## Actual Result

not installed

## Reproduction Steps

```python
import requests

```

## System Information
ubuntu 14.04
python 2.75


This is likely an issue with you having system package manager installed packages and then trying to globally reinstall those packages with pip. This is not an issue with Requests or chardet, but with what you're attempting to do. You've also not provided the information we request as part of an issue to help you debug, so there's no further work we will do here. I suggest you perform more online searching to find the appropriate solution.
Update all documentation to show Python 3.7 is supported

Official support was added in 6686ac173011a302c26c4aedbd992f96d6e58357.

# [Codecov](https://codecov.io/gh/requests/requests/pull/4750?src=pr&el=h1) Report
> Merging [#4750](https://codecov.io/gh/requests/requests/pull/4750?src=pr&el=desc) into [master](https://codecov.io/gh/requests/requests/commit/e4d214dd763caf9a59dba0b382106cbf9938aa51?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `n/a`.

[![Impacted file tree graph](https://codecov.io/gh/requests/requests/pull/4750/graphs/tree.svg?width=650&src=pr&token=mZGswIiXLa&height=150)](https://codecov.io/gh/requests/requests/pull/4750?src=pr&el=tree)

```diff
@@           Coverage Diff           @@
##           master    #4750   +/-   ##
=======================================
  Coverage   66.79%   66.79%           
=======================================
  Files          15       15           
  Lines        1563     1563           
=======================================
  Hits         1044     1044           
  Misses        519      519
```



------

[Continue to review full report at Codecov](https://codecov.io/gh/requests/requests/pull/4750?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/requests/requests/pull/4750?src=pr&el=footer). Last update [e4d214d...df1cd08](https://codecov.io/gh/requests/requests/pull/4750?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).