Compare commits

...

1144 Commits

Author SHA1 Message Date
Nate Prewitt
970e8cec98 v2.32.1
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11) (push) Has been cancelled
Tests / build (macOS-latest, 3.12) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (macOS-latest, pypy-3.10) (push) Has been cancelled
Tests / build (macOS-latest, pypy-3.9) (push) Has been cancelled
Tests / build (macos-13, 3.8) (push) Has been cancelled
Tests / build (macos-13, 3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.11) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.12) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, pypy-3.10) (push) Has been cancelled
Tests / build (ubuntu-22.04, pypy-3.9) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11) (push) Has been cancelled
Tests / build (windows-latest, 3.12) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
Tests / build (windows-latest, pypy-3.10) (push) Has been cancelled
Tests / build (windows-latest, pypy-3.9) (push) Has been cancelled
Tests / No Character Detection (push) Has been cancelled
2024-05-20 15:02:29 -07:00
Nate Prewitt
d6ebc4a2f1 v2.32.0
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11) (push) Has been cancelled
Tests / build (macOS-latest, 3.12) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (macOS-latest, pypy-3.10) (push) Has been cancelled
Tests / build (macOS-latest, pypy-3.9) (push) Has been cancelled
Tests / build (macos-13, 3.8) (push) Has been cancelled
Tests / build (macos-13, 3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.11) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.12) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, pypy-3.10) (push) Has been cancelled
Tests / build (ubuntu-22.04, pypy-3.9) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11) (push) Has been cancelled
Tests / build (windows-latest, 3.12) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
Tests / build (windows-latest, pypy-3.10) (push) Has been cancelled
Tests / build (windows-latest, pypy-3.9) (push) Has been cancelled
Tests / No Character Detection (push) Has been cancelled
2024-05-20 08:46:49 -07:00
agubelu
9a40d12778 Avoid reloading root certificates to improve concurrent performance (#6667) 2024-05-15 14:07:26 -06:00
Ian Stapleton Cordasco
0c030f78d2 Merge pull request #6702 from nateprewitt/no_char_detection
Allow optional char detection dependencies in post-packaging
2024-05-14 19:15:19 -05:00
Nate Prewitt
555b870eb1 Allow character detection dependencies to be optional in post-packaging steps 2024-05-14 15:26:04 -07:00
Ian Stapleton Cordasco
d6dded3f00 Merge pull request #6700 from franekmagiera/update-redirect-to-invalid-uri-test
Use an invalid URI that will not cause httpbin to throw 500
2024-05-12 16:33:47 -05:00
franekmagiera
bf24b7d8d1 Use an invalid URI that will not cause httpbin to throw 500 2024-05-12 22:08:24 +02:00
Nate Prewitt
2d5f54779a Pin 3.8 and 3.9 runners back to macos-13 (#6688) 2024-04-23 10:50:19 -07:00
Nate Prewitt
f1bb07d39b Merge pull request #6687 from psf/dependabot/github_actions/github/codeql-action-3.25.0
Bump github/codeql-action from 3.24.0 to 3.25.0
2024-04-15 11:01:39 -06:00
dependabot[bot]
60047ade64 Bump github/codeql-action from 3.24.0 to 3.25.0
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.24.0 to 3.25.0.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](e8893c57a1...df5a14dc28)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-15 16:40:35 +00:00
Ian Stapleton Cordasco
31ebb8102c Merge pull request #6682 from frenzymadness/pytest8
Fix compatibility with pytest 8
2024-04-11 14:49:35 -05:00
Lumir Balhar
cc23d1c644 Fix compatibility with pytest 8
`pytest.warns(None)` has been deprecated in pytest 7.0.0
and it's no longer working in pytest 8.

Resolves: https://github.com/psf/requests/issues/6679
2024-04-11 21:10:36 +02:00
Nate Prewitt
0790ea4250 Merge pull request #6680 from mbeijen/rfc9110
Add rfc9110 HTTP status code names
2024-04-11 07:10:57 -07:00
Michiel W. Beijen
e45b428960 Add rfc9110 HTTP status code names
RFC 9110 _HTTP Semantics_ obsoletes some earlier RFCs which defined HTTP
1.1. It adds some status codes that were previously only used for
WebDAV to HTTP _proper_ after making the names somewhat more generic.

See https://www.rfc-editor.org/rfc/rfc9110.html#name-changes-from-rfc-7231

This commit adds the http status code names from that RFC.
2024-04-08 21:48:24 +02:00
Nate Prewitt
2a438c27b5 Merge pull request #6677 from psf/dependabot/github_actions/actions/setup-python-5.1.0
Bump actions/setup-python from 5.0.0 to 5.1.0
2024-04-01 10:36:47 -07:00
dependabot[bot]
2daa7b52a7 Bump actions/setup-python from 5.0.0 to 5.1.0
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 5.0.0 to 5.1.0.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](0a5c615913...82c7e631bb)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-01 17:00:20 +00:00
Ian Stapleton Cordasco
8dd3b26bf5 Merge pull request #6302 from flysee/main
Fix the proxy_bypass_registry function all returning true in some cases.
2024-03-18 16:38:16 -05:00
flysee
13d892bdbe Additional should_bypass_proxies function test cases 2024-03-18 22:33:17 +08:00
flysee
1604e20fc8 Fix the proxy_bypass_registry function all returning true in some cases. 2024-03-18 15:36:36 +08:00
Ian Stapleton Cordasco
eeafb6ab3a Merge pull request #6662 from sigmavirus24/fix-tls-floppy
Add local TLS server
2024-03-14 06:25:24 -05:00
Ian Stapleton Cordasco
a94e9b5308 Add local TLS server
This also adds certificates for testing purposes and files to make it
easy to generate/regenerate them.

This also replaces an existing test of how we utilize our pool manager
such that we don't connect to badssl.com

Finally, this adds additional context parameters for our pool manager to
account for mTLS certificates used by clients to authenticate to a
server.
2024-03-14 06:06:22 -05:00
Ian Stapleton Cordasco
a58d7f2ffb Merge pull request #6655 from sigmavirus24/fix-tls-floppy
Use TLS settings in selecting connection pool
2024-03-11 06:21:59 -05:00
Ian Stapleton Cordasco
c0813a2d91 Use TLS settings in selecting connection pool
Previously, if someone made a request with `verify=False` then made a
request where they expected verification to be enabled to the same host,
they would potentially reuse a connection where TLS had not been
verified.

This fixes that issue.
2024-03-06 11:28:13 -06:00
Ian Stapleton Cordasco
eea3bbf9ac Merge pull request #6562 from amkarn258/issue-6223
every chardet package maps to requests.packages.chardet.* package respectively
2024-02-23 06:26:38 -06:00
Ian Stapleton Cordasco
f3f2611d83 Merge pull request #6583 from EFord36/fix-broken-links
Fix broken links in docs
2024-02-23 05:30:46 -06:00
Elliot Ford
a0e79bad05 update broken rfc link
ietf seems appropriate here - it's used elsewhere in the requets docs in
several places.
2024-02-23 10:26:21 +00:00
Elliot Ford
0a7f662aa7 Make example URL format a literal rather than an actual link
The rendered docs 'auto-link' this, which might encourage users to click
the link, even though it doesn't go anywhere.
2024-02-23 10:26:21 +00:00
Elliot Ford
5f1c3c22ff remove section with broken link to survey 2024-02-23 10:26:21 +00:00
Elliot Ford
541aa80ca3 update urllib3 docs link 2024-02-23 10:26:21 +00:00
Elliot Ford
d3b3399ece update authors github link
Update account link for original author which has changed.
2024-02-23 10:25:50 +00:00
Elliot Ford
0ec2780c29 update broken github pagination link 2024-02-23 10:25:50 +00:00
Ian Stapleton Cordasco
b8be93a721 Merge pull request #6589 from bruceadams/super_len_str_utf-8
Enhance `super_len` to count encoded bytes for str
2024-02-22 18:53:25 -06:00
Ian Stapleton Cordasco
3587a5f869 Merge pull request #6644 from sigmavirus24/bug/6643
Trim excess leading path separators
2024-02-22 18:49:42 -06:00
Ian Stapleton Cordasco
60389df6d6 Trim excess leading path separators
A URL with excess leading / (path-separator)s would cause urllib3 to
attempt to reparse the request-uri as a full URI with a host and port.
This bypasses that logic in ConnectionPool.urlopen by replacing these
leading /s with just a single /.

Closes #6643
2024-02-22 18:36:44 -06:00
Nate Prewitt
382fc2c0c6 Merge pull request #6629 from Tarty/fix-6628-jsondecode-error-not-deserializable
Fix #6628 - JSONDecodeError are not deserializable
2024-02-22 12:27:37 -08:00
Nate Prewitt
7a13c041db Merge pull request #6642 from nateprewitt/drop_python_37
Drop support for CPython 3.7
2024-02-20 15:44:43 -08:00
Nate Prewitt
58cea7a728 Drop support for CPython 3.7 2024-02-20 15:37:46 -08:00
Ian Stapleton Cordasco
9439fad038 Merge pull request #6641 from nateprewitt/fix_ci
Fix CI
2024-02-20 17:32:57 -06:00
Nate Prewitt
8fa4302322 Update Sphinx to work with latest readthedocs requirements 2024-02-20 15:04:38 -08:00
Nate Prewitt
28855fd43a Update supported copies of PyPy
Dropped support for pypy-3.7 and pypy-3.8 which are no longer maintained by upstream.
Added support for pypy-3.10.
2024-02-20 13:58:26 -08:00
Nate Prewitt
5fc10bf1f5 Fix httpbin pin for test suite 2024-02-20 13:37:25 -08:00
Ian Stapleton Cordasco
46c1a3d8c8 Merge pull request #6640 from nateprewitt/community_docs_cleanup
Cleanup defunct links from community docs page
2024-02-20 14:04:33 -06:00
Nate Prewitt
6106a63eb6 Cleanup defunct links from community docs page 2024-02-20 11:58:35 -08:00
Ian Stapleton Cordasco
4f3f189d6b Merge pull request #6632 from psf/dependabot/github_actions/github/codeql-action-3.24.0
Bump github/codeql-action from 3.23.0 to 3.24.0
2024-02-05 20:54:26 -06:00
dependabot[bot]
a5a0e4b587 Bump github/codeql-action from 3.23.0 to 3.24.0
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.23.0 to 3.24.0.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](e5f05b81d5...e8893c57a1)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-05 16:38:01 +00:00
Thomas Dehghani
3ff3ff21dd Fix #6628 - JSONDecodeError are not deserializable
requests.exceptions.JSONDecodeError are not deserializable: calling
`pickle.dumps` followed by `pickle.loads` will trigger an error.

This is particularly a problem in a process pool, as an attempt to
decode json on an invalid json document will result in the entire
process pool crashing.

This is due to the MRO of the `requests.exceptions.JSONDecodeError`
class: the `__reduce__` method called when pickling an instance is not
the one from the JSON library parent: two out of three args expected
for instantiation will be dropped, and the instance can't be
deserialised.

By specifying in the class which parent `__reduce__` method should be
called, the bug is fixed as all args are carried over in the resulting
pickled bytes.
2024-01-31 17:13:53 +01:00
Ian Stapleton Cordasco
96b22fa18c Merge pull request #6619 from psf/dependabot/github_actions/github/codeql-action-3.23.0
Bump github/codeql-action from 3.22.11 to 3.23.0
2024-01-08 11:56:01 -06:00
dependabot[bot]
b0e6c9bf85 Bump github/codeql-action from 3.22.11 to 3.23.0
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.22.11 to 3.23.0.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](b374143c11...e5f05b81d5)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-08 17:01:37 +00:00
Ian Stapleton Cordasco
72eccc8dd8 Merge pull request #6612 from miketheman/fix-docs-urls
docs: specify sphinx dirhtml builder, use references instead of absolutes
2023-12-23 12:33:48 -06:00
Mike Fiedler
25939d8784 add myself
Signed-off-by: Mike Fiedler <miketheman@gmail.com>
2023-12-23 18:15:33 +00:00
Mike Fiedler
bfba9dc68c docs: replace concrete URLs with references
Any development links will now refer back to the generated docs.

Signed-off-by: Mike Fiedler <miketheman@gmail.com>
2023-12-23 18:09:55 +00:00
Mike Fiedler
f23346a9b8 Revert "Merge pull request #6605 from jaikishpai/fix-#6604"
This reverts commit 1396eb6f7a, reversing
changes made to e4c821a247.
2023-12-23 17:36:34 +00:00
Ian Stapleton Cordasco
f3f9784419 Merge pull request #6613 from miketheman/add-socks-label
docs: add label to socks heading
2023-12-23 11:24:56 -06:00
Mike Fiedler
b5bd0f14cc docs: add label to socks heading
When trying to link via intersphinx, a label must be used.
Otherwise a full URL is required, which is less desirable.

Signed-off-by: Mike Fiedler <miketheman@gmail.com>
2023-12-23 17:17:34 +00:00
Mike Fiedler
242d3113c0 docs: specify sphinx dirhtml builder
With the requirement of a configuration file, the default builder
of `dirhtml` that RTD used to use is no longer specified.
This leads to URLs ending in `.html` now, which
breaks other exisitng references.

Refs: #6603
Refs: https://docs.readthedocs.io/en/stable/config-file/v2.html#sphinx-builder
Refs: https://www.sphinx-doc.org/en/master/usage/builders/index.html#sphinx.builders.dirhtml.DirectoryHTMLBuilder

Signed-off-by: Mike Fiedler <miketheman@gmail.com>
2023-12-23 16:16:50 +00:00
Nate Prewitt
1396eb6f7a Merge pull request #6605 from jaikishpai/fix-#6604
fix for ##6604
2023-12-19 22:17:55 -08:00
Nate Prewitt
e4c821a247 Merge pull request #6607 from psf/dependabot/github_actions/github/codeql-action-3.22.11
Bump github/codeql-action from 2.22.1 to 3.22.11
2023-12-18 09:30:42 -08:00
dependabot[bot]
421b1f1757 Bump github/codeql-action from 2.22.1 to 3.22.11
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.22.1 to 3.22.11.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](fdcae64e14...b374143c11)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-18 16:39:47 +00:00
Jaikish Pai
1447bccc05 fix for ##6604 2023-12-17 22:34:30 +01:00
Ian Stapleton Cordasco
3b5978fc5d Merge pull request #6592 from atatuzuner61/bug/6584
"TOO_EARLY" type definition for status code 425
2023-12-16 14:24:02 -06:00
Ian Stapleton Cordasco
1ddf014f47 Merge pull request #6600 from MestreLion/MestreLion-connection-timeout-note
Add note on connection timeout being larger than specified. Fix #5773
2023-12-16 07:30:18 -06:00
Ian Stapleton Cordasco
92f9e431c9 Update docs/user/advanced.rst
Add note about wall clock too
2023-12-16 07:29:50 -06:00
Ian Stapleton Cordasco
951dd15fa6 Update docs/user/advanced.rst
fix indentation for note so it renders properly
2023-12-16 07:26:23 -06:00
Ian Stapleton Cordasco
51d0d83eaf Merge pull request #6603 from nsoranzo/rtd_config
Add now mandatory readthedocs config file
2023-12-16 07:24:37 -06:00
Nicola Soranzo
c7c2ebf1a7 Add now mandatory readthedocs config file
Docs builds currently fail with:

```
Problem in your project's configuration. No default configuration file found at repository's root. See https://docs.readthedocs.io/en/stable/config-file/
```

See e.g. https://readthedocs.org/projects/requests/builds/22842479/
2023-12-15 20:59:56 +00:00
Rodrigo Silva
a64f32ba45 Add note on connection timeout being larger than specified. Fix #5773
On servers with multiple IPs, such as IPv4 and IPv6, `urllib3` tries each address sequentially until one successfully connects, using the specified timeout for _each_ attempt, leading to a total connection timeout that is a _multiple_ of the requested time.
2023-12-13 10:05:12 -03:00
Nate Prewitt
a25fde6989 Merge pull request #6599 from psf/dependabot/github_actions/actions/setup-python-5.0.0 2023-12-11 08:11:07 -08:00
dependabot[bot]
ba67dc8dcc Bump actions/setup-python from 4.7.0 to 5.0.0
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4.7.0 to 5.0.0.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](61a6322f88...0a5c615913)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-11 16:07:15 +00:00
Nate Prewitt
769bc3ae5c Merge pull request #6596 from psf/fix-autoclose-automtaion
Update close-issues.yml
2023-12-01 09:18:02 -08:00
Ian Stapleton Cordasco
d6ffd868ee Update close-issues.yml
I noticed the auto-labeling was working but not the auto-closing. Looking at recent actions runs I see that we need to specify the token even if we're not giving our own special token. See https://github.com/psf/requests/actions/runs/7057701782/job/19211845073#step:2:13 for additional context, namely

```
 gh: To use GitHub CLI in a GitHub Actions workflow, set the GH_TOKEN environment variable. Example:
  env:
    GH_TOKEN: ${{ github.token }}
```
2023-12-01 08:05:59 -06:00
Bruce Adams
3fd309a5c1 Enhance super_len to count encoded bytes for str
This fixes issue #6586
2023-11-29 15:42:57 -05:00
Ata Tuzuner
ec84f2c539 Fixes to test 2023-11-29 12:27:18 -05:00
Ata Tuzuner
889910c77a Added tests for status code 425 definitions. 2023-11-29 12:24:15 -05:00
Ata Tuzuner
b37878d340 Too early definition added to 425 status code type 2023-11-28 18:12:22 -05:00
Bruce Adams
f6707042d8 Unit test for string containing multi-byte UTF-8
There are two tests here. One demonstrating existing, correct
behavior for `data=bytes`, and another, failing, test for the case
where `data=string` and the string contains multi-byte UTF-8.
2023-11-27 17:27:43 -05:00
Ian Stapleton Cordasco
0b4d494192 Merge pull request #6581 from EFord36/typo-fix
fix docstring typo: a -> as
2023-11-22 09:10:47 -06:00
Elliot Ford
15849947ec fix docstring typo: a -> as 2023-11-22 11:34:04 +00:00
Ian Stapleton Cordasco
c6de5a14e5 Merge pull request #6580 from psf/dependabot/github_actions/dessant/lock-threads-5.0.0
Bump dessant/lock-threads from 4.0.1 to 5.0.0
2023-11-20 10:37:07 -06:00
dependabot[bot]
e66a07b286 Bump dessant/lock-threads from 4.0.1 to 5.0.0
Bumps [dessant/lock-threads](https://github.com/dessant/lock-threads) from 4.0.1 to 5.0.0.
- [Release notes](https://github.com/dessant/lock-threads/releases)
- [Changelog](https://github.com/dessant/lock-threads/blob/main/CHANGELOG.md)
- [Commits](be8aa5be94...d42e5f4980)

---
updated-dependencies:
- dependency-name: dessant/lock-threads
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-20 16:28:17 +00:00
Nate Prewitt
9e98a8749a Merge pull request #6574 from msea1/matthew/fix_space 2023-11-15 23:44:49 -08:00
Matthew Carruth
c32b046243 Fix missing space in error message 2023-11-15 17:00:28 -08:00
mayank
89cde235be checkstyle 2023-11-04 23:20:21 +05:30
amkarn258
d7490c9d2d Update src/requests/packages.py
Co-authored-by: Ian Stapleton Cordasco <graffatcolmingov@gmail.com>
2023-10-31 22:36:39 +05:30
mayank
e9b1217cff added handling for chardet and charset_normalizer imports 2023-10-31 20:37:59 +05:30
mayank
ad761abcdd every chardet package maps to requests.packages.chardet.* package respectively 2023-10-31 00:50:10 +05:30
Nate Prewitt
839a8edec3 Merge pull request #6552 from swims-hjkl/issue/test_header_validation
#6551  - assert statements for test test_header_validation
2023-10-17 23:08:52 -07:00
sumedhrao7
a8e9c1b436 added assert statements into tests/test_requests/test_header_validation in regards to the issue #6551 2023-10-18 07:40:50 +05:30
Nate Prewitt
b55bb15c35 Merge pull request #6527 from sigmavirus24/update-templates
Autoclose specific issue templates
2023-10-11 09:29:20 -07:00
Ian Stapleton Cordasco
8187768622 Update close-issues.yml
Remove references to GITHUB_TOKEN/MY_TOKEN
2023-10-11 08:19:57 -05:00
Ian Stapleton Cordasco
f75b9504fc Update close comment
Co-authored-by: Nate Prewitt <nate.prewitt@gmail.com>
2023-10-11 08:19:14 -05:00
Nate Prewitt
8199a2b389 Merge pull request #6548 from psf/dependabot/github_actions/github/codeql-action-2.22.1
Bump github/codeql-action from 2.21.3 to 2.22.1
2023-10-09 09:49:28 -07:00
dependabot[bot]
42a3b5cce8 Bump github/codeql-action from 2.21.3 to 2.22.1
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.21.3 to 2.22.1.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](5b6282e01c...fdcae64e14)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-09 16:29:55 +00:00
Nate Prewitt
f5a7aefc2d Fix urllib3 pin in setup.cfg (#6545) 2023-10-06 16:34:24 -06:00
Nate Prewitt
ee93fac6b2 Merge pull request #6538 from psf/dependabot/github_actions/actions/checkout-4.1.0
Bump actions/checkout from 4.0.0 to 4.1.0
2023-09-25 11:30:05 -07:00
dependabot[bot]
a775435c4b Bump actions/checkout from 4.0.0 to 4.1.0
Bumps [actions/checkout](https://github.com/actions/checkout) from 4.0.0 to 4.1.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](3df4ab11eb...8ade135a41)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-25 16:28:35 +00:00
Ian Stapleton Cordasco
6c8d9b1d0f Autoclose specific issue templates
We spend a fair amount of time closing issues because people don't read
the template closely or understand what they're being told. Let's take
advantage of being able to auto-label an issue based on the template and
then trigger a workflow to auto-magically close the issue with a message
and lock the issue.
2023-09-13 09:33:58 -05:00
Ian Stapleton Cordasco
881281250f Merge pull request #6519 from psf/dependabot/github_actions/actions/checkout-4.0.0
Bump actions/checkout from 3.6.0 to 4.0.0
2023-09-04 19:17:08 -05:00
dependabot[bot]
29fc8d1e93 Bump actions/checkout from 3.6.0 to 4.0.0
Bumps [actions/checkout](https://github.com/actions/checkout) from 3.6.0 to 4.0.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](f43a0e5ff2...3df4ab11eb)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-04 16:21:27 +00:00
Ian Stapleton Cordasco
8b560ecb24 Merge pull request #6517 from jnhyperion/remove-pytest-ini
Remove pytest.ini in MANIFEST.in since it does not exist anymore
2023-08-29 09:27:10 -05:00
Johnny.H
4585a7fbda remove pytest.ini since it does not exist anymore 2023-08-29 13:41:49 +08:00
Ian Stapleton Cordasco
16dc70df34 Merge pull request #6516 from psf/dependabot/github_actions/actions/checkout-3.6.0
Bump actions/checkout from 3.5.3 to 3.6.0
2023-08-28 14:05:56 -05:00
dependabot[bot]
bea231b033 Bump actions/checkout from 3.5.3 to 3.6.0
Bumps [actions/checkout](https://github.com/actions/checkout) from 3.5.3 to 3.6.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](c85c95e3d7...f43a0e5ff2)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-28 16:12:37 +00:00
13steinj
2ee5b0b01c Fix documentation monthly download badge (#6508) 2023-08-18 11:01:26 -06:00
Jonas Schell
89f0eb91b3 fix monthly download badge (#6507) 2023-08-16 08:16:53 -07:00
Nate Prewitt
005571d118 Remove pytest-mock requirement (#6505) 2023-08-13 16:08:21 -07:00
Nate Prewitt
d63e94f552 Move to src directory (#6506) 2023-08-13 14:46:13 -07:00
Nate Prewitt
e9fa2e2da3 Add 3.12 classifier and tox configuration (#6503) 2023-08-13 12:56:18 -07:00
Nate Prewitt
678fca8423 Upgrade to httpbin 0.10.0 (#6496) 2023-08-13 09:56:53 -07:00
Nate Prewitt
d8152769ce Merge pull request #6501 from psf/dependabot/github_actions/actions/checkout-3.5.3 2023-08-12 13:15:39 -07:00
Nate Prewitt
9ff1a25ef5 Merge pull request #6502 from psf/dependabot/github_actions/github/codeql-action-2.21.3
Bump github/codeql-action from 1.1.39 to 2.21.3
2023-08-12 12:50:52 -07:00
dependabot[bot]
4bd06cd325 Bump actions/checkout from 2.7.0 to 3.5.3
Bumps [actions/checkout](https://github.com/actions/checkout) from 2.7.0 to 3.5.3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2.7.0...c85c95e3d7251135ab7dc9ce3241c5835cc595a9)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 19:37:22 +00:00
Nate Prewitt
09a241f59e Merge pull request #6500 from psf/dependabot/github_actions/actions/setup-python-4.7.0
Bump actions/setup-python from 2.3.4 to 4.7.0
2023-08-12 12:36:48 -07:00
Nate Prewitt
6ad493650c Merge pull request #6499 from psf/dependabot/github_actions/dessant/lock-threads-4.0.1
Bump dessant/lock-threads from 3.0.0 to 4.0.1
2023-08-12 12:24:59 -07:00
dependabot[bot]
9acca90bf6 Bump github/codeql-action from 1.1.39 to 2.21.3
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 1.1.39 to 2.21.3.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](231aa2c8a8...5b6282e01c)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 19:03:30 +00:00
dependabot[bot]
c7933453cf Bump actions/setup-python from 2.3.4 to 4.7.0
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 2.3.4 to 4.7.0.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v2.3.4...61a6322f88396a6271a6ee3565807d608ecaddd1)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 19:03:22 +00:00
dependabot[bot]
ea49261a27 Bump dessant/lock-threads from 3.0.0 to 4.0.1
Bumps [dessant/lock-threads](https://github.com/dessant/lock-threads) from 3.0.0 to 4.0.1.
- [Release notes](https://github.com/dessant/lock-threads/releases)
- [Changelog](https://github.com/dessant/lock-threads/blob/main/CHANGELOG.md)
- [Commits](e460dfeb36...be8aa5be94)

---
updated-dependencies:
- dependency-name: dessant/lock-threads
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 19:03:17 +00:00
Nate Prewitt
8112fcc7be Pre commit update (#6498) 2023-08-12 12:03:10 -07:00
Nate Prewitt
2c193bda0c Pin GHA workflows and add dependabot to keep them up to date (#6497) 2023-08-12 12:02:58 -07:00
Ian Stapleton Cordasco
34a64bc65e Merge pull request #6266 from elprimato/spdx-conform-license
Change to SPDX conform license string
2023-08-12 13:51:42 -05:00
Nate Prewitt
9b6c62e235 Merge branch 'main' into spdx-conform-license 2023-08-12 11:37:15 -07:00
Joren Vrancken
cb7fcd7ebd Specify that Session.headers needs to be set to a OrderedDict in Header Ordering docs (#6475) 2023-08-12 10:53:36 -07:00
Calle Svensson
aa4cc78627 Add note about adapter prefix match to docs (#6465) 2023-07-29 21:05:44 -07:00
Kevin Kirsche
dfe46c1b7f refactor: prefer dictionary comphrension to loop (#6187) 2023-07-29 18:55:18 -07:00
Alexandre Erwin Ittner
2ecdb68561 Update reference to "cookielib" to "cookiejar" in documentation (#6214) 2023-07-29 18:50:43 -07:00
cpzt
fecf3dc472 add docstring parameter hooks (#6456) 2023-07-29 18:01:42 -07:00
Matthew Armand
cdbc2e2715 Add an Example for automatic retries to the Advanced Usage docs (#6258)
- While Requests doesn't automatically retry failures, this ability is a very common advanced use case in real world applications.
- Although there's a mention of this ability on the HTTPAdapter class docs, it's a bit buried and not very specific.
- It makes sense then to have an Example in the HTTPAdapter section of the Advanced Usage docs with a basic template for how this can be accomplished with Requests.
2023-07-03 13:38:22 -07:00
Boris Verkhovskiy
22db55a889 Fix doc typo (#6467) 2023-06-26 11:09:23 -06:00
Nate Prewitt
6e5b15d542 Fix linting issues 2023-05-22 09:36:22 -06:00
Nate Prewitt
147c8511dd v2.31.0
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11) (push) Has been cancelled
Tests / build (macOS-latest, 3.12-dev) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (macOS-latest, pypy-3.8) (push) Has been cancelled
Tests / build (macOS-latest, pypy-3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.11) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.12-dev) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, pypy-3.8) (push) Has been cancelled
Tests / build (ubuntu-22.04, pypy-3.9) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11) (push) Has been cancelled
Tests / build (windows-latest, 3.12-dev) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
Tests / build (windows-latest, pypy-3.8) (push) Has been cancelled
Tests / build (windows-latest, pypy-3.9) (push) Has been cancelled
2023-05-22 09:10:32 -06:00
Nate Prewitt
74ea7cf7a6 Merge pull request from GHSA-j8r2-6x86-q33q 2023-05-22 09:08:57 -06:00
Thomas Grainger
3022253346 test on pypy 3.8 and pypy 3.9 on windows and macos (#6424) 2023-05-15 09:04:21 -06:00
Thomas Grainger
b639e66c81 test on py3.12 (#6448)
* test on py3.12

* update to pytest-httpbin==2.0.0
2023-05-13 08:10:56 -06:00
Syed Saifullah
d3d504436e Fixed a small typo (#6452) 2023-05-09 10:55:33 -06:00
Nate Prewitt
2ad18e0e10 v2.30.0
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (false, ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.11) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.9) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2023-05-03 09:39:44 -06:00
Quentin Pradet
f2629e9e3c Remove strict parameter (#6434) 2023-04-28 13:17:10 -06:00
Nate Prewitt
87d63de873 v2.29.0
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (false, ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.11) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-22.04, 3.9) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2023-04-26 09:19:11 -06:00
Thomas Grainger
51716c4ef3 enable the warnings plugin (#6416) 2023-04-22 18:00:22 -06:00
Thomas Grainger
a7da1ab349 try on ubuntu 22.04 (#6418) 2023-04-22 17:53:09 -06:00
Thomas Grainger
dfc3e24338 pin cryptography<40 on pypy 3.7 (#6421)
* pin cryptography<40 on pypy 3.7
2023-04-22 17:41:27 -06:00
Levi
26bea1e498 Use urllib3 native chunking ability (#6226)
* Fix #3844 
* Use urllib for chunked 

---------

Co-authored-by: James Pickering <james.pickering@xml-solutions.com>
Co-authored-by: Leon Verrall <LVerrall@slb.com>
2023-04-22 17:32:51 -06:00
Seth Michael Larson
7f694b79e1 Allow str/bytes subclasses to be used as header parts 2023-03-03 14:39:02 -06:00
Yifang Zhu
e90852d20c Make json doc strings consistent (#6368) 2023-03-02 21:32:49 -08:00
Nate Prewitt
ec78348c4b Upgrade lint.yml action (#6370) 2023-03-02 20:45:27 -08:00
Boris Verkhovskiy
46188256ee Response.raw.read() returns bytes (#6365) 2023-02-27 08:31:15 -07:00
Quentin Pradet
15585909c3 Support missing SNIMissingWarning in tests (#6336) 2023-01-21 01:44:33 -07:00
Matthew Feickert
16a17a3ca7 fix: Remove '<4' from python_requires (#6333)
* As discussed in https://discuss.python.org/t/use-of-less-than-next-major-version-e-g-4-in-python-requires-setup-py/1066
  and other places by the PyPA, use of upper bounds with python_requires
  for future versions of Python is unintended use of python_requires and
  actively discouraged.
2023-01-18 22:37:24 -07:00
Nate Prewitt
61c324da43 v2.28.2
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (false, ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.11) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.9) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2023-01-12 09:16:09 -07:00
Ashish Kurmi
eb07385b02 ci: add minimum GitHub token permissions for workflows (#6236)
Signed-off-by: Ashish Kurmi <akurmi@stepsecurity.io>
2023-01-11 15:06:53 -07:00
Bruno Alla
2745db131a Switch to Python 3.11 final on CI and add to tox file (#6325) 2023-01-06 11:32:31 -07:00
ch-iv
ec553c275f Update flake8 repo and version (#6317) 2022-12-25 21:24:16 -07:00
Ian Stapleton Cordasco
ac3be98b19 Merge pull request #6291 from oliviacrain/docs/git-clone-protocol
Replace git protocol URL in docs with an HTTPS URL
2022-11-21 16:06:01 -06:00
Olivia Crain
192083576d Replace git protocol URL in docs with an HTTPS URL 2022-11-21 14:01:02 -06:00
Volker Schaus
53a0562331 change to SPDX conform license string 2022-10-23 18:35:43 +00:00
Ian Stapleton Cordasco
1e62a3ec18 Merge pull request #6262 from winmorre/docs-update/#6260
JSONDecodeError included in the documentation
2022-10-21 11:37:47 -05:00
reeko234
7908ad3af9 JSONDecodeError included in the documentation #6260 2022-10-21 07:42:58 +00:00
deedy5
c57f1f0ca1 Allow charset normalizer >=2 and <4 (#6261) 2022-10-20 12:26:18 -06:00
Ian Stapleton Cordasco
7104ad4b13 Merge pull request #6234 from jaap3/patch-1
Fix CURL_CA_BUNDLE override example
2022-09-09 14:10:14 -05:00
Jaap Roes
da246958b4 Fix CURL_CA_BUNDLE override example
Promote REQUESTS_CA_BUNDLE as it is looked at first
2022-09-07 09:48:59 +02:00
David Cain
177dd90f18 Remove Python 2 mention on chardet behavior (#6204) 2022-07-27 09:22:21 -08:00
Miloslav Pojman
786255613b Remove Python 2 mention from tox (#6200) 2022-07-20 17:13:36 -06:00
Sergey Lyapustin
bda7f0171f Fixed warnings message to suggest using secure protocol. (#6188) 2022-06-29 12:41:49 -06:00
Nate Prewitt
4d394574f5 v2.28.1
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (false, ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11-dev) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.11-dev) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.9) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11-dev) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2022-06-29 09:09:11 -06:00
Kevin Kirsche
16b418b44a Use yield from instead of looping yield (#6170) 2022-06-28 20:08:26 -06:00
Lumír 'Frenzy' Balhar
0e28c8f1dc Allow charset normalizer >=2 and <3 (#6169) 2022-06-28 20:01:42 -06:00
Wong Hoi Sing Edison
73793ce43e Update Dependency with chardet>=3.0.2,<6 (#6179)
https://github.com/chardet/chardet/releases/tag/5.0.0 was released on
2022-06-25 with remove of Python 3.6 support, which also align with our
Python > 3.6 requirement.

Signed-off-by: Wong Hoi Sing Edison <hswong3i@pantarei-design.com>
2022-06-27 20:25:58 -06:00
Nate Prewitt
da9996fe4d v2.28.0
Some checks failed
Lint code / lint (push) Has been cancelled
Tests / build (false, ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.11-dev) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.11-dev) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.9) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.11-dev) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2022-06-09 08:42:10 -06:00
Nate Prewitt
1dcf3b7122 Add GitHub action to automate linting (#6157) 2022-06-08 13:11:11 -06:00
Nate Prewitt
e36f34597c Add valdation for header name (#6154) 2022-06-08 12:03:56 -06:00
Nate Prewitt
60865f21ae Run 3.11 CI on all platforms (#6155) 2022-06-08 10:12:53 -06:00
Olivier Gayot
3af2f456d8 Fix output of test_lowlevel tests in case of timeout (#6136)
Signed-off-by: Olivier Gayot <olivier.gayot@canonical.com>
2022-06-08 10:02:42 -06:00
Nate Prewitt
0f358eabe6 Reduce lock thread runs to daily (#6150) 2022-06-01 11:51:04 -06:00
Nate Prewitt
210095fd08 Tolerate bad registry entries in Windows proxy settings (#6149) 2022-06-01 11:36:26 -06:00
Nate Prewitt
a5e7169e75 Cleanup the docs sidebar (#6144) 2022-05-26 12:45:57 -07:00
davidshivaji
79f2ec3acc Grammar fix (#6133) 2022-05-13 10:36:13 -06:00
Mickaël Schoentgen
cb233a101d Fix several ResourceWarnings in test_requests.py (#4766) 2022-05-10 19:04:17 -06:00
Nate Prewitt
40956723f2 Add .git-blame-ignore-revs 2022-04-29 15:39:22 -06:00
Nate Prewitt
2a6f290bc0 Add automatic code formatting to Requests (#6095) 2022-04-29 13:16:58 -06:00
Nate Prewitt
2d5517682b Fix inconsistent exception for JSONDecode error (#6097)
When calling .json() it was possible to raise a
requests.exceptions.JSONDecodeError or ValueError
depending on whether the encoding is set.
2022-03-28 12:51:27 -06:00
Nate Prewitt
8bce583b95 Farewell, sweet Concorde!
Formally removing any remaining vestiges of Python 2 from Requests.
We'll also leave behind Python 3.6 while we're at it.
2022-03-25 10:50:33 -06:00
Ian Stapleton Cordasco
79f60274f7 Merge pull request #6074 from nateprewitt/curl_ca_bundle
Fix environment CA Bundle resolution
2022-02-26 07:39:28 -06:00
Nate Prewitt
79c4a017fe Fix environment CA Bundle resolution 2022-02-25 11:25:20 -07:00
Ian Stapleton Cordasco
5e749546a2 Merge pull request #6068 from nateprewitt/sess_prox_warn
Reword proxies section and add warning
2022-02-19 17:04:06 -06:00
Ian Stapleton Cordasco
3eed0512a6 Merge pull request #6069 from nateprewitt/jinja_fix
Pin markupsafe for older versions of Jinja2
2022-02-19 07:34:48 -06:00
Nate Prewitt
3ed60078e2 Fix jinja 2022-02-18 18:33:43 -07:00
Nate Prewitt
15fde024f2 Reword proxies section and add warning 2022-02-18 18:18:23 -07:00
Nate Prewitt
95f4567336 Wrap urllib3's SSLError as requests' SSLError (#6057) 2022-02-05 11:56:05 -07:00
Nate Prewitt
7ae38876b1 Merge pull request #5978 from sha016/all-proxy-docs
Co-authored-by: Seth Michael Larson <sethmichaellarson@gmail.com>
2022-02-02 11:03:26 -07:00
Seth Michael Larson
2c20474bfe Update advanced.rst 2022-02-02 11:56:27 -06:00
Chavithra
24dfbfde55 Update quickstart.rst : fixing brotlicffi link (#6044) 2022-01-17 11:30:24 -07:00
chyzzqo2
fa1b0a367a Initialize JsonDecodeError before initializing IOError (#6036)
That way we get the formated error message

Co-authored-by: Peter <cHYzZQo@netflix.com>
2022-01-13 08:42:49 -07:00
Ian Stapleton Cordasco
d15a3b6e2e Merge pull request #6042 from nateprewitt/lock_thread_spam
Disable lock-threads on forks
2022-01-11 11:42:00 -06:00
Nate Prewitt
48676caf57 Disable lock-threads on forks 2022-01-11 08:24:39 -07:00
Nate Prewitt
d718e75383 Start testing on 3.11 dev branch (#6037) 2022-01-07 12:07:31 -07:00
Marwan
620ed4fc52 Move socks testing requirement into requirements-dev.txt (#6035) 2022-01-06 10:57:59 -07:00
Nate Prewitt
31a89d9c84 v2.27.1
Some checks failed
Tests / build (macOS-latest, 2.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.6) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-18.04, 2.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.6) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.9) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy3) (push) Has been cancelled
Tests / build (windows-latest, 2.7) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.6) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2022-01-05 08:35:04 -07:00
Ian Stapleton Cordasco
8fa9724398 Merge pull request #6028 from nateprewitt/prox_auth_fix
Fix auth parsing for proxies
2022-01-04 10:04:25 -06:00
Nate Prewitt
38f3f8ecb9 Fix auth parsing for proxies
Co-authored-by: adamp01 <@adamp01>
2022-01-04 08:27:23 -07:00
Nate Prewitt
0192aac241 v2.27.0
Some checks failed
Tests / build (macOS-latest, 2.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.10) (push) Has been cancelled
Tests / build (macOS-latest, 3.6) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-18.04, 2.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.10) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.6) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.9) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy-3.7) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy3) (push) Has been cancelled
Tests / build (windows-latest, 2.7) (push) Has been cancelled
Tests / build (windows-latest, 3.10) (push) Has been cancelled
Tests / build (windows-latest, 3.6) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2022-01-03 07:59:10 -07:00
Nate Prewitt
e50dc12b0f Fix doc link 2022-01-02 22:20:40 -07:00
Nate Prewitt
17e6e27a93 General cleanup for 2.27.0 2021-12-29 16:29:09 -06:00
Greg Dubicki
ab38e2c726 Make the data vs json parameters more clear (#5382)
As https://stackoverflow.com/q/26685248/2693875 question
and answer popularity shows that there is a lot of people who
do not understand the distinction.
2021-12-29 10:46:21 -07:00
Nate Prewitt
77d1e9aa3e Merge pull request #5894 from dbaxa/do-not-re-build-proxies-when-proxies-have-been-provided
Prevent unnecessary should_bypass_proxies checks in rebuild_proxies
2021-12-29 10:06:05 -07:00
Ian Stapleton Cordasco
b0829a8690 Merge pull request #6020 from nateprewitt/pypy_37
Update 3.10-dev to 3.10 and add pypy-3.7 in CI
2021-12-29 07:32:11 -06:00
Ian Stapleton Cordasco
28d537dde3 Merge pull request #5917 from nateprewitt/proxy_scheme_unknown_fix
Move from urlparse to parse_url for prepending schemes
2021-12-29 07:31:40 -06:00
Nate Prewitt
86bbee71b2 Update 3.10-dev to 3.10 and add pypy-3.7 2021-12-28 22:28:30 -07:00
Nate Prewitt
0d5347e628 Only compute should_bypass_proxies if needed
Co-authored-by: David Black <dblack@atlassian.com>
2021-12-28 22:10:51 -07:00
Nate Prewitt
ef59aa0227 Move from urlparse to parse_url for prepending schemes 2021-12-28 21:12:00 -07:00
Ian Stapleton Cordasco
d09659997c Merge pull request #5414 from mondeja/5367
Raise InvalidUrl if host starts with '.' character.
2021-12-28 19:39:36 -06:00
Ian Stapleton Cordasco
2b06a952a9 Merge pull request #6017 from nateprewitt/schema2scheme
Fix erroneous use of 'schema' instead of 'scheme'
2021-12-28 19:39:08 -06:00
Ian Stapleton Cordasco
e2064a2c05 Merge pull request #6018 from nateprewitt/basic_auth_update
Update basic auth example
2021-12-28 19:38:35 -06:00
Nate Prewitt
401e17bbdc Update basic auth example 2021-12-28 18:07:01 -07:00
Nate Prewitt
4246792b81 Fix erroneous use of 'schema' instead of 'scheme' 2021-12-28 17:32:48 -07:00
Álvaro Mondéjar
658c10e84a Raise InvalidURL if hosts starts with '.' as was reported at #5367. 2021-12-28 14:24:24 -07:00
Abhinav Vashisth
39d0fdd909 Update README.md (#5998) 2021-12-05 02:52:10 -08:00
Ian Stapleton Cordasco
c193d9742e Merge pull request #5993 from davisagli/tox-parallel
Run tox in parallel using -p instead of detox
2021-11-30 08:07:59 -06:00
David Glick
8e764f355d Run tox in parallel using -p instead of detox 2021-11-29 22:20:47 -05:00
Nate Prewitt
7556ea4213 Merge pull request #5391 from hodbn/fix-5274
Send only one Host header in chunked request
2021-11-29 07:58:31 -08:00
David Hotham
2d2447e210 Catch AttributeError in utils.super_len (#5239)
* Catch AttributeError in utils.super_len

This allows it to handle files obtained via `Tarfile.extractfile()`.
2021-11-28 12:04:49 -08:00
Ian Stapleton Cordasco
e77dd8de6e Merge pull request #5990 from mgorny/trustme-test-dep
Skip the test requiring trustme when it is not available
2021-11-27 19:20:17 -06:00
Michał Górny
55da533a87 Defer the trustme import until inside the fixture
Move the trustme import from global scope into the nosan_server fixture
in order to make it possible to deselect the test via command-line
when trustme is not available.
2021-11-27 18:47:56 +01:00
Nate Prewitt
99b3b49241 Refactor rebuild_proxies to allow proxy resolution (#5924)
without stripping Proxy-Authorization header
2021-11-24 13:21:01 -06:00
sha016
e2fa8d3654 mention all_proxy env variable in Proxies section 2021-11-13 20:58:30 -06:00
Alan Yee
590350f8d0 Update Bug_report.md (#5965)
Add some highlighting and comment out the instructions so that the submitter can see it but it is not displayed in the GitHub issue
2021-10-21 11:06:33 -07:00
Nate Prewitt
9dd6e47b5b Add doc build requirements for RTD (#5956) 2021-10-09 15:03:33 -07:00
Борис Верховский
94f9f7357e Don't mention pip as the reason for supporting py2 (#5940) 2021-09-21 16:22:12 -07:00
Kevin Kirsche
fc106ab586 fix minor typos (#5934) 2021-09-15 06:43:12 -05:00
Ian Stapleton Cordasco
1e5fad7433 Update lock-issues.yml (#5930)
Run this hourly. I'm not seeing any effects, let's see if
running it more frequently will allow it to avoid the GitHub ratelimit

https://github.com/dessant/lock-threads#why-are-only-some-issues-and-pull-requests-processed
2021-09-07 17:00:31 -07:00
Nate Prewitt
248122a697 Add support for 3.10 (#5928) 2021-09-03 19:03:15 -07:00
Nate Prewitt
9572d6a299 General doc updates (#5923) 2021-09-02 08:53:46 -07:00
Nate Prewitt
4ab2550d66 Add test for default chunked Host header 2021-09-02 01:53:34 -07:00
hodbn
6fbfca90b6 Send only one Host header in chunked request
Closes #5274
2021-09-02 00:53:08 -07:00
Ben Li-Sauerwine
aae78010e9 Time out requests' tests after 10 minutes. (#5916) 2021-08-27 11:49:51 -07:00
Nate Prewitt
10968357a1 Appropriately handle urllib3's InvalidHeader exception (#5914) 2021-08-26 20:11:30 -05:00
Nate Prewitt
b351e906b6 Update codeql branch target (#5913) 2021-08-26 05:58:35 -05:00
Nate Prewitt
70a13e2a26 Fix syntax error in lock action (#5912) 2021-08-25 18:04:43 -07:00
Ian Stapleton Cordasco
8ea90a5ce7 Shorten the window before we lock threads
Per Nate's recommendation, let's lock things after 90 days rather than
360
2021-08-25 11:44:57 -07:00
Ian Stapleton Cordasco
7adb8686ac Add thread locker workflow (#5909) 2021-08-25 13:21:35 -05:00
Борис Верховский
827b87b9be Formatting (#5910) 2021-08-25 09:48:30 -07:00
Ben Li-Sauerwine
2d30aeb7c6 Add a test which verifies that ChunkedEncodingError is emitted if an invalid Transfer-Encoding: chunked response is returned. (#5906) 2021-08-24 19:00:17 -07:00
Israel Tsadok
b0e025ade7 Fix broken link to adapters essay (#5899) 2021-08-03 22:58:51 -07:00
Thomas Lam
d8829f9f24 Fix extract_zipped_paths infinite loop when provided invalid unc path (#5851) 2021-08-02 19:40:34 -05:00
Michał Górny
b227e3cb82 Fix creating non-listening sockets in tests on some platforms (#5890)
Fix the listen() invocation for the test server not to pass a backlog
value of zero.  The value of zero means no backlog which effectively
means that the socket can not accept any connections.  This does not
matter for the majority of platforms since the value is only advisory
and the platform tends to go with a bigger backlog anyway.  However,
a few platforms (e.g. alpha or riscv Linux) do take the value literally,
and therefore the tests fail since they are unable to connect to
the server.
2021-07-28 11:23:08 -05:00
Steve Berdy
db575eeedc Fix inconsistent exception type in response.json() method (#5856) 2021-07-26 08:56:44 -07:00
Jeremy Cline
941a77f2b8 docs: Update the Red Hat vulnerabilities contact (#5881) 2021-07-19 09:44:02 -07:00
Egor
a3d54b83f7 Update advanced.rst (#5821)
* Update advanced.rst

* remove confusing euphemism
2021-07-18 05:59:37 -05:00
Steve Berdy
a5b45edf2f Update api.rst (#5877) 2021-07-16 11:06:42 -07:00
Nate Prewitt
a1a6a549a0 v2.26.0
Some checks failed
Tests / build (macOS-latest, 2.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.6) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-18.04, 2.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.6) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.9) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy3) (push) Has been cancelled
Tests / build (windows-latest, 2.7) (push) Has been cancelled
Tests / build (windows-latest, 3.6) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2021-07-13 07:52:02 -07:00
Quentin Pradet
e253eba5ed Stop abusing pytest-httpbin to test commonName support
pytest-httpbin<1.0 ships with a server certificate with a commonName but
no subjectAltName. urllib3 2.0 will stop supporting those in the future,
so we want to upgrade pytest-httpbin.

Unfortunately, `test_https_warnings` was relying on this broken
certificate. With this change, we use `trustme` to create a broken
certificate specifically for this test, so that we can upgrade
pytest-httpbin and make sure that other tests relying on httpbin TLS
support will continue to work with urllib3 2.0.
2021-07-12 09:44:43 -05:00
Nate Prewitt
f6c0619d89 Disable requests[security] and remove 3.5 support references 2021-07-09 12:40:55 -07:00
Naor Livne
33cf965f72 Allow idna 3.x to be installed on Python 3.x
Co-authored-by: Mickaël Schoentgen <contact@tiger-222.fr>
Co-authored-by: Seth Michael Larson <sethmichaellarson@gmail.com>
2021-07-07 08:25:20 -05:00
Дилян Палаузов
5351469472 Add support for brotli decoding (#5783)
* Add support for Brotli decoding

When the brotli or brotlicffi packages are installed,
urllib3.util.make_headers() inserts ',br' in the Accept-Encoding header
and decodes br from the answers.

* Create the default Accept-Encoding header once

* Preserve the previous delimiter behavior

* Update prose in quickstart.rst

Co-authored-by: Seth Michael Larson <sethmichaellarson@gmail.com>
2021-07-07 08:16:28 -05:00
Bernát Gábor
24630743ce Avoid zip extract racing condition by using read+write instead extract (#5707)
Extract also creates the folder hierarchy, however we do not need that,
the file itself being extracted to a temporary folder is good enough.
Instead we read the content of the zip and then write it. The write is
not locked but it's OK to update the same file multiple times given the
update operation will not alter the content of the file. By not creating
the folder hierarchy (default via extract) we no longer can run into the
problem of two parallel extracts both trying to create the folder
hierarchy without exists ok flag, and one must fail.

Resolves #5223.

Signed-off-by: Bernát Gábor <bgabor8@bloomberg.net>
2021-07-06 19:14:51 -05:00
Ash Berlin-Taylor
2ed84f55b2 Switch LGPL'd chardet for MIT licensed charset_normalizer (#5797)
Although using the (non-vendored) chardet library is fine for requests
itself, but using a LGPL dependency the story is a lot less clear
for downstream projects, particularly ones that might like to bundle
requests (and thus chardet) in to a single binary -- think something
similar to what docker-compose is doing. By including an LGPL'd module
it is no longer clear if the resulting artefact must also be LGPL'd.

By changing out this dependency for one under MIT we remove all
license ambiguity.

As an "escape hatch" I have made the code so that it will use chardet
first if it is installed, but we no longer depend upon it directly,
although there is a new extra added, `requests[lgpl]`. This should
minimize the impact to users, and give them an escape hatch if
charset_normalizer turns out to be not as good. (In my non-exhaustive
tests it detects the same encoding as chartdet in every case I threw at
it)

Co-authored-by: Jarek Potiuk <jarek@potiuk.com>

Co-authored-by: Jarek Potiuk <jarek@potiuk.com>
2021-07-06 18:55:02 -05:00
TAHRI Ahmed R
33d448eb21 Pin Flask to <2.0 to fix the test suite
httpbin does not limit Flask version and the 2.0 release has broken compatibility with our test suite
2021-07-06 15:39:50 -05:00
Francois Marier
1466ad713c Fix GitHub links (#5835)
All of these links now redirect to a repo under a different GitHub
user account.
2021-05-31 21:23:54 -07:00
Mark Bell
f6d43b03fb Updated to new be-cordial-or-be-on-your-way URL and CoC now references Python Community CoC (#5811)
* Updated references to new be-cordial-or-be-on-your-way URL.

* CoC now references Python Community Code of Conduct
2021-05-07 11:54:37 -05:00
tallalnparis4ev
05a1a21593 Throw value error when serializing JSON object with NaN value (#5810)
* disallow nan values in json serialize

* test nan value in json post

* added exception for invalid json in request

* use invalid json exception

* invalid json test
2021-05-06 13:18:58 -05:00
Coco Mishra
c45a4dfe6b grammar fix (#5791) 2021-04-11 11:25:49 -05:00
Hans96
2c2138e811 Update setup.py (#5780)
Removed `import re` as unnecessary import
2021-03-19 17:09:29 -05:00
laggardkernel
c267415882 Remove call to set default value for allow_redirects
The call to kwargs.setdefault was redundant and unnecessary as the lower-level session defaults to true.
2021-03-19 11:44:19 -05:00
Ian Stapleton Cordasco
5433656878 Merge pull request #5777 from cclauss/patch-1
quickstart.rst: r.json() can raise JSONDecodeError on Py3
2021-03-18 09:36:34 -05:00
Christian Clauss
f79d1ef42f Also update requests.models.Response 2021-03-18 13:19:28 +01:00
Christian Clauss
4193b95db0 simplejson.JSONDecodeError may be raised on Py2 and Py3 2021-03-18 12:27:02 +01:00
Christian Clauss
06462a6e79 quickstart.rst: r.json() can raise JSONDecodeError on Py3
% `python2 -c "import requests ; requests.get('https://github.com').json()"`
% `python3 -c "import requests ; requests.get('https://github.com').json()"`
2021-03-18 10:06:14 +01:00
Andrew M. White
913880c45a Fix typo 2021-02-24 10:19:48 -07:00
Ian Stapleton Cordasco
bdc00eb097 Merge pull request #5755 from pdmccormick/master
Provide directions for cloning repository despite malformed commits
2021-02-17 15:37:02 -06:00
Peter David McCormick
ef6ceffc1c Provide directions for cloning repository despite malformed commits 2021-02-17 15:38:48 -05:00
Ian Stapleton Cordasco
8c211a96cd Merge pull request #5681 from mateusduboli/5677
5677: Rebuild proxies on Session#send
2021-01-24 16:59:46 -06:00
XiaojueGuan
74b7280049 Fix typo request -> requests 2021-01-22 07:41:39 -06:00
Ian Stapleton Cordasco
083aa67a0d Merge pull request #5723 from bbodenmiller/patch-2
Format c_rehash
2021-01-20 08:58:35 -06:00
Ben Bodenmiller
f6072f1e14 Format c_rehash 2021-01-19 17:27:56 -08:00
Nate Prewitt
c2b307dbef v2.25.1
Some checks failed
Tests / build (macOS-latest, 2.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.5) (push) Has been cancelled
Tests / build (macOS-latest, 3.6) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-18.04, 2.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.5) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.6) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.7) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.8) (push) Has been cancelled
Tests / build (ubuntu-18.04, 3.9) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy3) (push) Has been cancelled
Tests / build (windows-latest, 2.7) (push) Has been cancelled
Tests / build (windows-latest, 3.5) (push) Has been cancelled
Tests / build (windows-latest, 3.6) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2020-12-16 11:34:26 -08:00
Shouro
6de4f104cd Change docs title to requests.sessions 2020-12-14 17:49:49 -06:00
Nate Prewitt
b223291693 Merge pull request #5688 from dan-blanchard/patch-1
Upgrade to chardet 4.x
2020-12-14 09:29:10 -08:00
Dan Blanchard
516f84f490 Upgrade to chardet 4.x 2020-12-11 10:31:38 -05:00
Ernest W. Durbin III
d3e0f73354 Update sponsorship link
PSF relaunched new sponsorship program and the URL has changed.
2020-12-09 08:03:57 -06:00
Mateus Dubiela Oliveira
60ea7f0c2d #5677: Rebuild proxies on Session#send 2020-12-08 18:37:18 +01:00
Ian Stapleton Cordasco
5035827ba4 Merge pull request #5670 from smarie/pr_proxy_conf_helper_and_doc
Proxy related doc updates
2020-12-04 13:38:17 -06:00
Ian Stapleton Cordasco
589c454733 Merge pull request #5673 from jjmaldonis/master
updated `get_encoding_from_headers` to return utf-8 if the content type is set to application/json
2020-11-29 12:19:15 -06:00
jason
5855dd711f updated get_encoding_from_headers to return utf-8 if the content type is set to application/json, following RFC 4627.
fixes #5667
2020-11-29 11:51:41 -06:00
Kaartic Sivaraam
d0359c9460 Fix broken link 2020-11-28 12:21:02 -06:00
Sylvain MARIE
f02a80cbe8 Updated proxies documentation 2020-11-27 17:44:13 +01:00
Sylvain MARIE
d1ca591c0f Revert "New helper method set_http_proxy in Session to set proxies in a more user friendly way"
This reverts commit 4b66260c
2020-11-27 17:05:17 +01:00
Sylvain MARIE
2fddbe3606 Updated proxies documentation 2020-11-27 11:51:47 +01:00
Sylvain MARIE
4b66260cb7 New helper method set_http_proxy in Session to set proxies in a more user friendly way 2020-11-27 11:51:16 +01:00
Nate Prewitt
9ce669e3ae Merge pull request #5663 from hugovk/patch-1
Pin GHA to Ubuntu 18.04
2020-11-18 08:32:02 -08:00
Hugo van Kemenade
0514dea6fc Pin GHA to Ubuntu 18.04
`ubuntu-latest` points to 18.04 and will soon flip to 20.04.

However tests currently fail on 20.04, so let's explicitly pin to 18.04 for now.
2020-11-18 09:00:23 +02:00
Nate Prewitt
962c8986ca Merge pull request #5594 from icfly2/patch-1
Update advanced.rst
2020-11-16 17:31:39 -08:00
Ian Stapleton Cordasco
28cc1d237b Merge pull request #5659 from nateprewitt/contrib_cleanup
Remove reference to development philosophy
2020-11-16 13:19:05 -06:00
Nate Prewitt
78fdf4dd92 Remove reference to development philosophy 2020-11-16 10:44:31 -08:00
Nate Prewitt
03957eb1c2 v2.25.0
Some checks failed
Tests / build (macOS-latest, 2.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.5) (push) Has been cancelled
Tests / build (macOS-latest, 3.6) (push) Has been cancelled
Tests / build (macOS-latest, 3.7) (push) Has been cancelled
Tests / build (macOS-latest, 3.8) (push) Has been cancelled
Tests / build (macOS-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-latest, 2.7) (push) Has been cancelled
Tests / build (ubuntu-latest, 3.5) (push) Has been cancelled
Tests / build (ubuntu-latest, 3.6) (push) Has been cancelled
Tests / build (ubuntu-latest, 3.7) (push) Has been cancelled
Tests / build (ubuntu-latest, 3.8) (push) Has been cancelled
Tests / build (ubuntu-latest, 3.9) (push) Has been cancelled
Tests / build (ubuntu-latest, pypy3) (push) Has been cancelled
Tests / build (windows-latest, 2.7) (push) Has been cancelled
Tests / build (windows-latest, 3.5) (push) Has been cancelled
Tests / build (windows-latest, 3.6) (push) Has been cancelled
Tests / build (windows-latest, 3.7) (push) Has been cancelled
Tests / build (windows-latest, 3.8) (push) Has been cancelled
Tests / build (windows-latest, 3.9) (push) Has been cancelled
2020-11-11 11:55:50 -08:00
Nate Prewitt
320a10d142 Remove Pipfile/Pipfile.lock 2020-11-11 10:29:13 -08:00
Nate Prewitt
9cd2d33489 Move CI to Github Actions 2020-11-11 10:29:13 -08:00
Nate Prewitt
2f70990cd3 Merge pull request #5643 from tarmath/netrc
Respect the NETRC environment variable
2020-11-01 08:52:01 -08:00
Mathieu Pichette
ba543713d3 Respect the NETRC environment variable 2020-10-31 21:01:30 -07:00
Ian Stapleton Cordasco
1431502331 Merge pull request #5614 from smstong/master
small typo corrected.
2020-10-05 13:15:43 -05:00
Jonathan
4840d4a376 small typo corrected.
a small typo was corrected.
2020-10-04 20:45:07 -04:00
Ian Stapleton Cordasco
4f6c018715 Merge pull request #5611 from psf/add-codescanning
Create codeql-analysis.yml
2020-10-02 17:10:53 -05:00
Ian Stapleton Cordasco
d09c0e0f24 Update codeql-analysis.yml
Remove proposed/3.0.0 branch, only ever run against Python sans matrix option
2020-10-02 14:06:24 -05:00
Ian Stapleton Cordasco
941ac53ba0 Create codeql-analysis.yml 2020-10-01 09:19:34 -05:00
Ian Stapleton Cordasco
799a97d360 Merge pull request #5608 from abdullahselek/master
Add official Python 3.8 support on Appveyor
2020-09-30 15:35:12 -05:00
Abdullah Selek
ae6144599a Add official Python 3.8 support on Appveyor 2020-09-30 20:52:35 +01:00
Ae-Mc
333fa8d3f2 Remove reading HISTORY.md in setup.py 2020-09-29 10:36:31 -05:00
Ruben
c3280d7844 Update advanced.rst
replaced reference to requests-async with httpx the replacement project
2020-09-23 13:19:29 +02:00
Martin
967a05bfff Update renamed GitHub handle 2020-09-11 10:36:21 -05:00
Nate Prewitt
1f7c88880b Merge pull request #5570 from ajorg-aws/master
Apply the Apache-2.0 license correctly
2020-08-27 11:09:01 -07:00
Andrew Jorgensen
22b5a39098 Apply the Apache-2.0 license correctly
This follows instructions from the Apache Foundation. It also ensures
that the license will be correctly detected by license scanning tools.

Note that by adding a NOTICE file triggers Section 4.d of the license,
which is usually intended by users of the license.

The text that was in the LICENSE file before this change is intended
(by the authors of the license) to be used as a file header, and not as
a full license notice for a project, but it is commonly used this way,
so I would of course understand if this change is rejected.
2020-08-27 09:44:27 -07:00
Sagar Giri
2a7832b5b0 Update index.rst
Update misleading text about python support
2020-08-25 17:50:13 -07:00
Nate Prewitt
48237afd9d updating doc links and formatting 2020-08-18 15:13:59 -07:00
Seth Michael Larson
0b01355870 Pin more helpful links to sidebar 2020-08-18 15:13:59 -07:00
Seth Michael Larson
43ed689d97 Trim release section, add back Twitter support 2020-08-18 15:13:59 -07:00
Seth Michael Larson
551a0bf0df Recommend Pip, remove todo/philo docs, pare down support avenues 2020-08-18 15:13:59 -07:00
Seth Michael Larson
0830062100 Remove images, analytics, 'keep up to date' 2020-08-18 15:13:59 -07:00
Seth Michael Larson
533c384b87 Make README markdown compatible 2020-08-18 15:13:59 -07:00
Matt Silverlock
02eb5a2cd3 Document the dangers of using verify=False 2020-08-16 21:31:05 -05:00
Ben Bodenmiller
2d39c0db05 Docs: list CURL_CA_BUNDLE as supported (#5509)
* Docs: list CURL_CA_BUNDLE as supported
2020-07-23 21:57:30 -07:00
Nate Prewitt
1b41763472 cleanup advanced docs header 2020-06-26 10:51:20 -08:00
Nate Prewitt
8149e9fe54 Merge pull request #5505 from ollien/prepared-requests-docs-correction
Clarify that PreparedRequests should not be manually created
2020-06-19 09:04:21 -07:00
Nick Krichevsky
9cae7be94f Clarify that PreparedRequests should not be manually created
Closes #5504
2020-06-18 22:06:41 -04:00
Kartik Chugh
1ca1c52e69 Google App Engine (#5475)
* Continuity: Google App Engine
2020-06-17 13:09:34 -07:00
Nate Prewitt
0797c61fd5 v2.24.0 2020-06-17 08:50:25 -07:00
Nate Prewitt
daa2b297a3 updating usage information 2020-06-17 08:50:25 -07:00
Nate Prewitt
7c71982260 Merge pull request #5496 from dbaxa/optimise-prepare-body
Avoid an unnecessary computation of the length of data for non-stream requests (which determine content-length based upon body content).
2020-06-17 08:21:38 -07:00
David Black
71a05cf289 Avoid an unnecessary computation of the length of data for non-stream requests (which determines content-length based upon body content). 2020-06-16 20:53:07 +10:00
Bharat Raghunathan
737dd0c3c6 Update number of dependents on requests (#5495)
* Update dependents on requests
2020-06-15 12:56:07 -07:00
Kevin Kirsche
8ac5929ae1 Fix typo in README (#5468) 2020-06-15 08:23:17 -07:00
Nate Prewitt
2b3436e0e7 Merge pull request #5492 from dbaxa/avoid-calling-resolve_redirects-whe-not-following-redirects
Remove what appears to be an un-needed call to self.resolve_redirects when not following redirects as part of creating a request's history.
2020-06-15 07:44:38 -07:00
David Black
fa2dbe9a91 Remove what appears to be an un-needed call to self.resolve_redirects when not following redirects as part of creating a request's history. 2020-06-15 20:16:47 +10:00
Thomas Grainger
9ed5db8ed2 fix raise_for_status docstring (#5293)
the exception isn't stored it's created new each call
2020-05-08 22:08:51 -07:00
Miro Hrončok
427e8eb1e7 Fix test_conflicting_post_params to work on pytest 5 (#5305)
The non-contextmanager form of pytest.raises was removed in pytest 5.
http://doc.pytest.org/en/latest/deprecations.html#raises-warns-with-a-string-as-the-second-argument

It was used here to support Python < 2.7, but that is no longer needed.
https://github.com/psf/requests/pull/1503#issuecomment-22333666

Fixes https://github.com/psf/requests/issues/5304
2020-05-08 21:58:03 -07:00
Seth Michael Larson
251f73f65d Add changelog entry for pyOpenSSL change 2020-05-01 16:33:51 -07:00
Seth Michael Larson
db47b9b4a0 Don't use pyOpenSSL unless no SNI is detected 2020-05-01 16:33:51 -07:00
Nate Prewitt
bfb93d4b7d update bleach security vulnerability 2020-04-03 14:39:06 -07:00
Nate Prewitt
9ea85109a5 fixing rst markup 2020-04-03 14:31:44 -07:00
Dustin Rodrigues
c577eb8d5f fix README typo 2020-04-03 13:59:17 -07:00
Alessio Izzo
bebf5250b0 Remove explicit unicode literal in README.md and doc (#5336)
* [remove] remove "u" prefix in README and documentation examples
2020-03-25 12:44:51 -07:00
Seth Michael Larson
2758124a13 Also update GitHub's Security Disclosure document (#5370) 2020-02-27 21:33:09 -06:00
Nate Prewitt
4fc7f4a255 Update disclosure contact info (#5369) 2020-02-27 12:05:07 -06:00
Nate Prewitt
65989ddfe9 changing of the guard
Thanks for everything Ian. Welcome Seth!
2020-02-26 20:47:28 -08:00
Nate Prewitt
0a760ff025 updating pipfile.lock for bleach security issue (#5364) 2020-02-26 20:21:47 -08:00
Redowan Delowar
ca6f9af5db Normalize exception docstrings (#5338) 2020-02-23 11:56:46 -06:00
Nate Prewitt
b7c6aba848 v2.23.0 2020-02-19 10:44:27 -08:00
Nate Prewitt
fd13816d01 Revert "Fix for response with UTF-8 BOM #4976"
This reverts commit 19cff44ec1.
This reverts commit 9e27326d68.
This reverts commit f507a3ef12.
2020-02-18 18:56:39 -06:00
Nate Prewitt
24bcb9eab6 Revert "Use urllib for chunked requests"
This reverts commit 2da7fe0858.
2020-02-18 18:56:39 -06:00
Nate Prewitt
b15056d1d3 Revert "#4965 fix: Accessing response.content twice removes forgets read error."
This reverts commit bd10047244.

This reverts commit d91fe00983.
2020-02-18 18:56:39 -06:00
Ned Batchelder
80011a7917 Remove an obsolete attribute from __attrs__
The extra attribute in __attrs__ makes an unpickled session have one more attribute than the original.  Removing it makes the original and the unpickled be identical.
2020-02-18 09:17:21 -08:00
Chris Withers
c46f55bd48 Limit dependencies to major instead of minor (#5342) 2020-02-18 08:58:27 -06:00
Alexander Zhukov
e11302018b Fix the syntax highlighting in the example (#5276)
Co-authored-by: Nate Prewitt <nate.prewitt@gmail.com>
2020-02-17 23:19:38 -08:00
Nate Prewitt
23f6faa7cd Merge pull request #5346 from stock1218/master
Update pipenv links in README and installation guide.
2020-02-17 21:44:33 -08:00
John Samuels
ae0a497b0c Update link to pipenv in installation guide. 2020-02-17 21:47:34 +00:00
John Samuels
b1631b03bc Update link to pipenv in README. 2020-02-17 21:46:26 +00:00
Nate Prewitt
a9906536ee Merge pull request #5326 from nawatts/intersphinx-mapping-config
Fix intersphinx_mapping config for Python standard library
2020-01-31 14:24:52 -10:00
Nick Watts
d5c4cac0f4 Fix intersphinx_mapping config for Python standard library 2020-01-25 18:19:22 -05:00
Nate Prewitt
7b565d886c Merge pull request #5325 from nawatts/install-pip-link
Change link for pip installation instructions
2020-01-25 10:19:34 -08:00
Nick Watts
7138d8b0e3 Change link for pip installation instructions 2020-01-25 12:09:10 -05:00
johnthagen
9b95b4e7b4 Add PyPy3 to Travis test suite (#5193) 2020-01-21 11:00:51 -06:00
Hugo van Kemenade
d2f65af033 Move community files under .github/ (#5206) 2020-01-19 09:41:09 -06:00
Sumana Harihareswara
a9ee0eef5a Add Python 2 support entry in FAQ (#5303)
* Add Python 2 support entry in FAQ

Fixes: #5211

Signed-off-by: Sumana Harihareswara <sh@changeset.nyc>

* Adding Python 3 recommendation

Co-authored-by: Nate Prewitt <nate.prewitt@gmail.com>
2020-01-09 09:55:20 -08:00
John Kooker
782e94d141 Update example code in README.md (#5292)
Show the current project description.
2020-01-09 09:26:42 -08:00
Nate Prewitt
ad18d14573 Merge pull request #5306 from hugovk/update-python-versions-in-faq
Update supported Python versions
2020-01-09 09:06:47 -08:00
Hugo
f462eecf48 Update supported Python versions 2020-01-06 11:24:02 +02:00
Nate Prewitt
eedd674628 Merge pull request #5250 from MasterOdin/patch-1
Fix link to requests-threads in community/recommended doc
2019-11-22 18:50:54 -08:00
Matthew Peveler
4a540ff5f1 Fix link to requests-threads on community/recommended 2019-10-30 16:15:13 -03:00
Sorin Sbarnea
d2590ee46c Change documentation website to requests.readthedocs.io (#5236)
Fixes: #5212
2019-10-24 20:02:55 -07:00
Charles Reid
4cd95aa496 update translation links from http -> https (#5237) 2019-10-24 19:46:04 -07:00
Nate Prewitt
56fd46f9bf Merge pull request #5243 from hugovk/test-3.8-final
Test on Python 3.8 final
2019-10-24 19:32:25 -07:00
Hugo
2ff8106d62 Test on Python 3.8 final 2019-10-22 18:40:03 +03:00
Ernest W. Durbin III
fab1fd10d0 Merge pull request #5216 from Leetcore/patch-1
documentation link fixed
2019-09-30 05:52:29 -04:00
Alex K
74b72ce426 documentation link fixed
websites is down, link to requests.readthedocs.io
2019-09-29 18:10:59 +02:00
Hugo
6e05165a29 Test on Python 3.8 beta 2019-09-26 15:06:29 -07:00
Hugo
0178903841 Xenial is now the default 2019-09-26 15:06:29 -07:00
☿ Kenneth Reitz
0d180a5cbb Merge pull request #5208 from psf/partII
Part II: The Principle of Polarity
2019-09-23 16:08:40 -04:00
☿ Kenneth Reitz
8345819b70 Update README.md 2019-09-23 14:31:19 -04:00
☿ Kenneth Reitz
5f824fb019 Update README.md 2019-09-23 14:30:16 -04:00
☿ Kenneth Reitz
1311c96eae Update README.md 2019-09-23 14:29:35 -04:00
☿ Kenneth Reitz
c4c60864f8 Update README.md 2019-09-23 14:28:52 -04:00
Kenneth Reitz
e8a9bd7415 The Principle of Polarity
Everything is dual; Everything has poles; Everything has its pair of opposites; Like and unlike are the same; Opposites are identical in nature, but different in degree; Extremes meet; All truths, are but half-truths; All paradoxes may be reconciled.
2019-09-23 14:17:08 -04:00
Kenneth Reitz
729fd3cf42 Revert "deepmind"
This reverts commit 14c323492a.
2019-09-23 14:07:17 -04:00
Kenneth Reitz
1d3787a0ea AUTHORS.rst 2019-09-23 14:07:01 -04:00
Nate Prewitt
0357b0724b Merge pull request #5195 from lzutao/patch-1
Fix formatting of status code example
2019-09-19 08:32:13 -07:00
Nate Prewitt
189fea7a11 Merge pull request #5197 from 5uper5hoot/patch-1
Fix misspelling
2019-09-19 08:29:29 -07:00
Nate Prewitt
a5f4f3c9a3 resolve more-itertools py2.7 issues
more-itertools is a transitive testing dependency that no longer supports
python2.7. In order to keep the test suite going, we're pinning under
6.0.0 (the breaking version) until we have better syntax in pipfile.
2019-09-19 08:17:21 -07:00
Nate Prewitt
e08981ee46 updating project url 2019-09-19 07:52:28 -07:00
Nate Prewitt
afb508f6a7 removing duplicate entry 2019-09-19 07:42:23 -07:00
Nate Prewitt
09fd857eb1 Revert "Add trusted domains"
This reverts commit fbe48fbb7c.
2019-09-19 07:42:23 -07:00
☿ Kenneth Reitz
1462917951 Update README.md 2019-09-18 19:24:42 -04:00
Peter Schutt
2962c236c9 Fix misspelling
Just noticed a small typo!
2019-09-18 21:09:22 +10:00
Kenneth Reitz
9d4fd3c968 Update README.md 2019-09-18 05:47:48 -04:00
Kenneth Reitz
12640ec242 Merge branch 'master' of github.com:psf/requests 2019-09-18 05:41:40 -04:00
Kenneth Reitz
5cb55a84a7 squash! 2019-09-18 05:41:33 -04:00
Kenneth Reitz
2cb3abea55 Update README.md 2019-09-18 05:41:05 -04:00
Kenneth Reitz
38d9a4f65f Merge branch 'master' of github.com:psf/requests 2019-09-18 05:40:25 -04:00
Kenneth Reitz
fbc5ed552e psf 2019-09-18 05:40:18 -04:00
Kenneth Reitz
5099688bfc Update README.md 2019-09-18 05:38:32 -04:00
Kenneth Reitz
4cd65385f8 Update README.md 2019-09-18 05:38:12 -04:00
Kenneth Reitz
87f9a58d45 Update README.md 2019-09-18 05:37:47 -04:00
Kenneth Reitz
9369b5a37a kr 2019-09-18 05:37:03 -04:00
Kenneth Reitz
23fe729356 Merge branch 'master' of github.com:psf/requests 2019-09-18 05:33:21 -04:00
Kenneth Reitz
1a7d1406cb cleanups 2019-09-18 05:33:15 -04:00
Kenneth Reitz
92b88fcffb Update README.md 2019-09-18 05:26:27 -04:00
Kenneth Reitz
ac851d8ac3 Merge branch 'master' of github.com:psf/requests 2019-09-18 05:26:03 -04:00
Kenneth Reitz
a025522d08 flourish 2019-09-18 05:25:59 -04:00
Kenneth Reitz
a3735e2517 Update README.md 2019-09-18 05:10:42 -04:00
Kenneth Reitz
06826504da Merge branch 'master' of github.com:psf/requests 2019-09-18 05:10:10 -04:00
Kenneth Reitz
14c323492a deepmind 2019-09-18 05:10:03 -04:00
Kenneth Reitz
c196511934 Update README.md 2019-09-18 05:02:36 -04:00
Kenneth Reitz
a9860c4fae Update README.md 2019-09-18 05:02:07 -04:00
Kenneth Reitz
f82382588f Update README.md 2019-09-18 05:01:17 -04:00
Kenneth Reitz
72176ab9ac Update README.md 2019-09-18 04:59:40 -04:00
Kenneth Reitz
eb2c14889f Update README.md 2019-09-18 04:59:26 -04:00
Kenneth Reitz
cfdd00f3a3 Update README.md 2019-09-18 04:57:16 -04:00
Kenneth Reitz
b15bccf35e Update README.md 2019-09-18 04:56:18 -04:00
Kenneth Reitz
f348d51818 Update README.md 2019-09-18 04:56:04 -04:00
Kenneth Reitz
dc1526f85d Update README.md 2019-09-18 04:55:34 -04:00
Kenneth Reitz
c21c039ec8 Update FUNDING.yml 2019-09-18 04:54:31 -04:00
Kenneth Reitz
49acab8033 Update FUNDING.yml 2019-09-18 04:54:20 -04:00
Kenneth Reitz
0f71067f64 Update README.md 2019-09-18 04:52:39 -04:00
Kenneth Reitz
9f35ebd795 Update README.md 2019-09-18 04:52:22 -04:00
Kenneth Reitz
de1c200dff Update README.md 2019-09-18 04:51:58 -04:00
Kenneth Reitz
458496d43e Update README.md 2019-09-18 04:51:23 -04:00
Kenneth Reitz
446911b853 Update README.md 2019-09-18 04:51:10 -04:00
Kenneth Reitz
3ed0f8fba0 Update README.md 2019-09-18 04:50:39 -04:00
Kenneth Reitz
d66ffdbb2b Update README.md 2019-09-18 04:49:57 -04:00
Kenneth Reitz
99197c2058 Update README.md 2019-09-18 04:49:43 -04:00
Kenneth Reitz
179f943300 Update README.md 2019-09-18 04:48:05 -04:00
Kenneth Reitz
75f062dcef Update README.md 2019-09-18 04:47:36 -04:00
Kenneth Reitz
a7944ba94f Update README.md 2019-09-18 04:46:49 -04:00
Kenneth Reitz
cf77263ad4 Update README.md 2019-09-18 04:45:14 -04:00
Kenneth Reitz
af85e68f1f Update README.md 2019-09-18 04:44:37 -04:00
Kenneth Reitz
536b583bc9 Update README.md 2019-09-18 04:44:26 -04:00
Kenneth Reitz
0f1251bc13 Update README.md 2019-09-18 04:43:41 -04:00
Kenneth Reitz
a29be8f9cc Update LICENSE 2019-09-18 04:42:26 -04:00
Kenneth Reitz
ac9f0d7c97 Update README.md 2019-09-18 04:40:07 -04:00
Kenneth Reitz
be2fe0c6af Update README.md 2019-09-18 04:39:30 -04:00
Kenneth Reitz
abe22b1da6 Update README.md 2019-09-18 04:39:17 -04:00
Kenneth Reitz
e11caeb39f Update README.md 2019-09-18 04:38:51 -04:00
Kenneth Reitz
30a16088c4 Update README.md 2019-09-18 04:37:53 -04:00
Kenneth Reitz
6831d2d8e4 Merge branch 'master' of github.com:psf/requests 2019-09-18 04:35:36 -04:00
Kenneth Reitz
a5bcc9c46e pngsquash 2019-09-18 04:35:29 -04:00
Kenneth Reitz
186dcee8a0 Update README.md 2019-09-18 04:31:58 -04:00
Kenneth Reitz
caf91bd175 Update README.md 2019-09-18 04:29:05 -04:00
Kenneth Reitz
80562c9f83 Update README.md 2019-09-18 04:28:47 -04:00
Kenneth Reitz
2256fd2bc4 Update README.md 2019-09-18 04:28:32 -04:00
Kenneth Reitz
316f748226 Update README.md 2019-09-18 04:28:17 -04:00
Kenneth Reitz
c6ab21c103 Update README.md 2019-09-18 04:27:19 -04:00
Kenneth Reitz
1d41e8dc97 Update README.md 2019-09-18 04:27:06 -04:00
Kenneth Reitz
80c7cbd46e Update README.md 2019-09-18 04:26:52 -04:00
Kenneth Reitz
775813aae7 Update README.md 2019-09-18 04:26:38 -04:00
Kenneth Reitz
cbccc5f07e Update README.md 2019-09-18 04:26:00 -04:00
Kenneth Reitz
26466b54ad Merge branch 'master' of github.com:psf/requests 2019-09-18 04:25:21 -04:00
Kenneth Reitz
042ccfcf99 license 2019-09-18 04:25:17 -04:00
Kenneth Reitz
24e46d0303 Update README.md 2019-09-18 04:21:16 -04:00
Kenneth Reitz
70cc902f5e Update README.md 2019-09-18 04:19:56 -04:00
Kenneth Reitz
091604455a Update README.md 2019-09-18 04:19:37 -04:00
Kenneth Reitz
b639f17705 Update README.md 2019-09-18 04:18:41 -04:00
Kenneth Reitz
33f41b8a13 Update README.md 2019-09-18 04:18:03 -04:00
Kenneth Reitz
73a65941ad Update README.md 2019-09-18 04:17:42 -04:00
Kenneth Reitz
2e992817d4 Update README.md 2019-09-18 04:17:04 -04:00
Kenneth Reitz
0f9bcfb86c Update README.md 2019-09-18 04:14:44 -04:00
Kenneth Reitz
fcde69193a Update README.md 2019-09-18 04:14:21 -04:00
Kenneth Reitz
b08073a7c3 Update README.md 2019-09-18 04:12:57 -04:00
Kenneth Reitz
e1eb569751 Update README.md 2019-09-18 04:12:00 -04:00
Kenneth Reitz
8d09a80a16 Update README.md 2019-09-18 04:11:31 -04:00
Kenneth Reitz
8074cc8bf5 Update README.md 2019-09-18 04:08:42 -04:00
Kenneth Reitz
8e19074296 Update README.md 2019-09-18 04:07:44 -04:00
Kenneth Reitz
30c128ade9 Update README.md 2019-09-18 04:05:51 -04:00
Kenneth Reitz
65a73bd0f7 Update README.md 2019-09-18 04:01:56 -04:00
Kenneth Reitz
e63d846b15 Update README.md 2019-09-18 03:59:35 -04:00
Kenneth Reitz
d6db3901cb Update README.md 2019-09-18 03:57:15 -04:00
Kenneth Reitz
355e288940 Update README.md 2019-09-18 03:56:27 -04:00
Kenneth Reitz
a08c421f7c Update README.md 2019-09-18 03:55:43 -04:00
Kenneth Reitz
e35ace77bf Update README.md 2019-09-18 03:55:23 -04:00
Kenneth Reitz
f3b62442be Update README.md 2019-09-18 03:54:03 -04:00
Kenneth Reitz
846c37c29d Update README.md 2019-09-18 03:53:50 -04:00
Kenneth Reitz
570dc15b52 Update README.md 2019-09-18 03:52:51 -04:00
Kenneth Reitz
4a87d1e62f Update README.md 2019-09-18 03:52:36 -04:00
Kenneth Reitz
2d3b68cf1e Update README.md 2019-09-18 03:51:22 -04:00
Kenneth Reitz
31a6e696bb Update README.md 2019-09-18 03:51:03 -04:00
Kenneth Reitz
33e402b21f Update README.md 2019-09-18 03:48:48 -04:00
Kenneth Reitz
60cffb076b Update README.md 2019-09-18 03:48:25 -04:00
Kenneth Reitz
bdc92c795f Update README.md 2019-09-18 03:41:20 -04:00
Kenneth Reitz
426a1c0120 Update README.md 2019-09-18 03:40:05 -04:00
Kenneth Reitz
bc8fa9c246 Update README.md 2019-09-18 03:39:46 -04:00
Kenneth Reitz
be7cbe1353 Update README.md 2019-09-18 03:38:46 -04:00
Kenneth Reitz
9ba6c5e638 Update README.md 2019-09-18 03:37:59 -04:00
Kenneth Reitz
762042260b Update README.md 2019-09-18 03:37:29 -04:00
Kenneth Reitz
2abe57458d Update README.md 2019-09-18 03:37:21 -04:00
Kenneth Reitz
e40a3d6094 Update README.md 2019-09-18 03:35:33 -04:00
Kenneth Reitz
c2479aeac7 logo 2019-09-18 03:34:08 -04:00
Kenneth Reitz
7ce4691289 Merge branch 'master' of github.com:psf/requests 2019-09-18 03:32:27 -04:00
Kenneth Reitz
c5d9e1216e resize 2019-09-18 03:32:18 -04:00
Kenneth Reitz
863542529d Update README.md 2019-09-18 03:31:48 -04:00
Kenneth Reitz
8072d4fda8 Update README.md 2019-09-18 03:31:23 -04:00
Kenneth Reitz
e820ac7c40 Update README.md 2019-09-18 03:30:45 -04:00
Kenneth Reitz
720f1ce61d Update README.md 2019-09-18 03:29:25 -04:00
Kenneth Reitz
6d37433c0e Merge branch 'master' of github.com:psf/requests 2019-09-18 03:28:44 -04:00
Kenneth Reitz
969783702d flower of life 2019-09-18 03:28:35 -04:00
Kenneth Reitz
6fbbbc8c9e Update README.md 2019-09-18 03:26:17 -04:00
Kenneth Reitz
26b104ecb9 Update README.md 2019-09-18 03:25:58 -04:00
Kenneth Reitz
3f21a2d62e shoes and cars 2019-09-18 03:25:21 -04:00
Kenneth Reitz
42926b5731 Merge branch 'master' of github.com:psf/requests 2019-09-18 03:22:03 -04:00
Kenneth Reitz
a7e2da804c flourish 2019-09-18 03:21:34 -04:00
Kenneth Reitz
2416c2dd47 Update README.md 2019-09-18 03:20:31 -04:00
Kenneth Reitz
b44d6fdf49 Update README.md 2019-09-18 03:20:10 -04:00
Kenneth Reitz
0859c01b16 flourish 2019-09-18 03:19:23 -04:00
Kenneth Reitz
c198cc0b2e Update README.md 2019-09-18 03:17:40 -04:00
Kenneth Reitz
4b9e5d0ef3 Update README.md 2019-09-18 03:17:21 -04:00
Kenneth Reitz
9b51d7c4f2 Update README.md 2019-09-18 03:17:05 -04:00
Kenneth Reitz
6b89c8752a Update README.md 2019-09-18 03:16:49 -04:00
Kenneth Reitz
59dac47346 Update README.md 2019-09-18 03:15:04 -04:00
Kenneth Reitz
bb2ae009bc Update README.md 2019-09-18 03:14:40 -04:00
Kenneth Reitz
11982c1f9f Update README.md 2019-09-18 03:14:26 -04:00
Kenneth Reitz
36cc7bbfc3 Update README.md 2019-09-18 03:12:31 -04:00
Kenneth Reitz
d675d83b1d Update README.md 2019-09-18 03:12:12 -04:00
Kenneth Reitz
4d2875da11 Update README.md 2019-09-18 03:11:56 -04:00
Kenneth Reitz
687ff0eb36 Update README.md 2019-09-18 03:11:34 -04:00
Kenneth Reitz
c51a9efa2b Update README.md 2019-09-18 03:10:41 -04:00
Kenneth Reitz
c386eebcf8 Update README.md 2019-09-18 03:10:21 -04:00
Kenneth Reitz
3423b51748 Update README.md 2019-09-18 03:10:00 -04:00
Kenneth Reitz
3ff2995c1d Update README.md 2019-09-18 03:09:42 -04:00
Kenneth Reitz
e231de6ddc Update README.md 2019-09-18 03:05:16 -04:00
Kenneth Reitz
54cefc901c Update README.md 2019-09-18 03:04:51 -04:00
Kenneth Reitz
2bc6aeb64e Update README.md 2019-09-18 03:03:12 -04:00
Kenneth Reitz
7c71cb9643 Update README.md 2019-09-18 03:02:29 -04:00
Kenneth Reitz
e0359b2725 Update README.md 2019-09-18 02:54:15 -04:00
Kenneth Reitz
25d1ffda8c Update README.md 2019-09-18 02:53:30 -04:00
Kenneth Reitz
537ac3cf22 Update README.md 2019-09-18 02:52:51 -04:00
Kenneth Reitz
5477208835 Update README.md 2019-09-18 02:52:15 -04:00
Kenneth Reitz
0b2517465d Update README.md 2019-09-18 02:51:37 -04:00
Kenneth Reitz
1c19e6148f Update README.md 2019-09-18 02:51:10 -04:00
Kenneth Reitz
55d3d8b3b2 Update README.md 2019-09-18 02:50:59 -04:00
Kenneth Reitz
5f3b95992b Update README.md 2019-09-18 02:49:42 -04:00
Kenneth Reitz
3e012c16c3 Update README.md 2019-09-18 02:49:15 -04:00
Kenneth Reitz
c13ccd11f6 Update README.md 2019-09-18 02:48:45 -04:00
Kenneth Reitz
266d17c4de Update README.md 2019-09-18 02:43:58 -04:00
Kenneth Reitz
6b639bbc08 Update README.md 2019-09-18 02:43:41 -04:00
Kenneth Reitz
6c322457a2 pipfile / lock 2019-09-18 02:42:55 -04:00
Kenneth Reitz
5090ba79ac Create .nojekyll 2019-09-18 02:39:15 -04:00
Kenneth Reitz
da13fec6ce Create SECURITY.md 2019-09-18 02:37:03 -04:00
Kenneth Reitz
d7018e6d61 Create FUNDING.yml 2019-09-18 02:34:01 -04:00
lzutao
39b3dcf7d9 Fix formatting of status code example 2019-09-17 19:34:36 +07:00
Kenneth Reitz
3d968ff34d Update index.rst 2019-08-26 10:35:52 -04:00
Kenneth Reitz
b6b90f4d9b Update sidebarintro.html 2019-08-20 19:02:36 -04:00
Kenneth Reitz
913adced21 Update sidebarlogo.html 2019-08-20 19:02:23 -04:00
Nate Prewitt
e320f9e467 Merge pull request #5171 from MFStapert/patch-2
Fix typo
2019-08-20 10:28:48 -07:00
Marijn Stapert
4070bcf1b9 Fix typo 2019-08-20 19:25:03 +02:00
Kenneth Reitz
3c01cd7080 Update README.md 2019-08-20 01:02:03 -04:00
Kenneth Reitz
bc81ee3af4 Update setup.py 2019-08-20 01:01:06 -04:00
Kenneth Reitz
b1d584e899 Update index.rst 2019-08-20 00:58:49 -04:00
Kenneth Reitz
b98be047f2 Update README.md 2019-08-20 00:58:07 -04:00
Kenneth Reitz
ced3779126 Update README.md 2019-08-20 00:57:58 -04:00
Kenneth Reitz
bedb1cd38f Update README.md 2019-08-20 00:57:46 -04:00
Kenneth Reitz
d258b20eba Delete sponsors.rst 2019-08-20 00:57:00 -04:00
Kenneth Reitz
e2fce5e60c Update index.rst 2019-08-20 00:56:45 -04:00
Kenneth Reitz
72ca1b7e31 Update index.rst 2019-08-20 00:55:57 -04:00
Kenneth Reitz
7f3ce7eaac Update sidebarlogo.html 2019-08-20 00:55:22 -04:00
Kenneth Reitz
b248328eb3 Update sidebarintro.html 2019-08-20 00:54:28 -04:00
Kenneth Reitz
10e5f874c7 Update sidebarintro.html 2019-08-20 00:54:00 -04:00
Kenneth Reitz
7f2513fb81 Update index.rst 2019-08-20 00:50:22 -04:00
Kenneth Reitz
04b5c83701 Update index.rst 2019-08-20 00:50:07 -04:00
Kenneth Reitz
1f9ec06e22 Update index.rst 2019-08-20 00:49:18 -04:00
Kenneth Reitz
00fa902c7d Update README.md 2019-08-20 00:47:05 -04:00
Kenneth Reitz
3393232304 Update README.md 2019-08-20 00:46:57 -04:00
Kenneth Reitz
d41fba6347 Update README.md 2019-08-20 00:46:47 -04:00
Kenneth Reitz
7ca0e86a67 Update README.md 2019-08-20 00:45:53 -04:00
Kenneth Reitz
428f7a2759 Merge pull request #5076 from myrheimb/patch-1
Possible fix for #4945?
2019-08-20 00:38:21 -04:00
Kenneth Reitz
a71e2240df Merge pull request #4976 from eduardomourar/feature/strip-utf8-bom
Fix for response with UTF-8 BOM
2019-08-20 00:26:59 -04:00
Kenneth Reitz
4bce5a0bc5 Merge branch 'master' into feature/strip-utf8-bom 2019-08-20 00:26:51 -04:00
Kenneth Reitz
3e7d0a873f Merge pull request #4987 from aless10/master
[fix] fix failing doctests in requests/*
2019-08-20 00:25:50 -04:00
Kenneth Reitz
df918c066f Merge branch 'master' into master 2019-08-20 00:25:37 -04:00
Kenneth Reitz
ada50499a0 Merge pull request #4996 from sblondon/master
Add link to user-agent documentation
2019-08-20 00:24:08 -04:00
Kenneth Reitz
82c744b59c Merge pull request #4983 from jaketreacher/2949-trusted-domain
Add trusted domains
2019-08-20 00:23:52 -04:00
Kenneth Reitz
bbc3d43522 Merge pull request #4922 from jdufresne/ordered
Remove unnecessary compat shim for OrderedDict
2019-08-20 00:22:32 -04:00
Kenneth Reitz
8086ffdbbf Merge pull request #4999 from greysteil/add-project-urls
Add project URLs with links to source code and docs
2019-08-20 00:21:31 -04:00
Kenneth Reitz
5eb7337494 Merge pull request #4978 from sayzlim/master
Fix double image request
2019-08-20 00:21:12 -04:00
Kenneth Reitz
48e1a3359e Merge branch 'master' into master 2019-08-20 00:21:04 -04:00
Kenneth Reitz
1b450d2038 Merge pull request #5018 from hugovk/rm-2.6
Remove duplicate config
2019-08-20 00:17:54 -04:00
Kenneth Reitz
67a7b2e833 Merge pull request #5087 from LuckyDenis/master
#4965 Fix
2019-08-20 00:16:35 -04:00
Kenneth Reitz
42c5a4f622 Merge pull request #5128 from lmvlmv/urllibfix
Use urllib for chunked requests
2019-08-20 00:15:44 -04:00
Kenneth Reitz
11ed88bcb2 Merge pull request #5105 from alanyee/patch-1
Update sessions.py
2019-08-20 00:14:36 -04:00
Kenneth Reitz
0fe6653eab Merge pull request #5049 from hroncok/pytest4
Support pytest 4
2019-08-20 00:12:58 -04:00
Kenneth Reitz
dd15e52840 Merge pull request #5119 from alanyee/patch-1
Update sessions.py
2019-08-20 00:11:22 -04:00
Kenneth Reitz
9bc49b5960 Merge branch 'master' into patch-1 2019-08-20 00:11:02 -04:00
Nate Prewitt
d79024f246 Merge pull request #5160 from OrangutanGaming/change-github
Updated references to previous requests/requests GitHub path
2019-08-19 15:57:15 -07:00
Nihaal
9cdf294107 Updated references to previous requests/requests GitHub path 2019-08-19 21:33:18 +01:00
Nate Prewitt
9f55e4bc09 Merge pull request #5164 from dschaller/patch-1
fix codecov logo in readme
2019-08-19 10:55:40 -07:00
Nate Prewitt
bf582192b8 Merge pull request #5167 from aadibajpai/patch-1
[IMPROVEMENT] Update monthly download count
2019-08-19 10:54:31 -07:00
Aadi Bajpai
408e576d33 Update README.md with download count
https://pepy.tech/project/requests
2019-08-19 22:13:41 +05:30
Derek
7d57e8ec55 fix codecov logo in readme 2019-08-15 18:47:10 -07:00
Denis Belavin
e8ff4897fe Merge branch 'master' into master 2019-08-14 21:12:19 +03:00
Dull Bananas
a4c18cd733 Add missing backtick (#5145) 2019-07-29 09:06:11 -07:00
sblondon
07005b0ffc Merge branch 'master' into master 2019-07-25 18:07:21 +02:00
lmvlmv
989f702742 Merge branch 'master' into urllibfix 2019-07-25 10:49:24 +01:00
Alessio Izzo
a0d58026e0 Merge branch 'master' into master 2019-07-24 12:42:40 +02:00
Denis Belavin
3922dcf2a1 Merge branch 'master' into master 2019-07-23 21:36:37 +03:00
Kenneth Reitz
589a822567 Merge pull request #5141 from minho42/Fix-typos
Fix typos
2019-07-23 12:53:21 -04:00
lmvlmv
e8c9acc8a2 Merge branch 'master' into urllibfix 2019-07-23 09:31:00 +01:00
Kenneth Reitz
9a2e5df000 Merge pull request #5142 from dullbananas/master
Improve docs
2019-07-20 23:57:00 -04:00
Dull Bananas
c79d61b953 List valid methods for request() 2019-07-20 15:32:04 -07:00
Dull Bananas
f9ac75cab1 Fix GitHub profile link 2019-07-20 09:31:39 -07:00
Dull Bananas
ebd3e36ad5 Add 'Dull Bananas' to AUTHORS 2019-07-20 09:29:50 -07:00
Dull Bananas
50daf9c005 Add .eggs dir to .gitignore 2019-07-20 09:23:52 -07:00
Dull Bananas
fb7efcf3f1 Add example of good code below example of bad code 2019-07-20 09:17:54 -07:00
Min ho Kim
5f576ad22f Fix typos 2019-07-20 01:46:08 +10:00
kobayashi
0b6c110a5c Merge pull request #5127 from Unit03/head-allow-redirects-docstring
Document that `request.head` defaults `allow_redirects` to `False`
2019-07-11 20:18:42 -04:00
Leon Verrall
2da7fe0858 Use urllib for chunked requests 2019-07-02 10:17:33 +01:00
Jacek Kołodziej
c8d8b4b513 Document that request.head defaults allow_redirects to False
Related: kennethreitz/requests#4274
2019-07-01 21:41:38 +02:00
Alan Yee
45c2e679e0 Update sessions.py
Use `.format()` over `%` given PEP 3101
2019-06-24 10:12:38 -07:00
aless10
27b24f974f Merge branch 'master' of https://github.com/kennethreitz/requests 2019-06-13 22:48:08 +02:00
Denis Belavin
6296df90b9 Merge branch 'master' into master 2019-06-13 10:18:55 +03:00
Nate Prewitt
4983a9bde3 Merge pull request #5108 from atombrella/python34
Removed py34 from tox.ini.
2019-06-03 07:01:03 -07:00
Mads Jensen
2e4329d153 Removed py34 from tox.ini. 2019-06-03 08:45:48 +02:00
Alan Yee
47cb8bae1a Update sessions.py
-Made removing a key-value pair more modular
-Remove unneeeded return statement
2019-05-29 11:49:44 -07:00
aless10
d889b98eae Merge branch 'master' of https://github.com/kennethreitz/requests 2019-05-24 20:40:22 +02:00
Miro Hrončok
dc75b3ca0b Support pytest 4
Fixes https://github.com/kennethreitz/requests/issues/5048

See https://docs.pytest.org/en/latest/deprecations.html#marks-in-pytest-mark-parametrize
2019-05-24 00:02:43 +02:00
Denis Belavin
0becdca7e3 Merge branch 'master' into master 2019-05-20 21:00:14 +03:00
Buğra İşgüzar
6f81e78dfe Merge pull request #5099 from petar-iv/password-no-print
Print the type of the password instead of the password itself
2019-05-20 18:35:41 +03:00
Denis Belavin
9c3c755abe Merge branch 'master' into master 2019-05-20 10:12:35 +03:00
petar-iv
d88240ba44 Print the type of the password instead of the password itself 2019-05-20 09:57:11 +03:00
aless10
6d2a5072ca [add] add NORMALIZE_WHITESPACE and ELLIPSIS to pytest.ini and remove them from requests/__init__.py 2019-05-19 16:25:52 +02:00
aless10
96ff7ca31f Merge branch 'master' of https://github.com/aless10/requests 2019-05-19 16:21:40 +02:00
aless10
2e633471f1 Merge branch 'master' of https://github.com/kennethreitz/requests 2019-05-19 16:20:40 +02:00
aless10
67a0e90b6b [change] change doctest based on LuckyDenis suggestion 2019-05-19 16:20:11 +02:00
Alessio Izzo
4a59cd0950 Merge branch 'master' into master 2019-05-19 16:08:55 +02:00
Hugo
be295ba4d4 Simplify config 2019-05-16 18:36:45 +03:00
Hugo
d36f391957 Merge branch 'master' into rm-2.6 2019-05-16 18:31:37 +03:00
Frost Ming
a79a63390b Merge pull request #5088 from zurbrugc/master
Linked a GitHub tutorial regarding pull requests in README
2019-05-16 13:20:45 +08:00
Frost Ming
86760daf23 Merge branch 'master' into master 2019-05-16 13:14:08 +08:00
Frost Ming
8e26bfd86d Merge pull request #5092 from kennethreitz/urllib1.25
v2.22.0
2019-05-16 13:12:48 +08:00
Nate Prewitt
aeda65bbe5 v2.22.0 2019-05-15 12:51:39 -07:00
Nate Prewitt
68e581f1b5 drop 3.4 support 2019-05-15 12:51:31 -07:00
Nate Prewitt
a91905d78e adjust pytest pins to fix testing infra 2019-05-15 12:51:23 -07:00
zurbrugc
44256ffe7c Linked how to make a pull requests in README
This makes it easier for users new to GitHub to learn how to make a pull request.
2019-05-14 11:25:16 -07:00
zurbrugc
4803716715 Merge pull request #1 from kennethreitz/master
Updating my fork with the original
2019-05-14 11:21:30 -07:00
Белавин Денис
bd10047244 #4965 fix: Accessing response.content twice removes forgets read error. 2019-05-14 12:11:56 +03:00
Белавин Денис
d91fe00983 #4965 fix-draw: Accessing response.content twice removes forgets read error. 2019-05-13 17:18:42 +03:00
Kenneth Reitz
b18f765774 Merge pull request #5054 from imikay/patch-1
Add import statement to README example
2019-05-09 17:38:19 -04:00
Kenneth Reitz
b5b8c038a7 Merge pull request #5082 from zurbrugc/master
Linked contribution information in README
2019-05-09 17:37:32 -04:00
zurbrugc
a694ab5c00 Linked contribution information in README
For potential contributors who are new to GitHub and prefer to learn via structured processes, linking the Contributor's Guide and development philosophy documents in the README will make it easier for them to find this information. This will increase the quality of their contributions and make them more comfortable contributing to the project.
2019-05-09 11:33:01 -07:00
Kenneth Reitz
e52932c427 Update index.rst 2019-05-06 07:48:07 -04:00
Kenneth Reitz
1f9425ca53 Update README.md 2019-05-06 07:41:34 -04:00
Buğra İşgüzar
b4f76878fe Merge branch 'master' into patch-1 2019-05-02 00:30:04 +03:00
Bjørnar Myrheim
a310b5ab34 Possible fix for #4945?
Could the missing colon on line 612 be the reason for the missing reference in the docs as described in issue #4945?
2019-04-30 18:37:11 +02:00
Kenneth Reitz
e73a6c52d2 Merge pull request #5034 from tomchristie/patch-1
Add `requests-async` link to "non-blocking" docs.
2019-04-27 09:13:43 -04:00
Kenneth Reitz
e3c3c0a8fe Merge pull request #5062 from alexwlchan/patch-1
docs: Correct the spelling of "maintenance"
2019-04-27 09:12:09 -04:00
Alex Chan
faafb5a043 docs: Correct the spelling of "maintenance" 2019-04-25 08:19:20 +01:00
Alessio Izzo
663aa1162b Merge branch 'master' into master 2019-04-23 19:18:02 +02:00
Kenneth Reitz
d22d219d34 Merge pull request #5066 from s-pace/doc/update
[doc website] Add a nice search experience
2019-04-23 08:23:57 -04:00
s-pace
74289f420c feat: add search to the main introduction page 2019-04-23 07:47:33 +02:00
s-pace
749419ad0c feat: add search to every documentation pages 2019-04-23 07:47:08 +02:00
Kenneth Reitz
7f438416e4 less is more 2019-04-20 08:22:04 -04:00
Kenneth Reitz
5d06354734 fix 2019-04-20 08:21:21 -04:00
Kenneth Reitz
2d120e32db fix 2019-04-20 08:19:49 -04:00
Kenneth Reitz
69856f3052 requests 3.0 intentions 2019-04-20 08:09:43 -04:00
Ian Gao
37011aaa3f Add import statement
Should add this import statement to make it more user friendly, especially for the beginners in Python.
2019-04-11 19:03:15 +08:00
Alessio Izzo
8b773a4fed [remove] remove invalid field in docete
Remove 'Connection': 'close' field in 'headers'
2019-04-07 13:36:34 +02:00
Alessio Izzo
c19c394ac1 Merge branch 'master' into master 2019-04-07 13:24:09 +02:00
Kenneth Reitz
9742da7f91 Update sidebarlogo.html 2019-03-28 23:52:07 -04:00
Kenneth Reitz
76a89c3c9b Update sidebarintro.html 2019-03-28 23:51:53 -04:00
Tom Christie
6f6d0164a9 Add requests-async link to "non-blocking" docs.
Links to https://github.com/encode/requests-async for an asyncio non-blocking option.
2019-03-27 10:09:19 +00:00
Alessio Izzo
aa21dbe7fc Merge branch 'master' into master 2019-03-26 16:24:43 +01:00
Hugo
a7969c5c42 Remove old Python 2.6 check and duplicate config 2019-03-10 17:08:09 +02:00
Kenneth Reitz
a345b776fb update copyright year 2019-02-28 12:03:44 -05:00
Kenneth Reitz
63e7748fe5 programming quiz 2019-02-28 11:47:41 -05:00
Kenneth Reitz
f2409648ac programming quiz 2019-02-28 11:46:27 -05:00
Grey Baker
7d7d9ebacf Add project URLs with links to source code and docs 2019-02-23 13:24:52 +00:00
sblondon
248211453d Add link to user-agent documentation
So the user has a pointer to the documentation about the searched topic.
2019-02-22 11:04:07 +01:00
aless10
fd926e74c3 [change] change description in __init__ module. Now it is the same as master 2019-02-17 19:45:32 +01:00
aless10
177f4dd2a4 [fix] fix failing doctests in requests/*
[add] add --doctest-modules in pytest.ini file as addopts
[add] add myself to AUTHORS
2019-02-17 19:06:01 +01:00
Jake Treacher
fbe48fbb7c Add trusted domains 2019-02-15 10:40:24 +08:00
Sayz Lim
5add08fc84 Fix double image request
Use official framework for the "custom" ad design integration.
2019-02-12 20:24:58 +07:00
Eduardo Rodrigues
19cff44ec1 fix response with utf8 bom 2019-02-09 22:14:22 +01:00
Eduardo Rodrigues
9e27326d68 add failing tests for bom 2019-02-09 22:00:32 +01:00
Eduardo Rodrigues
f507a3ef12 add utf8 with bom to test 2019-02-09 11:56:06 +01:00
Ian Stapleton Cordasco
c9309e4c59 Merge pull request #4960 from andrewbonney/master
docs: correct error in 'merge_environment_settings' usage

Closes #4959
2019-02-04 09:22:40 -06:00
Andrew Bonney
827bbe2a7e docs: correct error in 'merge_environment_settings' usage
Resolves #4959
2019-02-04 13:28:12 +00:00
Ian Stapleton Cordasco
64bde6582d Merge pull request #4940 from sloria/patch-2
Remove sudo: from .travis.yml
2019-01-21 12:50:27 -06:00
Ian Stapleton Cordasco
334be4d272 Merge branch 'master' into patch-2 2019-01-21 07:59:29 -06:00
Ian Stapleton Cordasco
67a9ed47ae Merge pull request #4915 from sethmlarson/patch-1
Normalize percent-encoded bytes before comparison
2019-01-21 07:58:32 -06:00
Seth Michael Larson
28208392cd revert lock change 2019-01-19 10:57:12 -06:00
Seth Michael Larson
5734f4fc4a Force pipenv to use the lockfile 2019-01-19 10:51:12 -06:00
Seth Michael Larson
4c320ac3a2 Lock pytest to <4.1 2019-01-19 10:34:58 -06:00
Steven Loria
b49547f135 Remove sudo: from .travis.yml
TravisCI has migrated their infrastructure: https://blog.travis-ci.com/2018-11-19-required-linux-infrastructure-migration
2019-01-16 20:59:14 -05:00
Seth M. Larson
f1e48f4d0d Merge branch 'master' into patch-1 2019-01-16 18:47:10 +00:00
Nate Prewitt
f37daf2500 Merge pull request #4936 from ofek/patch-2
Fix typo
2019-01-12 15:54:21 -08:00
Ofek Lev
6dd410ff17 Fix typo 2019-01-12 18:33:00 -05:00
Jon Dufresne
2aab9a9a39 Remove internal use of unnecessary compat shim for OrderedDict
The shim is the same on both Python 2 & 3. It is always
collections.OrderedDict. Avoid the indirection and import from Python
stdlib instead.

Keep requests.compat.OrderedDict for backwards compatibility. Some
packages import this.
2018-12-29 12:05:33 -05:00
Seth M. Larson
ad9400ecfe Normalize percent-encoded bytes before comparison 2018-12-23 15:50:16 -06:00
Nate Prewitt
5c1f72e80a Merge pull request #4910 from moy/master
get(), request(): fix documentation of 'params'
2018-12-13 13:34:10 -08:00
Matthieu Moy
c4d76800e8 get(), request(): fix documentation of 'params'
'params' is sent to the query string, not the body.
2018-12-13 15:57:00 +01:00
Nate Prewitt
c452e3b92d Merge pull request #4901 from requests/v2.21.0
v2.21.0
2018-12-10 07:36:33 -08:00
Nate Prewitt
5a1e738ea9 v2.21.0 2018-12-09 22:13:32 -08:00
Alex Gaynor
8761e9736f Bumped maximum version of idna 2018-12-09 21:41:14 -08:00
Nate Prewitt
abe950cfd3 Revert "Set up Azure Pipelines for Linux and Windows"
This reverts commit e4974c7ff5.
2018-12-09 20:45:06 -08:00
Nate Prewitt
c35f34263a Merge pull request #4898 from requests/revert_azure
revert azure pipeline changes
2018-12-09 20:31:09 -08:00
Nate Prewitt
0dd4752598 revert azure pipeline changes
Reverting commits:
fc9dfac
bc3eddc
d911f27
3da2f10
ce52825
398d110
c15d2b6
086655e
2018-12-09 20:19:10 -08:00
Kenneth Reitz
57d7284c1a Merge pull request #4874 from kaylangan/patch-1
Add build badge for Azure Pipelines
2018-11-14 10:33:06 -05:00
Kayla Ngan
fc9dfac2b9 Add build badge for Azure Pipelines
Not sure if you want to add a build badge since you didn't have one before. But if you do, here's yours for Azure Pipelines.
2018-11-14 10:27:16 -05:00
Kenneth Reitz
bc3eddc6ed Delete settings.json 2018-11-13 07:53:16 -05:00
Kenneth Reitz
d911f27868 Delete install.ps1 2018-11-13 07:52:59 -05:00
Kenneth Reitz
3da2f10290 Delete .travis.yml 2018-11-13 07:52:48 -05:00
Kenneth Reitz
5e0ebc9b9f Merge pull request #4867 from jdufresne/extra
Simplify tox.ini
2018-11-13 07:52:06 -05:00
Kenneth Reitz
75e2dd3094 Merge pull request #4868 from jdufresne/tox-py37
Add Python 3.7 to tox test matrix
2018-11-13 07:51:36 -05:00
Kenneth Reitz
9533df1f0b Merge pull request #4870 from requests/kennethreitz-patch-1
Delete appveyor.yml
2018-11-13 07:51:25 -05:00
Kenneth Reitz
ce52825d12 fix coverage 2018-11-13 07:48:59 -05:00
Kenneth Reitz
398d1105b4 fix coverage 2018-11-13 07:48:48 -05:00
Kenneth Reitz
c15d2b6949 Delete appveyor.yml 2018-11-13 07:27:42 -05:00
Kenneth Reitz
7d4fc04a6f Merge pull request #4869 from kaylangan/master
Set up CI with Azure Pipelines
2018-11-13 07:11:50 -05:00
Kayla Ngan
086655e4fc Unify Linux and Windows 2018-11-12 13:37:50 -05:00
Jon Dufresne
779fd6e7f3 Add Python 3.7 to tox test matrix 2018-11-11 12:01:41 -08:00
Jon Dufresne
af63554106 Simplify tox.ini
Tox installs the package to the virtualenv by default. PySocks is
already included in test_requirements. Don't need to install these
explicitly.
2018-11-11 11:54:25 -08:00
Nate Prewitt
bedd9284c9 Merge pull request #4861 from altendky/patch-1
Set iter_lines() decode_unicode default to False
2018-11-09 12:44:34 -08:00
Kayla Ngan
e4974c7ff5 Set up Azure Pipelines for Linux and Windows 2018-11-09 15:20:08 -05:00
Kyle Altendorf
36412c5ae7 Merge branch 'master' into patch-1 2018-11-09 14:09:08 -05:00
Nate Prewitt
6cfbe1aedd v2.20.1 2018-11-08 09:14:10 -08:00
Kyle Altendorf
a7aa86a933 Set iter_lines() decode_unicode default to False
The docs just read a bit strange with `decode_unicode=None` as opposed to `False`.
2018-11-06 12:35:39 -05:00
Nate Prewitt
c501ec986d Merge pull request #4853 from mainanick/master
Incorrect ValueError Message on ~requests.utils.from_key_val_list comments
2018-10-29 23:13:56 -07:00
Maina Nick
045b706b37 Merge pull request #2 from requests/master
Syncing fork to the original repository
2018-10-29 22:55:03 +03:00
unknown
ccbffe5a53 Incorrect ValueError Message 2018-10-29 22:53:02 +03:00
Ian Stapleton Cordasco
eaab47f033 Merge pull request #4851 from requests/default_port_handling
proper handling for default ports in auth stripping
2018-10-29 07:48:36 -05:00
Nate Prewitt
ea9436a5d6 proper handling for default ports in auth stripping 2018-10-28 23:29:04 -07:00
Maina Nick
3a831be413 Merge pull request #1 from requests/master
Syncing fork to the original repository
2018-10-28 14:20:07 +03:00
Nate Prewitt
7c812e919b Merge pull request #4839 from rabdill/patch-1
Reverting redirect examples back to intended URLs
2018-10-20 16:36:09 -07:00
Rich Abdill
5fdc25b029 Reverting redirect examples back to intended URLs
A find/replace from a few weeks ago made the redirection sample not demonstrate redirection anymore
2018-10-20 16:55:48 -05:00
Nate Prewitt
d2962f1d55 update maintainer contact info 2018-10-18 09:03:51 -07:00
Nate Prewitt
edf7731e66 update vulnerability information 2018-10-18 09:00:12 -07:00
Nate Prewitt
a1f4e62aa4 fix broken HISTORY.md reference 2018-10-18 08:58:48 -07:00
Nate Prewitt
75bdc998e2 Merge pull request #4835 from requests/2.20.0
v2.20.0
2018-10-18 08:44:49 -07:00
Nate Prewitt
bd840450c0 v2.20.0 2018-10-17 22:32:22 -07:00
Nate Prewitt
7fd9267b3b remove final remnants from 2.6 2018-10-17 00:18:51 -07:00
Hugo Osvaldo Barrera
6ae8a21892 Add myself to AUTHORS
(Or rather, just update my email)
2018-10-16 20:34:56 -07:00
Hugo Osvaldo Barrera
89ab030cdb Use comprehensions whenever possible 2018-10-16 20:34:22 -07:00
Nate Prewitt
2c6a8426ae Merge pull request #4827 from webmaven/patch-1
CVE URLs update: www sub-subdomain no longer valid
2018-10-16 09:33:08 -07:00
Michael R. Bernstein
30be889651 CVE URLs update: www sub-subdomain no longer valid 2018-10-16 10:10:30 -06:00
Nate Prewitt
a6cd380c64 Merge pull request #4765 from requests/encapsulate_urllib3_exc
wrap url parsing exceptions from urllib3's PoolManager
2018-09-30 20:23:57 -06:00
Nate Prewitt
bbdbcc8f05 wrap url parsing exceptions from urllib3's PoolManager 2018-09-30 18:36:05 -06:00
Nate Prewitt
ff0c325014 Merge pull request #4805 from jdufresne/https
Prefer https:// for URLs throughout project
2018-09-30 18:27:23 -06:00
Jon Dufresne
b0ad2499c8 Prefer https:// for URLs throughout project 2018-09-30 17:14:40 -05:00
Jon Dufresne
8f20b7dc8f Remove dead link to unixstickers.com
The link does not link Requests stickers as the text suggests.
2018-09-30 14:03:59 -06:00
Nate Prewitt
207e83f6b6 Merge pull request #4802 from schafezp/patch-1
Update README.md to fix typo
2018-09-21 09:27:12 -07:00
Zachary Schafer
b3c8bb7bef Update README.md to fix typo
I noticed "Rquests" was used at the top of the readme instead of "Requests". If that was intentional then ignore this change.
2018-09-21 12:22:53 -04:00
Kenneth Reitz
d26f6314ab Update index.rst 2018-09-17 06:42:52 -04:00
Kenneth Reitz
dcf5617a5e Update index.rst 2018-09-17 06:42:21 -04:00
Kenneth Reitz
76cf1fa214 Update index.rst 2018-09-17 06:41:41 -04:00
Kenneth Reitz
05dd0b88a1 Update index.rst 2018-09-17 06:40:47 -04:00
Kenneth Reitz
3f024ff774 Update index.rst 2018-09-17 06:40:26 -04:00
Kenneth Reitz
cb1bd313e1 Update MANIFEST.in 2018-09-17 06:07:08 -04:00
Kenneth Reitz
efc4ea6ed7 Delete HISTORY.rst 2018-09-17 06:06:47 -04:00
Kenneth Reitz
5251882a03 history 2018-09-17 06:06:08 -04:00
Kenneth Reitz
02a5d7ba68 Update MANIFEST.in 2018-09-17 06:05:18 -04:00
Kenneth Reitz
eea96f94d9 Update setup.py 2018-09-17 06:05:03 -04:00
Kenneth Reitz
9866277c03 Delete README.rst 2018-09-17 06:03:42 -04:00
Kenneth Reitz
7675468068 Update README.md 2018-09-17 06:03:22 -04:00
Kenneth Reitz
fdcb717cf7 Merge branch 'master' of github.com:requests/requests 2018-09-17 06:00:56 -04:00
Kenneth Reitz
4e7e2707e3 readme 2018-09-17 05:59:57 -04:00
Kenneth Reitz
86914e2dda Update README.rst 2018-09-17 05:56:15 -04:00
Nate Prewitt
52473da631 Merge pull request #4791 from juozasget/patch-1
Tuple test_requirements was too long, PEP8
2018-09-15 21:44:26 +08:00
juozasget
b9dfc95cf2 Tuple test_requirements was too long, PEP8
Broken a long line into multiple lines inside tuple parenthesis.
2018-09-15 13:26:59 +03:00
Nate Prewitt
c292cabd1f Merge pull request #4787 from vinayak-mehta/patch-1
Fix broken essay link
2018-09-15 08:08:44 +08:00
Vinayak Mehta
5ef429efe3 Fix broken essay link 2018-09-15 03:43:30 +05:30
Nate Prewitt
c45d7c49ea Merge pull request #4718 from bmerry/fix-4716
Strip Authorization header whenever root URL changes
2018-09-14 20:08:04 +08:00
Bruce Merry
857e9b7ac2 Rework authorization stripping logic as discussed
The exception for http->https upgrade now requires the standard HTTP(S)
ports to be used, either implicitly (no port specified) or explicitly.
2018-09-14 10:44:43 +02:00
Bruce Merry
3331e2aecd Strip Authorization header whenever root URL changes
Previously the header was stripped only if the hostname changed, but in
an https -> http redirect that can leak the credentials on the wire
(#4716). Based on with RFC 7235 section 2.2, the header is now stripped
if the "canonical root URL" (scheme+authority) has changed, by checking
scheme, hostname and port.
2018-09-14 10:44:43 +02:00
Nate Prewitt
dd754d13de Merge pull request #4785 from alexwlchan/encounterd-of-the-third-kind
Fix a typo in a test docstring
2018-09-12 22:57:31 -07:00
Alex Chan
d1fab0b60c Fix a typo in a test docstring 2018-09-13 06:26:59 +01:00
Kenneth Reitz
8472dbd134 Merge pull request #4782 from sayzlim/master
Fix CSS error
2018-09-10 16:02:00 -04:00
Sayz Lim
0fc171091d Fix CSS error
Human error, I shouldn’t have moved the CTA.
2018-09-11 02:59:03 +07:00
Kenneth Reitz
15029e3b16 Merge pull request #4781 from sayzlim/master
Adjust padding and button placements
2018-09-10 15:35:07 -04:00
Sayz Lim
f18f12bcbc Merge branch 'master' of https://github.com/sayzlim/requests 2018-09-11 00:11:44 +07:00
Sayz Lim
ddbeb3025b Adjust padding and button placements
Move the CTA button so the version doesn’t overlap with it. Make the expanded ad more compact to take less vertical space.
2018-09-11 00:11:38 +07:00
Kenneth Reitz
0755c4cf1b Merge branch 'master' of github.com:requests/requests 2018-09-10 11:07:28 -04:00
Kenneth Reitz
e7cce354c1 ad by 2018-09-10 11:07:20 -04:00
Kenneth Reitz
6e8c27e5a8 Merge pull request #4780 from sayzlim/master
Correct fixed footer width
2018-09-10 11:06:14 -04:00
Kenneth Reitz
16f0280c31 Merge branch 'master' into master 2018-09-10 11:06:03 -04:00
Kenneth Reitz
79e28b7f03 Merge branch 'master' of github.com:requests/requests 2018-09-10 11:05:14 -04:00
Sayz Lim
c3ec370e2d Merge branch 'master' into master 2018-09-10 22:05:13 +07:00
Kenneth Reitz
e976ea839b no more stickers :-/ 2018-09-10 11:04:40 -04:00
Sayz Lim
08b6a78883 Correct fixed footer width 2018-09-10 21:52:30 +07:00
Kenneth Reitz
2072888e28 Merge pull request #4779 from sayzlim/master
Integrate Native CPC by BuySellAds
2018-09-10 10:49:30 -04:00
Sayz Lim
2297d33403 Integrate Native CPC by BuySellAds
Replacing Carbon zone key with the direct key and install CPC ad unit on the site.
2018-09-10 21:45:35 +07:00
Kenneth Reitz
a559d62f17 Revert "updates to docs"
This reverts commit f4818b2010.
2018-09-10 06:29:01 -04:00
Kenneth Reitz
f4818b2010 updates to docs 2018-09-10 06:26:52 -04:00
Kenneth Reitz
33b41c7880 updates 2018-08-29 03:29:14 -04:00
Kenneth Reitz
704abf1332 updates 2018-08-29 03:28:33 -04:00
Nate Prewitt
9cfd292da3 Merge pull request #4723 from kalefranz/fix-no_proxy-file-url
Fix assumed hostname when using a 'file' URI scheme adapter
2018-08-13 09:54:33 -07:00
Kale Franz
8023a01dba Fix assumed hostname when using a 'file' URI scheme adapter 2018-08-13 11:28:35 -05:00
Nate Prewitt
dffd5d435e Merge pull request #4678 from jdufresne/intersphinx
In docs, use intersphinx to link to Python documentation
2018-08-11 20:34:59 -07:00
Jon Dufresne
5aa6a9b654 In docs, use intersphinx to link to Python documentation
The intersphinx extension can generate automatic links to the
documentation of objects in other projects. It was already used for
urllib3. For complete details on intersphinx, see:

http://www.sphinx-doc.org/en/master/ext/intersphinx.html
2018-08-11 17:31:43 -07:00
Nate Prewitt
922aa406b5 updating HISTORY.rst 2018-08-11 12:54:21 -07:00
Nate Prewitt
489f58ced5 represent classifiers as list instead of tuple 2018-08-06 23:04:50 -07:00
Jon Dufresne
c8f3add5ed Update all documentation to show Python 3.7 is supported
Official support was added in 6686ac1730.
2018-08-02 10:55:40 -07:00
Nate Prewitt
285ab5b06b Merge pull request #4755 from dohvis/patch-1
Add return type on cookies.py
2018-08-02 10:53:43 -07:00
Dohyeon Kim
72d96a67ef Add return type on cookies.py
http://docs.python-requests.org/en/master/api/#api-cookies
2018-08-01 17:21:03 +09:00
Nate Prewitt
e4d214dd76 Merge pull request #4749 from derlin/master
make content-type's charset information case-insensitive
2018-07-24 09:42:27 -07:00
Lucy Linder
907c927d60 make content-type's charset information case-insensitive
see issue https://github.com/requests/requests/issues/4748 for more information
2018-07-24 18:13:50 +02:00
Eric Brown
6686ac1730 Add official Python 3.7 support (#4717)
* Add official Python 3.7 support

Python 3.7 was just released [1]. This is a small change to
enable support in requests.

Signed-off-by: Eric Brown <browne@vmware.com>
2018-07-24 07:44:37 -07:00
Nate Prewitt
8e43d34d1f Merge pull request #4701 from akaihola/4700-multivalued-list-form-encoded
Documentation and tests for form-encoded multivalued elements as lists
2018-07-20 09:56:28 -07:00
Antti Kaihola
9c92f757e6 Rolled multi-value form examples in documentation into one (#4700)
As suggested by @nateprewitt
2018-07-20 10:30:31 +03:00
Antti Kaihola
87fb312534 Add myself to the authors list 2018-07-20 10:30:31 +03:00
Antti Kaihola
9a8eb131c9 Documentation for multivalued form-encoded element as a list (#4700) 2018-07-20 10:30:31 +03:00
Antti Kaihola
691e9520ed Add test for multivalued form-encoded element as a list (#4700) 2018-07-20 10:30:31 +03:00
Steven M. Vascellaro
4d51e6d201 Remove unused httpbin parameters
httpbin is used to mock HTTP endpoints. In these methods, the parameter
goes unused.
2018-07-17 19:39:18 -07:00
Nate Prewitt
5aeec8b661 Merge pull request #4739 from moy/doc-list-of-tuples
Document that params and data can be list of tuples everywhere
2018-07-17 15:16:02 -07:00
Matthieu Moy
c008bf3883 Document that 'params' can also be a list of tuples
Like we just did for 'data', 'params' follows the same processing and
can also be a list of tuples.
2018-07-17 18:55:55 +02:00
Matthieu Moy
2d1b4482c5 Document that 'data' can be a list of tuples everywhere
The documentation for the 'data' parameter of various functions was
inconsistant. The low-level function, used by every convenience API,
internally uses RequestEncodingMixin._encode_params which accepts list
of tuples as well as dictionaries, hence every function taking a data
parameter also accepts a list of tuple.

Keep the documentation short, but provide a link to Request for
details.
2018-07-17 18:45:43 +02:00
Kenneth Reitz
f6e13ccfc4 Update MANIFEST.in 2018-07-12 14:16:01 -04:00
Ian Stapleton Cordasco
4499401a55 Merge pull request #4728 from yan12125/patch-1
Fix an invalid escape sequence
2018-07-09 07:19:50 -05:00
Chih-Hsuan Yen
b1a360c2f1 Fix an invalid escape sequence 2018-07-09 01:10:00 +08:00
Nate Prewitt
ef88b9faa6 Merge pull request #4713 from Stevoisiak/fix-docstring-param
Misspelled 'proxy' parameter in docstring
2018-06-26 13:32:32 -07:00
Steven M. Vascellaro
5d90638281 Misspelled 'proxy' parameter in docstring
The 'proxy' parameter was misspelled as 'proxies' in the docstring.
2018-06-26 14:58:18 -04:00
Nate Prewitt
9fc639d030 Merge pull request #4710 from Stevoisiak/remove-unused-sessions
Remove unused session variables
2018-06-26 09:50:40 -07:00
Steven M. Vascellaro
28da72b616 Remove unused session variables
Removed local session variables that go unused during testing.
2018-06-26 12:34:15 -04:00
Kenneth Reitz
943a5c8e89 Merge pull request #4709 from Stevoisiak/update-twitter-max-characters
Update max Twitter characters to 280
2018-06-25 14:11:39 -04:00
Steven M. Vascellaro
0c036feb89 Update max Twitter characters to 280
Twitter expanded the maximum character count per tweet from 140 to 280 in November 2017.
2018-06-25 12:56:14 -04:00
Kenneth Reitz
d79187143f Merge pull request #4708 from Stevoisiak/stack-overflow-typo
Change "StackOverflow" to "Stack Overflow"
2018-06-25 11:48:05 -04:00
Steven M. Vascellaro
3e4efeeb89 Change "StackOverflow" to "Stack Overflow"
Add a missing space when referring to "Stack Overflow".
2018-06-25 11:39:07 -04:00
Nate Prewitt
cd97ce90ba Merge pull request #4685 from Stevoisiak/patch-2
Note that session() should not be used
2018-06-21 12:09:06 -07:00
Steven M. Vascellaro
1c13c5e6f3 Document that requests.session() is depreciated
Adds a docstring note that `requests.session()` is depreciated. Users should
use `requests.Session()` in versions released after Requests v1.0.
2018-06-21 09:46:16 -04:00
Nate Prewitt
883caaf145 v2.19.1 2018-06-14 06:26:27 -07:00
Ian Stapleton Cordasco
2530323faf Merge pull request #4683 from martindurant/docstrings_for_optimize
Do not alter status_codes docstring if it is None
2018-06-13 10:24:45 -05:00
Martin Durant
8031ec76b8 Do not alter status_codes docstring if it is None
With PYTHONOPTIMIZE=2, the current code breaks with TypeError.
2018-06-12 17:52:50 -04:00
Nate Prewitt
991e8b76b7 v2.19.0
* Updated HISTORY.rst.
* Moved version pin for idna to allow recent 2.7 release.
* Updated version warning for urllib3 to allow 1.23.
* Updated metadata dunders in __version__.py.
* Removed Python 2.6 trove classifier.
* Removed Python 2.6 reference from README.rst.
2018-06-12 07:38:10 -07:00
Raymond Hettinger
7e297ed95b Separate collections from collections.abc 2018-06-11 22:14:59 -07:00
Laurent Bachelier
10915e3b0d Add a public method to get the cookie policy 2018-06-11 22:13:07 -07:00
Laurent Bachelier
ace0c200f4 Add cookie policy related tests 2018-06-11 22:13:07 -07:00
Laurent Bachelier
3ef49272f2 Copy cookie policy when copying a CookieJar
Without it, the cookie policy would get lost while making a request.
That would be invisible to the user if the default cookie policy wasn't
changed, of course.
2018-06-11 22:13:07 -07:00
Nate Prewitt
d1aeb7ea8c Merge pull request #4672 from requests/remove_2.6_refs
remove references to 2.6 support in documentation
2018-06-11 07:13:13 -07:00
Nate Prewitt
de64f0f23f port pyopenssl fix from urllib3 2018-06-10 14:49:13 -07:00
Nate Prewitt
bc46de58e6 remove references to 2.6 support in documentation 2018-06-10 14:48:59 -07:00
Nate Prewitt
16fd7e03a9 Merge pull request #4676 from jdufresne/doc-py3
Update Python 2 doc links to Python 3
2018-06-10 08:37:08 -07:00
Jon Dufresne
35a1874912 Update Python 2 doc links to Python 3
The Python 3 docs are better maintained and are the future of Python
development.
2018-06-09 20:29:41 -07:00
Nate Prewitt
d98f881118 Merge pull request #4669 from michael-k/patch-1
Allow urllib3 1.23
2018-06-05 06:35:08 -07:00
Michael
ac944b7439 Allow urllib3 1.23
https://github.com/urllib3/urllib3/blob/1.23/CHANGES.rst#123-2018-06-04
2018-06-05 12:06:03 +00:00
Ian Stapleton Cordasco
00fd4c8eb4 Merge pull request #4661 from ofek/patch-2
Response.content minor perf improvement
2018-05-26 19:00:25 -05:00
Ofek Lev
c1b828bc95 Response.content minor perf improvement 2018-05-26 18:20:27 -04:00
Nate Prewitt
fe8290b3d0 updating HISTORY.rst 2018-05-17 13:56:17 -07:00
Rajiv Mayani
8546a15587 The library raises NoneType error when file-pointer (fp) resolves to None.
>>> from requests import post
>>> r = post("https://example.com", files={"file-name": None})

However, when a param value or json field is None they are not included in the request body.

>>> from requests import get
>>> r = get("https://example.com", params={"file-name": None})
>>> r.request.url

This commit makes the beahviour consistent for files.
2018-05-17 13:56:17 -07:00
Ian Stapleton Cordasco
5f09f0ca7e Merge pull request #4631 from pradyunsg/patch-1
Add long_description_content_type to setup.py
2018-05-17 09:34:06 -05:00
Ian Stapleton Cordasco
8bffd3da5f Merge branch 'master' into patch-1 2018-05-17 09:12:26 -05:00
Nate Prewitt
9b5071cdb6 Merge pull request #4648 from requests/update_lock_file
bring Pipfile.lock up to date with current constraints
2018-05-16 12:31:48 -07:00
Nate Prewitt
c6db87978f bring Pipfile.lock up to date with current constraints 2018-05-16 07:39:43 -07:00
Nate Prewitt
f3fc892b90 bring HISTORY.rst up to date with recent changes 2018-05-16 07:35:44 -07:00
Ian Stapleton Cordasco
161acb6a50 Merge pull request #4410 from linuxlizard/master
Add SHA-256 and SHA-512 digest auth algorithms
2018-05-16 09:06:57 -05:00
Ian Stapleton Cordasco
371ee7cbec Merge branch 'master' into master 2018-05-16 08:46:26 -05:00
Ian Stapleton Cordasco
80e2637a83 Merge pull request #4647 from requests/appveyor_test
fix appveyor
2018-05-16 08:14:37 -05:00
Nate Prewitt
9055b33f6f install Requests separately on appveyor to fix builds 2018-05-15 23:06:43 -07:00
Nate Prewitt
9616f82905 Merge pull request #4625 from nicktimko/patch-1
Certifi.io broken
2018-05-14 09:22:10 -07:00
Nick Timkovich
919c168cdb Certifi.io broken
http://certifi.io/ -> https://certifiio.readthedocs.io/
2018-05-14 09:55:33 -05:00
Kenneth Reitz
adceafd79d Update issue templates 2018-05-13 16:51:44 -04:00
Kenneth Reitz
e02effb774 Merge pull request #4632 from mingrammer/update-license
Update license copyright to 2018
2018-05-13 13:30:57 -04:00
Julien Prigent
60a5a393d8 Add a comment about lowercase env. variables precedence over uppercase 2018-05-13 06:15:56 -07:00
Kenneth Reitz
9e1d8edcb7 Merge branch 'master' into update-license 2018-05-12 17:10:24 -04:00
Ian Stapleton Cordasco
1e8a3142d2 Merge pull request #4634 from vshih/patch-1
Spelling.
2018-05-08 06:12:32 -05:00
Victor Shih
71e402fe40 Spelling. 2018-05-07 10:51:53 -07:00
Pradyun Gedam
048c926b46 README is in ReST 2018-05-07 00:23:38 +05:30
mingrammer
41c455182b Update license copyright to 2018 2018-05-05 09:57:14 +09:00
Pradyun Gedam
5f306dbe99 Add long_description_content_type to setup.py
See:
- https://packaging.python.org/guides/making-a-pypi-friendly-readme/
- https://pypi.org/p/requests/
2018-05-04 16:43:25 +05:30
Nate Prewitt
239ee19431 Merge pull request #4612 from Obeyed/patch-1
update json param's description to avoid confusion
2018-04-30 08:00:19 -07:00
Elias Obeid
75c57985b0 update json param's description to avoid confusion
- the Request class doesn't accept JSON, but a JSON serializable object
2018-04-30 16:50:23 +02:00
Ian Stapleton Cordasco
11b82ca87c Merge pull request #4620 from requests/appveyor_fix
fix windows builds
2018-04-29 18:56:09 -05:00
Nate Prewitt
cd1278ef99 fix windows builds
Appveyor isn't able to replace the running executable. We'll run it
from inside the interpreter to fix build issues.
2018-04-29 10:27:20 -07:00
Ian Stapleton Cordasco
2de907ad77 Merge pull request #4596 from jdufresne/pypi
Update all pypi.python.org URLs to pypi.org
2018-04-19 05:41:37 -05:00
Jon Dufresne
165804b25e Update all pypi.python.org URLs to pypi.org
For details on the new PyPI, see the blog post:

https://pythoninsider.blogspot.ca/2018/04/new-pypi-launched-legacy-pypi-shutting.html
2018-04-18 20:28:19 -07:00
Nate Prewitt
b66908e7b6 Merge pull request #4547 from Saraislet/json-kwarg-docs
add comment about json parameter changing content-type
2018-03-16 12:42:55 -07:00
Hackbright Student
35af0b077f add comment about json parameter changing content-type 2018-03-16 12:34:24 -07:00
Kenneth Reitz
8246b82a16 niteo
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-13 11:28:31 -04:00
Kenneth Reitz
cd6eb30b20 party time
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-12 17:11:08 -04:00
Kenneth Reitz
e203d50e10 every day 2018-03-12 17:07:37 -04:00
Kenneth Reitz
b920c6e3f8 no hr
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-12 17:05:01 -04:00
Kenneth Reitz
6576370b7b cleanup
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-12 17:04:31 -04:00
Kenneth Reitz
85e536f7eb reorder
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-12 17:04:14 -04:00
Kenneth Reitz
130773a2d3 sidebar updates
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-12 17:02:06 -04:00
Kenneth Reitz
87872b9587 sponsored by™ 2018-03-12 16:59:11 -04:00
Kenneth Reitz
3de173e1c9 🍰 2018-03-12 16:54:00 -04:00
Kenneth Reitz
b5eacad638 patron sponsors
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-12 13:50:12 -04:00
Kenneth Reitz
b1ba9173d0 linode
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-12 13:48:12 -04:00
Kenneth Reitz
ee58368c9f typo
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-09 17:02:15 -05:00
Kenneth Reitz
cf0b8ed291 azure
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-09 16:50:13 -05:00
Kenneth Reitz
280c8b2a72 azure
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-09 16:47:27 -05:00
Kenneth Reitz
16b56d822e twilio!
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-09 11:07:37 -05:00
Kenneth Reitz
742610c6b9 linode
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 16:15:31 -05:00
Kenneth Reitz
eb692cb1e1 hiring
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:57:33 -05:00
Kenneth Reitz
f9a9233058 slack improvements
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:56:40 -05:00
Kenneth Reitz
9de992e22c sign off
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:43:27 -05:00
Kenneth Reitz
c063938abb individuals
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:42:17 -05:00
Kenneth Reitz
667367d6b9 better formatting
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:38:55 -05:00
Kenneth Reitz
8ce2fd2557 change order
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:36:29 -05:00
Kenneth Reitz
d8cc045a2e contact
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:35:39 -05:00
Kenneth Reitz
dc10a5dadd sponsors
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:34:07 -05:00
Kenneth Reitz
bf32936955 cleanup
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:33:26 -05:00
Kenneth Reitz
05b1401795 links
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:32:18 -05:00
Kenneth Reitz
873e8914c1 some
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:31:18 -05:00
Kenneth Reitz
c55258792b cleanup
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:30:33 -05:00
Kenneth Reitz
afad1aab14 community
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:28:55 -05:00
Kenneth Reitz
d05840d34d sponsors
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:28:41 -05:00
Kenneth Reitz
3323e65e96 track fundraiser on personal site
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 15:11:59 -05:00
Kenneth Reitz
74cf6fc38e \o/
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 09:19:28 -05:00
Kenneth Reitz
d91b70bd29 512
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-08 06:29:53 -05:00
Kenneth Reitz
5daa6cc63c $253
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 20:06:13 -05:00
Kenneth Reitz
0730b231ec $203
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 20:02:12 -05:00
Kenneth Reitz
77aa42943e more info
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 19:42:03 -05:00
Kenneth Reitz
b98027af9e donations
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 19:41:24 -05:00
Kenneth Reitz
8ce2c1a182 one time
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 19:27:15 -05:00
Kenneth Reitz
327a54d29d sidebar
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 19:24:45 -05:00
Kenneth Reitz
38a1947957 $10
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 19:11:45 -05:00
Kenneth Reitz
f8ade96762 sidebar
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 18:52:24 -05:00
Kenneth Reitz
665bb2a687 fix
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 18:49:49 -05:00
Kenneth Reitz
f21fd19ac5 goals
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 18:44:36 -05:00
Kenneth Reitz
f51c489d38 fix
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:41:09 -05:00
Kenneth Reitz
773eeff1a2 authors
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:40:38 -05:00
Kenneth Reitz
ac0a7ed152 fix
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:38:05 -05:00
Kenneth Reitz
a4f313a0e5 development
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:36:35 -05:00
Kenneth Reitz
8ca453a8d7 white
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:35:21 -05:00
Kenneth Reitz
c436165a2d gitignore
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:34:04 -05:00
Kenneth Reitz
97b28fdf7f top bar
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:33:51 -05:00
Kenneth Reitz
40f4b984ef index
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:18:27 -05:00
Kenneth Reitz
529c423fb5 support for Requests 3.0
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:15:59 -05:00
Kenneth Reitz
e292f302b7 different form
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 17:01:50 -05:00
Kenneth Reitz
c95b63736d links
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 16:56:58 -05:00
Kenneth Reitz
2d357f9c3b cleanup
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 16:55:18 -05:00
Kenneth Reitz
7fb1d70b86 fix fix fix
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 16:54:40 -05:00
Kenneth Reitz
c78c5002b5 important
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 16:51:30 -05:00
Kenneth Reitz
d123e9fe78 fix broken things
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 16:48:44 -05:00
Kenneth Reitz
8ad24ad430 experiment
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-03-07 16:44:57 -05:00
David Poole
85ec7d759e Merge branch 'master' into master 2018-03-05 09:07:12 -07:00
Kenneth Reitz
4ea09e49f7 .org
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-02-27 10:19:31 -05:00
Kenneth Reitz
06e788e253 <li><a href="http://html.python-requests.com/">Requests-HTML</a></li>
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-02-27 09:18:00 -05:00
Kenneth Reitz
27aad3666c Merge branch 'master' of github.com:requests/requests 2018-02-27 08:44:37 -05:00
Kenneth Reitz
44dbf8cf40 updated copyright year
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-02-27 08:44:29 -05:00
Kenneth Reitz
6e76aaea45 nike
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-02-22 08:34:32 -05:00
Jon Dufresne
265ef609d5 Remove remaining references to removed, vendored packages (#4499)
As the vendored packages were removing in version 2.16, all remaining
doc references should be replaced with newer practices.
2018-02-17 08:15:54 -06:00
Nate Prewitt
cafa3c16c2 Merge pull request #4497 from jdufresne/docs-certfi
Clarify docs that Requests always uses certs from certifi
2018-02-15 17:56:00 -08:00
Jon Dufresne
9c0db92249 Clarify docs that Requests always uses certs from certifi
Since commit 0d7de6430e, certifi is always
used for certificates. Certify became a hard dependency of the package
in 628633143d.

Now update the docs to clarify that Request will always use certificates
from certifi.
2018-02-14 05:47:34 -08:00
Kenneth Reitz
3c1d36b827 Merge branch 'master' of github.com:requests/requests
# Conflicts:
#	docs/_templates/sidebarintro.html
#	docs/_templates/sidebarlogo.html

Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-02-12 09:43:07 -05:00
Kenneth Reitz
3cd87fac5d new sidebar link
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2018-02-12 09:42:09 -05:00
Semen Zhydenko
22120d423e Fix typos
nonexistant -> nonexistent
neccessary -> necessary
2018-02-07 18:25:22 -06:00
Nate Prewitt
654da610e1 Merge pull request #4498 from jdufresne/ws
Trim trialing white space throughout the project
2018-02-05 08:37:19 -08:00
Jon Dufresne
e8205c0131 Trim trialing white space throughout the project
Many editors clean up trailing white space on save. By removing it all
in one go, it helps keep future diffs cleaner by avoiding spurious white
space changes on unrelated lines.
2018-02-05 06:23:53 -08:00
Ian Stapleton Cordasco
8da118dfeb Merge pull request #4493 from nateprewitt/3.7_testing
Start testing 3.7
2018-02-03 08:43:31 -06:00
Ian Stapleton Cordasco
d69c068ac2 Merge branch 'master' into 3.7_testing 2018-02-03 08:33:55 -06:00
Ian Stapleton Cordasco
3ad14bb54e Merge pull request #4496 from lolatravel/pass_send_kwargs_to_add_headers
Pass kwargs from adapter send call to add_headers, per documentation
2018-02-03 07:40:44 -06:00
Jonathan Elliott Blum
8e040523a4 pass kwargs from send call to add_headers, per documentation 2018-02-02 13:10:16 -05:00
Nate Prewitt
99533b0f0f start testing 3.7 2018-01-26 03:01:22 -08:00
Nate Prewitt
512066488e updating history 2018-01-21 11:06:33 -08:00
Nate Prewitt
d2e1130603 Merge pull request #4452 from nateprewitt/append_fragment_on_redirect
append previous url fragment on redirect
2018-01-21 10:41:46 -08:00
Nate Prewitt
f60324a3de append previous url fragment on redirect 2018-01-21 09:55:45 -08:00
Ian Stapleton Cordasco
f89c325fbe Merge pull request #4439 from nkonin/fix/certifi-broken-link
Fix broken link to Certifi
2018-01-21 08:36:31 -06:00
Ian Stapleton Cordasco
d55b81b964 Merge branch 'master' into fix/certifi-broken-link 2018-01-21 08:12:19 -06:00
Kenneth Reitz
6a74c70a3a merge 2018-01-20 09:02:15 -05:00
Kenneth Reitz
599a8f11f8 sidebar 2018-01-20 09:01:50 -05:00
Никита Конин
0813c865ee Fix broken link to Certifi 2018-01-18 20:14:33 +03:00
Ian Stapleton Cordasco
07372dc058 Merge pull request #4427 from ddormer/4275-use-hostname-not-netloc
Use hostname not netloc
2018-01-16 08:07:26 -06:00
Darren Dormer
2255c34a65 Fix DNS resolution by using hostname instead of netloc and strip username and password when comparing against proxy bypass items. 2018-01-16 10:18:06 +01:00
Nate Prewitt
020f96577f Merge pull request #4459 from jdufresne/pyreq
Pass python_requires argument to setuptools
2018-01-12 20:06:59 -08:00
Jon Dufresne
7cefa939f5 Pass python_requires argument to setuptools
Helps pip decide what version of the library to install.

https://packaging.python.org/tutorials/distributing-packages/#python-requires

> If your project only runs on certain Python versions, setting the
> python_requires argument to the appropriate PEP 440 version specifier
> string will prevent pip from installing the project on other Python
> versions.

https://setuptools.readthedocs.io/en/latest/setuptools.html#new-and-changed-setup-keywords

> python_requires
>
> A string corresponding to a version specifier (as defined in PEP 440)
> for the Python version, used to specify the Requires-Python defined in
> PEP 345.
2018-01-12 16:39:10 -08:00
Ian Stapleton Cordasco
b9d8e00cbc Merge pull request #4460 from jdufresne/py33
Remove unsupported Python 3.3 from tox.ini
2018-01-11 08:41:08 -06:00
Jon Dufresne
620a5391c3 Remove unsupported Python 3.3 from tox.ini
Python 3.3 is not a supported version so don't test it.
2018-01-10 18:37:22 -08:00
Nate Prewitt
c98e30b5cb Merge pull request #4451 from jdufresne/https
Prefer https over http for links in the documentation
2018-01-06 15:22:59 -08:00
Jon Dufresne
030dcce20c Prefer https over http for links in the documentation
- Fixed Read the Docs links
- Fixed GitHub links
- Fixed PyPI links
2018-01-06 11:23:50 -08:00
Ian Stapleton Cordasco
3dc84cde5b Merge pull request #4442 from DemetriosBairaktaris/master
Reduce overall memory usage by removing cgi dependency and writing a protected function
2018-01-04 16:32:39 -06:00
dbairaktaris1
e0ab287317 added more to test scenarios 2018-01-04 10:59:47 -06:00
dbairaktaris1
7deee699ad slice function removed 2018-01-04 10:48:17 -06:00
dbairaktaris1
cb0914407b Continue to refactor, remove list comprehension, add double quotes test case. 2018-01-04 10:30:50 -06:00
dbairaktaris1
80a790443e implement changes after code review 2018-01-03 23:41:41 -06:00
dbairaktaris1
071796d83f implement changes after code review 2018-01-03 23:40:08 -06:00
dbairaktaris1
1988d9cf72 Move nested function up to module level and rename. Add more tests for function. 2018-01-01 14:20:55 -06:00
dbairaktaris1
2dc51c887f added versions back 2018-01-01 00:43:13 -06:00
dbairaktaris1
19cfec28a8 CI 2017-12-31 22:18:19 -06:00
dbairaktaris1
cef0830419 clean 2017-12-31 15:02:39 -06:00
dbairaktaris1
d8666e1906 Reduce overall memory usage of Requests module by removing cgi module dependency in utils.py. Instead wrote a nested function to parse header and return content type and params. 2017-12-31 14:46:15 -06:00
David Poole
efacb9e312 Merge branch 'master' into master 2017-11-29 07:13:07 -07:00
David Poole
1e46cbb4f0 add test for HTTP Digest auth algorithms SHA-256 and SHA-512 2017-11-29 07:10:57 -07:00
Cory Benfield
24092b11d7 Merge pull request #4380 from afedchin/win10
utils: winreg module may not exist like on windows universal platform.
2017-11-27 20:39:15 +00:00
Anton Fedchin
351ec982bb update changelog 2017-11-25 17:21:59 +03:00
Anton Fedchin
714c9dc967 utils: winreg module may not exist like on windows universal platform. 2017-11-25 17:21:59 +03:00
Cory Benfield
d1fb1a29ab Merge pull request #4394 from zaneb/document-status_codes
Add documentation for available status codes
2017-11-23 20:19:12 +00:00
Cory Benfield
c2507013ab Merge branch 'master' into document-status_codes 2017-11-22 20:41:46 +00:00
Nate Prewitt
e68ef0ecad Merge pull request #4368 from danielroseman/patch-1
Clarify behaviour of `json` parameter.
2017-11-22 07:56:09 -08:00
Zane Bitter
19919b44c4 Add documentation for available status codes
There was no way to determine what actual names were available outside
of looking at the source code. They were not listed in the documentation
or accessible through the interactive help.

In addition, doing `pydoc requests.status_codes` displayed some pretty
unhelpful information - the utf-8 encoding string was included in the
module name, there was no description, and internal variables used for
initialisation leaked into the module scope:

    DATA
        code = 511
        codes = <lookup 'status_codes'>
        title = 'network_authentication'
        titles = ('network_authentication_required', 'network_auth', ...

This change prevents the internal variables from leaking, adds a
docstring (which has the side-effect of correcting the module name), and
appends information on the allowed status code names to the docstring
when the module is initialised.

The improved module documentation is then used in the API documentation
to provide another easy reference to the complete list of status codes.
2017-11-21 16:11:34 -05:00
Daniel Roseman
39446def39 Clarify behaviour of json parameter.
`json` is ignored if `data` or `files` is not empty.
2017-11-21 13:40:59 +00:00
Mingyuan Xia
acd2645444 #4373, fix possible winreg value type difference (#4377)
* #4373, fix possible winreg value type difference

* add a test for ProxyOverride and ProxyEnable on win32

* add tests for winreg key ProxyEnable with two possible types

* fixing AppVeyor failures
2017-11-20 20:01:04 +00:00
Ian Stapleton Cordasco
e4fc3539b4 Merge pull request #4390 from alexwlchan/ok-docs
[docs; tiny] Clarify that Response.ok will *only* return True/False
2017-11-20 07:18:00 -06:00
Alex Chan
775cde0914 Clarify that Response.ok will *only* return True/False 2017-11-20 09:16:35 +00:00
David Poole
a31531fb9c Merge branch 'master' into master 2017-11-19 08:45:25 -07:00
Cory Benfield
c3f2553114 Merge pull request #4387 from dave-shawley/clarify-docs
Clarify raw response reading in the quickstart.
2017-11-18 09:44:29 +00:00
Dave Shawley
7cc3d8dc6a docs/quickstart: clarify raw response reading. 2017-11-17 16:37:08 -05:00
Ian Stapleton Cordasco
6d69f944a4 Merge pull request #4384 from taleinat/quickstart_doc_http_to_html
Correct HTTP -> HTML in quickstart doc
2017-11-16 10:01:45 -06:00
Tal Einat
7f08ad3b6c Corrent HTTP -> HTML in quickstart doc 2017-11-16 09:59:00 +02:00
Nate Prewitt
d55de2d391 Merge pull request #4356 from nehaljwani/fix-4353
Check if host is invalid for proxy
2017-11-15 14:16:33 -08:00
Nehal J Wani
9a8a826f22 Check if host is invalid for proxy
According to RFC3986, the authority section can be empty for a given URL,
however, for a proxy URL, it shouldn't be. This patch adds a check to verify
that the parsed URL will have a valid host before creating the proxy manager.

Fixes #4353
2017-11-15 08:58:54 -05:00
David Poole
1dbaddd75e for RFC-7616 add SHA-256 and SHA-512 2017-11-08 18:32:59 -07:00
Cory Benfield
234f80af88 Merge pull request #4371 from Twistbioscience/zipfile_compat
support extraction of certificate bundle from a zip archive
2017-11-06 21:08:45 +00:00
Arthur Vigil
c86b09b3c6 support extraction of certificate bundle from a zip archive 2017-11-05 12:14:17 -08:00
Nate Prewitt
81b63419cb Merge pull request #4352 from alexwlchan/hooks-on-sessions
Add something to the docs about hooks on Session()
2017-10-24 11:50:03 -07:00
Alex Chan
c5ed41e00a Add an example of two hooks 2017-10-24 07:27:55 +01:00
Alex Chan
40c5a8b0c2 Clarify that a Session can have multiple hooks 2017-10-23 13:25:46 +01:00
Alex Chan
87f3b0a559 Switch to using dict literals, it's 2017 2017-10-23 13:25:31 +01:00
Alex Chan
2c4849defe Add something to the docs about hooks on Session() 2017-10-23 08:30:35 +01:00
Nate Prewitt
c4c031fc5c Merge pull request #4342 from jdufresne/wheel-license
Include license file in the generated wheel package
2017-10-21 16:53:01 -07:00
Jon Dufresne
1595e43812 Include license file in the generated wheel package
The wheel package format supports including the license file. This is
done using the [metadata] section in the setup.cfg file. For additional
information on this feature, see:

https://wheel.readthedocs.io/en/stable/index.html#including-the-license-in-the-generated-wheel-file
2017-10-21 16:39:48 -07:00
Cory Benfield
8982efa9e4 Merge pull request #4349 from alvarogzp/patch-1
Fix case-insensitive comparison in Session.get_adapter
2017-10-21 06:26:31 -07:00
Alvaro Gutierrez Perez
2afc1cb37b Merge branch 'master' into patch-1 2017-10-21 03:24:55 +02:00
Cory Benfield
db9da3e0d2 Merge pull request #4316 from methane/no-platform
Avoid importing platform
2017-10-19 17:47:40 -07:00
INADA Naoki
a05aac7007 avoid import platform
platform module is relatively large: it takes about 5ms to import
2017-10-20 02:49:22 +09:00
Alvaro Gutierrez Perez
d165b18b6e Split test in two better-defined tests 2017-10-19 17:04:48 +02:00
Alvaro Gutierrez Perez
e11989e8ec Add test for Session.get_adapter() prefix matching 2017-10-19 16:50:13 +02:00
Alvaro Gutierrez Perez
af88af64e6 Add test for Session.get_adapter() case-insensitivity 2017-10-19 16:50:13 +02:00
Alvaro Gutierrez Perez
d3f14af44d Fix case-insensitive comparison in get_adapter()
While trying to get the prefix for an url, the url was lowered before comparing but the prefix not, so if it contains non-lowercase characters (eg. https://api.example.com/sOmE_WeiRD_pReFIX/), it won't match.
2017-10-18 19:27:06 +02:00
Nate Prewitt
54ad3d6dcc Merge pull request #4343 from jdufresne/classifier
Add missing trove classifier to document Python2 support
2017-10-16 01:21:19 -07:00
Jon Dufresne
c14bd018ad Add missing trove classifier to document Python2 support 2017-10-15 19:48:10 -07:00
Nate Prewitt
e86df6e0eb Merge pull request #4341 from hugovk/patch-1
Python 3.7 not officially supported yet
2017-10-15 13:35:52 -07:00
Hugo
ec5804c706 Python 3.3 has already been dropped (#4231) 2017-10-15 20:04:51 +03:00
Hugo
4316af7ae8 Python 3.7 not officially supported yet 2017-10-15 19:52:19 +03:00
Cory Benfield
8c4f78448a Merge pull request #4332 from PrimordialHelios/pyopenssl-warning
Warn about possible slowness on older versions of pyOpenSSL
2017-10-14 08:41:02 -07:00
Taylor Rose
15054aa390 Warn user about possible slowdown when using cryptography version <
1.3.4
2017-10-14 09:00:58 -04:00
Kenneth Reitz
9713289e74 Merge branch 'master' of github.com:requests/requests 2017-09-25 11:04:47 -04:00
Kenneth Reitz
e6afc37be5 new pipfile with new syntax
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-25 11:04:38 -04:00
Ian Stapleton Cordasco
5eb0811ef8 Merge pull request #4305 from sigmavirus24/fix-pypi-display
Fix the invalid restructured text in HISTORY file
2017-09-23 16:21:48 -05:00
Ian Stapleton Cordasco
40c8bcf70c Fix the invalid restructured text in HISTORY file
This was breaking the display of our long_description on PyPI.
2017-09-23 15:54:14 -05:00
Kenneth Reitz
0eb9a4c161 stickers
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-19 13:23:15 -04:00
Kenneth Reitz
cda429aa5d Merge pull request #4295 from requests/pipenv
pipfile (work in progress)
2017-09-17 11:58:46 -04:00
Kenneth Reitz
28ae74dbad update tests
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-17 11:46:33 -04:00
Kenneth Reitz
a9d05f06cd remove requirements.txt
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-17 11:39:53 -04:00
Kenneth Reitz
d552132464 run coverage w/ pipenv
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-17 11:36:54 -04:00
Kenneth Reitz
c3ecb825c4 don't test on 2.6
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-17 11:30:26 -04:00
Kenneth Reitz
70a4ae744c pip install pipenv
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-17 11:26:22 -04:00
Kenneth Reitz
4c300c2067 pipfile
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-09-17 11:24:05 -04:00
Kenneth Reitz
fdb9b753b4 Update authors.rst 2017-09-05 11:31:16 -04:00
Kenneth Reitz
4bda7b66e7 Update updates.rst 2017-09-04 16:21:57 -04:00
Kenneth Reitz
068d8863d1 Update support.rst 2017-09-04 16:21:04 -04:00
Kenneth Reitz
c49f3643ae Update release-process.rst 2017-09-04 16:20:03 -04:00
Kenneth Reitz
328cff252d Update out-there.rst 2017-09-04 16:19:36 -04:00
Kenneth Reitz
c57bd07a34 Update faq.rst 2017-09-04 16:19:01 -04:00
Kenneth Reitz
0d82afa0c3 Update recommended.rst 2017-09-04 16:18:00 -04:00
Kenneth Reitz
18e37c9368 Update todo.rst 2017-09-04 16:14:48 -04:00
Kenneth Reitz
389da34fc9 Update philosophy.rst 2017-09-04 16:14:07 -04:00
Kenneth Reitz
8ef20d5c36 Update contributing.rst 2017-09-04 16:13:08 -04:00
Kenneth Reitz
e63d481a7a Update authors.rst 2017-09-04 16:12:38 -04:00
Kenneth Reitz
f3eeb38542 Update vulnerabilities.rst 2017-09-04 16:11:52 -04:00
Kenneth Reitz
afaaae185c Update authentication.rst 2017-09-04 16:10:49 -04:00
Kenneth Reitz
8af65a1eca Update quickstart.rst 2017-09-04 16:09:51 -04:00
Kenneth Reitz
c04b044b30 Update advanced.rst 2017-09-04 16:09:08 -04:00
Kenneth Reitz
530198e0c0 Update install.rst 2017-09-04 16:08:22 -04:00
Kenneth Reitz
8c57515696 Update intro.rst 2017-09-04 16:05:57 -04:00
Kenneth Reitz
175452a6b6 Update index.rst 2017-09-04 16:04:07 -04:00
Kenneth Reitz
e35c829b59 Update index.rst 2017-09-04 16:03:49 -04:00
Kenneth Reitz
1ad51b0a41 Update index.rst 2017-09-04 15:55:53 -04:00
Kenneth Reitz
8be8105c42 Update advanced.rst 2017-09-04 15:53:26 -04:00
Kenneth Reitz
49ec082a77 Update recommended.rst 2017-09-04 15:50:38 -04:00
Kenneth Reitz
0488c640e2 Update index.rst 2017-09-04 15:46:47 -04:00
Kenneth Reitz
8371b56d0f Delete extensions.rst 2017-09-04 15:46:24 -04:00
Kenneth Reitz
830c18e4f9 Update index.rst 2017-09-04 15:45:28 -04:00
Kenneth Reitz
2c438cacd1 Create extensions.rst 2017-09-04 15:44:57 -04:00
Kenneth Reitz
9c8ae76928 Update index.rst 2017-09-04 15:40:02 -04:00
Kenneth Reitz
d5a05469f1 Update README.rst 2017-09-04 15:38:13 -04:00
Kenneth Reitz
e22e3a5059 Update README.rst 2017-09-04 15:37:24 -04:00
Kenneth Reitz
054ad4aa67 Update README.rst 2017-09-04 12:59:01 -04:00
Kenneth Reitz
b9638ec7be taste 2017-09-01 13:10:52 -04:00
Kenneth Reitz
940c1246e0 taste 2017-09-01 13:10:29 -04:00
Kenneth Reitz
e0e5b2e3aa Update philosophy.rst 2017-08-29 16:16:52 -04:00
Kenneth Reitz
96b9a3f0fc Update setup.py 2017-08-28 12:25:26 -04:00
Cory Benfield
657e44ad9a Merge pull request #4265 from PascalVA/patch-2
fixed syntax for code block for prepared requests
2017-08-28 10:39:26 +01:00
Pascal Van Acker
ac9a3e5320 fixed syntax for code block for prepared requests 2017-08-28 11:14:05 +02:00
Cory Benfield
6b21682712 Merge pull request #4264 from PascalVA/patch-1
Add environment info to prepared requests docs
2017-08-28 10:08:07 +01:00
Pascal Van Acker
785c733415 Add environment info to prepared requests
When using prepared requests, the environment is not taken into account. This should be reflected in the documentation.
2017-08-28 10:58:44 +02:00
Kenneth Reitz
369be8afd0 pretty little note
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-08-28 02:01:36 -04:00
Kenneth Reitz
572d2f4534 Python 2 Death Sentence™
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-08-28 01:50:35 -04:00
Kenneth Reitz
7e20b9193a Update index.rst 2017-08-28 01:33:45 -04:00
Kenneth Reitz
ad1aff52a0 Update index.rst 2017-08-28 01:33:32 -04:00
Kenneth Reitz
3a6dec9827 Update index.rst 2017-08-28 01:29:29 -04:00
Kenneth Reitz
3cceee3459 Update install.rst 2017-08-27 23:16:32 -04:00
Kenneth Reitz
dd57439fa5 Update README.rst 2017-08-27 23:13:50 -04:00
Cory Benfield
f09e462165 Merge pull request #4261 from Lukasa/fix-broken-tests
Pin to httpbin 0.5.0.
2017-08-27 14:00:37 +01:00
Cory Benfield
3a2ea9deba Pin to httpbin 0.5.0 2017-08-27 08:54:01 +01:00
Kenneth Reitz
5dcbdb50fc docs update 2017-08-25 22:12:34 -04:00
Kenneth Reitz
8ad09b68ea coinbin.org 2017-08-25 22:02:03 -04:00
Kenneth Reitz
88dc33522d Merge branch 'master' of https://github.com/requests/requests 2017-08-20 20:56:54 -04:00
Kenneth Reitz
e5666b93cf btc
Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
2017-08-20 20:56:48 -04:00
Cory Benfield
554a210f88 Merge pull request #4245 from remram44/fix-headers-links
Fix parse_header_links on empty header
2017-08-17 20:34:06 +01:00
Remi Rampin
8e411d0f99 Add test case for empty Link: header 2017-08-17 12:56:45 -04:00
Remi Rampin
7d190ef010 Add entry in HISTORY.rst 2017-08-17 12:56:38 -04:00
Remi Rampin
965ada6f66 Fix parse_header_links on empty header 2017-08-16 22:10:20 -04:00
Cory Benfield
af9dd61fcb Prepare for new release 2017-08-15 14:24:20 +01:00
Cory Benfield
a3d7cf3f27 v2.18.4 2017-08-15 14:22:52 +01:00
Cory Benfield
3c5ecfc9f5 Merge pull request #4240 from mgasvoda/master
Adding header name to exception
2017-08-12 15:41:27 +01:00
mgasvoda
d528106876 Adding record to history 2017-08-12 10:23:45 -04:00
mgasvoda
cbc7c2d1c9 Modifying tests to include header name info 2017-08-11 17:18:58 -04:00
mgasvoda
e36083b89c Adding space after colon 2017-08-11 16:19:43 -04:00
mgasvoda
308343508b Removing trailing whitespace 2017-08-11 16:14:13 -04:00
mgasvoda
ba21d14976 Improving message formatting 2017-08-11 16:12:36 -04:00
mgasvoda
cee8fae65e Adding header name to exception
Adds the name of the header to the invalid header exception raised on TypeError.
2017-08-11 15:37:57 -04:00
Kenneth Reitz
1c2022cf86 Merge pull request #4231 from Lukasa/drop-3.3-support
Drop Python 3.3 support.
2017-08-10 14:03:36 -04:00
Kenneth Reitz
8480cf937a Merge pull request #4237 from robinske/doc-import
Adds import statement to front page of docs for clarity and quicker start up
2017-08-10 14:02:57 -04:00
Kelley Robinson
f6952a9b8d Merge branch 'master' into doc-import 2017-08-10 10:33:22 -07:00
kelley
d758f0cf97 Adds import statement to front page of docs for clarity and quicker start up 2017-08-10 10:23:43 -07:00
Cory Benfield
c31a450c55 Remove references to 3.3 from the docs 2017-08-09 19:40:52 +01:00
Cory Benfield
0a2dc74ecb Drop Python 3.3 support 2017-08-09 19:03:04 +01:00
Cory Benfield
f78a57936b Merge pull request #4229 from NikosVlagoidis/issue#3863
Fixes issue #3863
2017-08-09 18:56:40 +01:00
NikosVlagoidis
218978601f Fix issue #3863 2017-08-09 20:18:43 +03:00
NikosVlagoidis
cb9620780f Update advanced.rst 2017-08-09 18:52:26 +03:00
Nikolaos Vlagoidis
963c78853f Fixes issue #3863 2017-08-09 15:38:45 +03:00
Kenneth Reitz
b670b61d54 Update AUTHORS.rst 2017-08-08 19:16:39 -04:00
Cory Benfield
9ec2005d9f Merge pull request #4223 from Lukasa/widen-idna-pin
Allow IDNA 2.6
2017-08-08 15:42:54 +01:00
Cory Benfield
f4ddf00c36 Allow IDNA 2.6 2017-08-08 13:32:15 +01:00
Cory Benfield
248f122970 Merge pull request #4217 from nikolas/patch-1
fix typo in changelog
2017-08-02 15:38:46 +01:00
Nik Nyby
be8ce365ab fix typo in changelog 2017-08-02 10:26:41 -04:00
Cory Benfield
3393dc8221 Prepare changelog for next release 2017-08-02 14:24:02 +01:00
Cory Benfield
7c67c4adf9 v2.18.3 2017-08-02 14:22:44 +01:00
Ian Stapleton Cordasco
2a4dd64fb4 Merge pull request #4210 from Lukasa/sslerror
Make sure we raise SSLError.
2017-07-29 06:27:17 -05:00
Cory Benfield
9e0fb37fff Changelog for #4209 2017-07-29 12:13:55 +01:00
Cory Benfield
4f49f6b3ed Correctly raise SSLError from urllib3. 2017-07-29 12:12:11 +01:00
Cory Benfield
8b3f20ca91 Add failing test for #4209 2017-07-29 12:09:04 +01:00
Nate Prewitt
fdf426125b Merge pull request #4182 from alexwlchan/idna-version
Add idna version info to requests.help
2017-07-27 14:54:09 -06:00
Alex Chan
d6b57c6fb2 Changelog entry 2017-07-27 21:33:44 +01:00
Alex Chan
39b121d791 Add idna version info to requests.help 2017-07-27 21:33:42 +01:00
Nate Prewitt
12c7456789 Merge pull request #4174 from alex/patch-2
Removed legacy fallback for python3.2
2017-07-27 09:51:33 -06:00
Alex Gaynor
2629c0906e Merge branch 'master' into patch-2 2017-07-27 11:19:32 -04:00
Cory Benfield
205755834d Merge pull request #4207 from markjszy/master
remove legacy super() call
2017-07-27 05:40:03 +01:00
Mark Szymanski
e2f5a135c3 remove legacy super() call 2017-07-26 19:21:45 -05:00
Cory Benfield
8de858f0de Merge pull request #4206 from jvanasco/feature-redirects
some docs on request redirect detection
2017-07-26 20:57:22 +01:00
jonathan vanasco
667896c557 some docs on request redirect detection 2017-07-26 15:32:07 -04:00
Cory Benfield
2b6f1e6236 Merge pull request #4204 from browniebroke/patch-1
Correct urllib3 compatibility comment
2017-07-26 11:03:57 +01:00
Bruno Alla
b77c1a3deb Correct urllib3 compatibility comment
So that it's in line with the code. I saw the warning raised recently and had to dive into the code for exact compatibility, but I stopped after reading the comment rather than the code. 
Maybe a better solution would be to surface the supported versions in the warning, but I see it was changed recently in https://github.com/requests/requests/pull/4144/
2017-07-26 10:23:01 +01:00
Cory Benfield
9e8d403a21 Prepare changelog for next release 2017-07-25 16:23:50 +01:00
Cory Benfield
6cc891fd32 v2.18.2 2017-07-25 16:21:48 +01:00
Cory Benfield
49c44a0c08 Merge pull request #4198 from andportnoy/patch-1
redundant comma
2017-07-21 07:05:10 +01:00
Andrey Portnoy
c6e18b04e3 redundant comma 2017-07-20 20:49:24 -07:00
Ian Stapleton Cordasco
c10b8384e4 Merge pull request #4196 from Lukasa/require-next-urllib3
Allow urllib3 1.22
2017-07-20 06:52:11 -05:00
Cory Benfield
8d1228cd19 Allow urllib3 1.22 2017-07-20 10:08:50 +01:00
Cory Benfield
8e227aeb89 Merge pull request #4195 from requests/requests/sessions-mount-docstring-clarity
Use 'prefix' instead of 'key' in session docstring
2017-07-20 09:13:06 +01:00
Alex Muller
d8c2fdf92f Use 'prefix' instead of 'key' in session docstring
This commit makes the API docs more clear. The 'key' is an
implementation detail.
2017-07-20 10:06:34 +02:00
Cory Benfield
cada19b300 Merge pull request #4192 from koobs/patch-2
Add requirements.txt to MANIFEST.in
2017-07-15 07:39:01 +01:00
Kubilay Kocak
c6a80640d1 Add requirements.txt to MANIFEST.in 2017-07-15 14:44:57 +10:00
Kenneth Reitz
649efc8c9b Merge branch 'master' of github.com:kennethreitz/requests 2017-07-06 17:57:37 -04:00
Kenneth Reitz
14176d1d63 no more stickers 2017-07-06 17:57:28 -04:00
Cory Benfield
1ea4e21958 Merge pull request #4183 from requests/fix_help_ssl_check
Fix help ssl check
2017-07-04 09:16:02 +01:00
Nate Prewitt
51feabbc27 test ssl version check functions as expected in python 2.6 2017-07-04 00:33:16 -06:00
Nate Prewitt
f6e07bb27f fix OPENSSL_VERSION_NUMBER check on Python2.6's ssl module 2017-07-03 17:21:56 -06:00
Alex Gaynor
c054a722bb Removed legacy fallback for python3.2 2017-06-25 12:51:15 -04:00
Kenneth Reitz
bbeb1c32d2 Merge branch 'master' of github.com:kennethreitz/requests 2017-06-16 18:31:19 -04:00
Kenneth Reitz
1263b8660d stickers 2017-06-16 18:30:39 -04:00
Cory Benfield
2fde9ee407 Setup HISTORY for next release 2017-06-14 18:52:03 +01:00
Cory Benfield
51de61f914 v2.18.1 2017-06-14 18:50:53 +01:00
Cory Benfield
dd13b13479 Prepare for next release cycle 2017-06-14 16:45:03 +01:00
140 changed files with 8674 additions and 5561 deletions

View File

@@ -1,2 +1,2 @@
[run]
omit = requests/packages/*
omit = requests/packages/*

5
.git-blame-ignore-revs Normal file
View File

@@ -0,0 +1,5 @@
# You can configure git to automatically use this file with the following config:
# git config --global blame.ignoreRevsFile .git-blame-ignore-revs
# Add automatic code formatting to Requests
2a6f290bc09324406708a4d404a88a45d848ddf9

6
.github/CODE_OF_CONDUCT.md vendored Normal file
View File

@@ -0,0 +1,6 @@
# Treat each other well
Everyone participating in the _requests_ project, and in particular in the issue tracker,
pull requests, and social media activity, is expected to treat other people with respect
and more generally to follow the guidelines articulated in the
[Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/).

View File

@@ -1,10 +1,7 @@
# Contribution Guidelines
Before opening any issues or proposing any pull requests, please do the
following:
1. Read our [Contributor's Guide](http://docs.python-requests.org/en/latest/dev/contributing/).
2. Understand our [development philosophy](http://docs.python-requests.org/en/latest/dev/philosophy/).
Before opening any issues or proposing any pull requests, please read
our [Contributor's Guide](https://requests.readthedocs.io/en/latest/dev/contributing/).
To get the greatest chance of helpful responses, please also observe the
following additional notes.

1
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1 @@
custom: ['https://www.python.org/psf/sponsorship/']

View File

@@ -25,4 +25,4 @@ import requests
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).
operating system, &c).

36
.github/ISSUE_TEMPLATE/Bug_report.md vendored Normal file
View File

@@ -0,0 +1,36 @@
---
name: Bug report
about: Create a report to help us improve
---
<!-- Summary. -->
## Expected Result
<!-- What you expected. -->
## Actual Result
<!-- What happened instead. -->
## Reproduction Steps
```python
import requests
```
## System Information
$ python -m requests.help
```json
{
"paste": "here"
}
```
<!-- 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). -->

10
.github/ISSUE_TEMPLATE/Custom.md vendored Normal file
View File

@@ -0,0 +1,10 @@
---
name: Request for Help
about: Guidance on using Requests.
labels:
- "Question/Not a bug"
- "actions/autoclose-qa"
---
Please refer to our [Stack Overflow tag](https://stackoverflow.com/questions/tagged/python-requests) for guidance.

View File

@@ -0,0 +1,10 @@
---
name: Feature request
about: Suggest an idea for this project
labels:
- "Feature Request"
- "actions/autoclose-feat"
---
Requests is not accepting feature requests at this time.

93
.github/SECURITY.md vendored Normal file
View File

@@ -0,0 +1,93 @@
# Vulnerability Disclosure
If you think you have found a potential security vulnerability in
requests, please email [Nate](mailto:nate.prewitt@gmail.com)
and [Seth](mailto:sethmichaellarson@gmail.com) directly.
**Do not file a public issue.**
Our PGP Key fingerprints are:
- 8722 7E29 AD9C FF5C FAC3 EA6A 44D3 FF97 B80D C864 ([@nateprewitt](https://keybase.io/nateprewitt))
- EDD5 6765 A9D8 4653 CBC8 A134 51B0 6736 1740 F5FC ([@sethmlarson](https://keybase.io/sethmlarson))
You can also contact us on [Keybase](https://keybase.io) with the
profiles above if desired.
If English is not your first language, please try to describe the
problem and its impact to the best of your ability. For greater detail,
please use your native language and we will try our best to translate it
using online services.
Please also include the code you used to find the problem and the
shortest amount of code necessary to reproduce it.
Please do not disclose this to anyone else. We will retrieve a CVE
identifier if necessary and give you full credit under whatever name or
alias you provide. We will only request an identifier when we have a fix
and can publish it in a release.
We will respect your privacy and will only publicize your involvement if
you grant us permission.
## Process
This following information discusses the process the requests project
follows in response to vulnerability disclosures. If you are disclosing
a vulnerability, this section of the documentation lets you know how we
will respond to your disclosure.
### Timeline
When you report an issue, one of the project members will respond to you
within two days *at the outside*. In most cases responses will be
faster, usually within 12 hours. This initial response will at the very
least confirm receipt of the report.
If we were able to rapidly reproduce the issue, the initial response
will also contain confirmation of the issue. If we are not, we will
often ask for more information about the reproduction scenario.
Our goal is to have a fix for any vulnerability released within two
weeks of the initial disclosure. This may potentially involve shipping
an interim release that simply disables function while a more mature fix
can be prepared, but will in the vast majority of cases mean shipping a
complete release as soon as possible.
Throughout the fix process we will keep you up to speed with how the fix
is progressing. Once the fix is prepared, we will notify you that we
believe we have a fix. Often we will ask you to confirm the fix resolves
the problem in your environment, especially if we are not confident of
our reproduction scenario.
At this point, we will prepare for the release. We will obtain a CVE
number if one is required, providing you with full credit for the
discovery. We will also decide on a planned release date, and let you
know when it is. This release date will *always* be on a weekday.
At this point we will reach out to our major downstream packagers to
notify them of an impending security-related patch so they can make
arrangements. In addition, these packagers will be provided with the
intended patch ahead of time, to ensure that they are able to promptly
release their downstream packages. Currently the list of people we
actively contact *ahead of a public release* is:
- Jeremy Cline, Red Hat (@jeremycline)
- Daniele Tricoli, Debian (@eriol)
We will notify these individuals at least a week ahead of our planned
release date to ensure that they have sufficient time to prepare. If you
believe you should be on this list, please let one of the maintainers
know at one of the email addresses at the top of this article.
On release day, we will push the patch to our public repository, along
with an updated changelog that describes the issue and credits you. We
will then issue a PyPI release containing the patch.
At this point, we will publicise the release. This will involve mails to
mailing lists, Tweets, and all other communication mechanisms available
to the core team.
We will also explicitly mention which commits contain the fix to make it
easier for other distributors and users to easily patch their own
versions of requests if upgrading is not an option.

11
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
ignore:
# Ignore all patch releases as we can manually
# upgrade if we run into a bug and need a fix.
- dependency-name: "*"
update-types: ["version-update:semver-patch"]

35
.github/workflows/close-issues.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: 'Autoclose Issues'
on:
issues:
types:
- labeled
permissions:
issues: write
jobs:
close_qa:
if: github.event.label.name == 'actions/autoclose-qa'
runs-on: ubuntu-latest
steps:
- env:
ISSUE_URL: ${{ github.event.issue.html_url }}
GH_TOKEN: ${{ github.token }}
run: |
gh issue close $ISSUE_URL \
--comment "As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)" \
--reason completed
gh issue lock $ISSUE_URL --reason off_topic
close_feature_request:
if: github.event.label.name == 'actions/autoclose-feat'
runs-on: ubuntu-latest
steps:
- env:
ISSUE_URL: ${{ github.event.issue.html_url }}
GH_TOKEN: ${{ github.token }}
run: |
gh issue close $ISSUE_URL \
--comment "As described in the template, Requests is not accepting feature requests" \
--reason "not planned"
gh issue lock $ISSUE_URL --reason off_topic

73
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@@ -0,0 +1,73 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
name: "CodeQL"
on:
push:
branches: [main]
pull_request:
# The branches below must be a subset of the branches above
branches: [main]
schedule:
- cron: '0 23 * * 0'
permissions:
contents: read
jobs:
analyze:
permissions:
actions: read # for github/codeql-action/init to get workflow details
contents: read # for actions/checkout to fetch code
security-events: write # for github/codeql-action/autobuild to send a status report
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Checkout repository
uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0
with:
languages: "python"
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0

20
.github/workflows/lint.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: Lint code
on: [push, pull_request]
permissions:
contents: read
jobs:
lint:
runs-on: ubuntu-20.04
timeout-minutes: 10
steps:
- uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0
- name: Set up Python
uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
with:
python-version: "3.x"
- name: Run pre-commit
uses: pre-commit/action@646c83fcd040023954eafda54b4db0192ce70507 # v3.0.0

19
.github/workflows/lock-issues.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: 'Lock Threads'
on:
schedule:
- cron: '0 0 * * *'
permissions:
issues: write
pull-requests: write
jobs:
action:
if: github.repository_owner == 'psf'
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@d42e5f49803f3c4e14ffee0378e31481265dda22 # v5.0.0
with:
issue-lock-inactive-days: 90
pr-lock-inactive-days: 90

59
.github/workflows/run-tests.yml vendored Normal file
View File

@@ -0,0 +1,59 @@
name: Tests
on: [push, pull_request]
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "pypy-3.9", "pypy-3.10"]
os: [ubuntu-22.04, macOS-latest, windows-latest]
# Python 3.8 and 3.9 do not run on macOS-latest which
# is now using arm64 hardware.
# https://github.com/actions/setup-python/issues/696#issuecomment-1637587760
exclude:
- { python-version: "3.8", os: "macos-latest" }
- { python-version: "3.9", os: "macos-latest" }
include:
- { python-version: "3.8", os: "macos-13" }
- { python-version: "3.9", os: "macos-13" }
steps:
- uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
- name: Install dependencies
run: |
make
- name: Run tests
run: |
make ci
no_chardet:
name: "No Character Detection"
runs-on: ubuntu-latest
strategy:
fail-fast: true
steps:
- uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
- name: 'Set up Python 3.8'
uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d
with:
python-version: '3.8'
- name: Install dependencies
run: |
make
python -m pip uninstall -y "charset_normalizer" "chardet"
- name: Run tests
run: |
make ci

14
.gitignore vendored
View File

@@ -14,10 +14,24 @@ requests.egg-info/
*.swp
*.egg
env/
.venv/
.eggs/
.tox/
.pytest_cache/
.vscode/
.eggs/
.workon
# in case you work with IntelliJ/PyCharm
.idea
*.iml
.python-version
t.py
t2.py
dist
/.mypy_cache/

28
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,28 @@
exclude: 'docs/|ext/'
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
exclude: tests/test_lowlevel.py
- repo: https://github.com/asottile/pyupgrade
rev: v3.10.1
hooks:
- id: pyupgrade
args: [--py37-plus]
- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8

29
.readthedocs.yaml Normal file
View File

@@ -0,0 +1,29 @@
# Read the Docs configuration file for Sphinx projects
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the OS, Python version and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.12"
# Build documentation in the "docs/" directory with Sphinx
sphinx:
configuration: docs/conf.py
builder: "dirhtml"
# Optionally build your docs in additional formats such as PDF and ePub
formats:
- pdf
- epub
# Optional but recommended, declare the Python requirements required
# to build your documentation
# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
python:
install:
- path: .
- requirements: docs/requirements.txt

View File

@@ -1,32 +0,0 @@
sudo: false
language: python
python:
- "2.6"
- "2.7"
- "3.3"
- "3.4"
- "3.5"
- "3.6"
# - "3.7-dev"
# - "pypy" -- appears to hang
# - "pypy3"
# command to install dependencies
install: "make"
# command to run tests
script:
- |
if [[ "$TRAVIS_PYTHON_VERSION" != "2.6" ]] ; then make test-readme; fi
- make ci
cache: pip
jobs:
include:
- stage: test
script:
- |
if [[ "$TRAVIS_PYTHON_VERSION" != "2.6" ]] ; then make test-readme; fi
- make ci
- stage: coverage
python: 3.6
script: codecov

View File

@@ -1,20 +1,16 @@
Requests is written and maintained by Kenneth Reitz and
various contributors:
Requests was lovingly created by Kenneth Reitz.
Keepers of the Four Crystals
Keepers of the Crystals
```````````````````````
- Nate Prewitt `@nateprewitt <https://github.com/nateprewitt>`_.
- Seth M. Larson `@sethmlarson <https://github.com/sethmlarson>`_.
Previous Keepers of Crystals
````````````````````````````
- Kenneth Reitz <me@kennethreitz.org> `@kennethreitz <https://github.com/kennethreitz>`_, Keeper of the Master Crystal.
- Kenneth Reitz <me@kennethreitz.org> `@kennethreitz <https://github.com/kennethreitz>`_, reluctant Keeper of the Master Crystal.
- Cory Benfield <cory@lukasa.co.uk> `@lukasa <https://github.com/lukasa>`_
- Ian Cordasco <graffatcolmingov@gmail.com> `@sigmavirus24 <https://github.com/sigmavirus24>`_
- Nate Prewitt <nate.prewitt@gmail.com> `@nateprewitt <https://github.com/nateprewitt>`_
Urllib3
```````
- Andrey Petrov <andrey.petrov@shazow.net>
- Ian Cordasco <graffatcolmingov@gmail.com> `@sigmavirus24 <https://github.com/sigmavirus24>`_.
Patches and Suggestions
@@ -128,7 +124,7 @@ Patches and Suggestions
- Bryce Boe <bbzbryce@gmail.com> (`@bboe <https://github.com/bboe>`_)
- Colin Dunklau <colin.dunklau@gmail.com> (`@cdunklau <https://github.com/cdunklau>`_)
- Bob Carroll <bob.carroll@alum.rit.edu> (`@rcarz <https://github.com/rcarz>`_)
- Hugo Osvaldo Barrera <hugo@osvaldobarrera.com.ar> (`@hobarrera <https://github.com/hobarrera>`_)
- Hugo Osvaldo Barrera <hugo@barrera.io> (`@hobarrera <https://github.com/hobarrera>`_)
- Łukasz Langa <lukasz@langa.pl>
- Dave Shawley <daveshawley@gmail.com>
- James Clarke (`@jam <https://github.com/jam>`_)
@@ -185,3 +181,15 @@ Patches and Suggestions
- Ryan Pineo (`@ryanpineo <https://github.com/ryanpineo>`_)
- Ed Morley (`@edmorley <https://github.com/edmorley>`_)
- Matt Liu <liumatt@gmail.com> (`@mlcrazy <https://github.com/mlcrazy>`_)
- Taylor Hoff <primdevs@protonmail.com> (`@PrimordialHelios <https://github.com/PrimordialHelios>`_)
- Arthur Vigil (`@ahvigil <https://github.com/ahvigil>`_)
- Nehal J Wani (`@nehaljwani <https://github.com/nehaljwani>`_)
- Demetrios Bairaktaris (`@DemetriosBairaktaris <https://github.com/demetriosbairaktaris>`_)
- Darren Dormer (`@ddormer <https://github.com/ddormer>`_)
- Rajiv Mayani (`@mayani <https://github.com/mayani>`_)
- Antti Kaihola (`@akaihola <https://github.com/akaihola>`_)
- "Dull Bananas" <dull.bananas0@gmail.com> (`@dullbananas <https://github.com/dullbananas>`_)
- Alessio Izzo (`@aless10 <https://github.com/aless10>`_)
- Sylvain Marié (`@smarie <https://github.com/smarie>`_)
- Hod Bin Noon (`@hodbn <https://github.com/hodbn>`_)
- Mike Fiedler (`@miketheman <https://github.com/miketheman>`_)

View File

@@ -1,3 +0,0 @@
Be cordial or be on your way.
https://www.kennethreitz.org/essays/be-cordial-or-be-on-your-way

1959
HISTORY.md Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

182
LICENSE
View File

@@ -1,13 +1,175 @@
Copyright 2017 Kenneth Reitz
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
http://www.apache.org/licenses/LICENSE-2.0
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

View File

@@ -1,2 +1,3 @@
include README.rst LICENSE NOTICE HISTORY.rst pytest.ini
include README.md LICENSE NOTICE HISTORY.md requirements-dev.txt
recursive-include tests *.py
recursive-include tests/certs *

View File

@@ -1,27 +1,27 @@
.PHONY: docs
init:
pip install -r requirements.txt
python -m pip install -r requirements-dev.txt
test:
# This runs all of the tests, on both Python 2 and Python 3.
detox
# This runs all of the tests on all supported Python versions.
tox -p
ci:
py.test -n 8 --boxed --junitxml=report.xml
python -m pytest tests --junitxml=report.xml
test-readme:
@python setup.py check --restructuredtext --strict && ([ $$? -eq 0 ] && echo "README.rst and HISTORY.rst ok") || echo "Invalid markup in README.rst or HISTORY.rst!"
python setup.py check --restructuredtext --strict && ([ $$? -eq 0 ] && echo "README.rst and HISTORY.rst ok") || echo "Invalid markup in README.rst or HISTORY.rst!"
flake8:
flake8 --ignore=E501,F401,E128,E402,E731,F821 requests
python -m flake8 src/requests
coverage:
py.test --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=requests tests
python -m pytest --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=src/requests tests
publish:
pip install 'twine>=1.5.0'
python -m pip install 'twine>=1.5.0'
python setup.py sdist bdist_wheel
twine upload dist/*
rm -fr build dist .egg requests.egg-info
docs:
cd docs && make html
@echo "\033[95m\n\nBuild successful! View the docs homepage at docs/_build/html/index.html.\n\033[0m"
@echo "\033[95m\n\nBuild successful! View the docs homepage at docs/_build/html/index.html.\n\033[0m"

2
NOTICE Normal file
View File

@@ -0,0 +1,2 @@
Requests
Copyright 2019 Kenneth Reitz

78
README.md Normal file
View File

@@ -0,0 +1,78 @@
# Requests
**Requests** is a simple, yet elegant, HTTP library.
```python
>>> import requests
>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
'{"authenticated": true, ...'
>>> r.json()
{'authenticated': True, ...}
```
Requests allows you to send HTTP/1.1 requests extremely easily. Theres no need to manually add query strings to your URLs, or to form-encode your `PUT` & `POST` data — but nowadays, just use the `json` method!
Requests is one of the most downloaded Python packages today, pulling in around `30M downloads / week`— according to GitHub, Requests is currently [depended upon](https://github.com/psf/requests/network/dependents?package_id=UGFja2FnZS01NzA4OTExNg%3D%3D) by `1,000,000+` repositories. You may certainly put your trust in this code.
[![Downloads](https://static.pepy.tech/badge/requests/month)](https://pepy.tech/project/requests)
[![Supported Versions](https://img.shields.io/pypi/pyversions/requests.svg)](https://pypi.org/project/requests)
[![Contributors](https://img.shields.io/github/contributors/psf/requests.svg)](https://github.com/psf/requests/graphs/contributors)
## Installing Requests and Supported Versions
Requests is available on PyPI:
```console
$ python -m pip install requests
```
Requests officially supports Python 3.8+.
## Supported Features & BestPractices
Requests is ready for the demands of building robust and reliable HTTPspeaking applications, for the needs of today.
- Keep-Alive & Connection Pooling
- International Domains and URLs
- Sessions with Cookie Persistence
- Browser-style TLS/SSL Verification
- Basic & Digest Authentication
- Familiar `dict`like Cookies
- Automatic Content Decompression and Decoding
- Multi-part File Uploads
- SOCKS Proxy Support
- Connection Timeouts
- Streaming Downloads
- Automatic honoring of `.netrc`
- Chunked HTTP Requests
## API Reference and User Guide available on [Read the Docs](https://requests.readthedocs.io)
[![Read the Docs](https://raw.githubusercontent.com/psf/requests/main/ext/ss.png)](https://requests.readthedocs.io)
## Cloning the repository
When cloning the Requests repository, you may need to add the `-c
fetch.fsck.badTimezone=ignore` flag to avoid an error about a bad commit (see
[this issue](https://github.com/psf/requests/issues/2690) for more background):
```shell
git clone -c fetch.fsck.badTimezone=ignore https://github.com/psf/requests.git
```
You can also apply this setting to your global Git config:
```shell
git config --global fetch.fsck.badTimezone ignore
```
---
[![Kenneth Reitz](https://raw.githubusercontent.com/psf/requests/main/ext/kr.png)](https://kennethreitz.org) [![Python Software Foundation](https://raw.githubusercontent.com/psf/requests/main/ext/psf.png)](https://www.python.org/psf)

View File

@@ -1,114 +0,0 @@
Requests: HTTP for Humans
=========================
.. image:: https://img.shields.io/pypi/v/requests.svg
:target: https://pypi.python.org/pypi/requests
.. image:: https://img.shields.io/pypi/l/requests.svg
:target: https://pypi.python.org/pypi/requests
.. image:: https://img.shields.io/pypi/pyversions/requests.svg
:target: https://pypi.python.org/pypi/requests
.. image:: https://codecov.io/github/requests/requests/coverage.svg?branch=master
:target: https://codecov.io/github/requests/requests
:alt: codecov.io
.. image:: https://img.shields.io/github/contributors/requests/requests.svg
:target: https://github.com/requests/requests/graphs/contributors
.. image:: https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg
:target: https://saythanks.io/to/kennethreitz
Requests is the only *Non-GMO* HTTP library for Python, safe for human
consumption.
**Warning:** Recreational use of the Python standard library for HTTP may result in dangerous side-effects,
including: security vulnerabilities, verbose code, reinventing the wheel,
constantly reading documentation, depression, headaches, or even death.
Behold, the power of Requests:
.. code-block:: python
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'disk_usage': 368627, u'private_gists': 484, ...}
See `the similar code, sans Requests <https://gist.github.com/973705>`_.
.. image:: https://raw.githubusercontent.com/requests/requests/master/docs/_static/requests-logo-small.png
:target: http://docs.python-requests.org/
Requests allows you to send *organic, grass-fed* HTTP/1.1 requests, without the
need for manual labor. There's no need to manually add query strings to your
URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling
are 100% automatic, thanks to `urllib3 <https://github.com/shazow/urllib3>`_.
Besides, all the cool kids are doing it. Requests is one of the most
downloaded Python packages of all time, pulling in over 11,000,000 downloads
every month. You don't want to be left out!
Feature Support
---------------
Requests is ready for today's web.
- International Domains and URLs
- Keep-Alive & Connection Pooling
- Sessions with Cookie Persistence
- Browser-style SSL Verification
- Basic/Digest Authentication
- Elegant Key/Value Cookies
- Automatic Decompression
- Automatic Content Decoding
- Unicode Response Bodies
- Multipart File Uploads
- HTTP(S) Proxy Support
- Connection Timeouts
- Streaming Downloads
- ``.netrc`` Support
- Chunked Requests
Requests officially supports Python 2.62.7 & 3.33.7, and runs great on PyPy.
Installation
------------
To install Requests, simply:
.. code-block:: bash
$ pip install requests
✨🍰✨
Satisfaction, guaranteed.
Documentation
-------------
Fantastic documentation is available at http://docs.python-requests.org/, for a limited time only.
How to Contribute
-----------------
#. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug. There is a `Contributor Friendly`_ tag for issues that should be ideal for people who are not very familiar with the codebase yet.
#. Fork `the repository`_ on GitHub to start making your changes to the **master** branch (or branch off of it).
#. Write a test which shows that the bug was fixed or that the feature works as expected.
#. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to AUTHORS_.
.. _`the repository`: http://github.com/requests/requests
.. _AUTHORS: https://github.com/requests/requests/blob/master/AUTHORS.rst
.. _Contributor Friendly: https://github.com/requests/requests/issues?direction=desc&labels=Contributor+Friendly&page=1&sort=updated&state=open

View File

@@ -1,229 +0,0 @@
# Sample script to install Python and pip under Windows
# Authors: Olivier Grisel, Jonathan Helmus, Kyle Kastner, and Alex Willmer
# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
$MINICONDA_URL = "http://repo.continuum.io/miniconda/"
$BASE_URL = "https://www.python.org/ftp/python/"
$GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
$GET_PIP_PATH = "C:\get-pip.py"
$PYTHON_PRERELEASE_REGEX = @"
(?x)
(?<major>\d+)
\.
(?<minor>\d+)
\.
(?<micro>\d+)
(?<prerelease>[a-z]{1,2}\d+)
"@
function Download ($filename, $url) {
$webclient = New-Object System.Net.WebClient
$basedir = $pwd.Path + "\"
$filepath = $basedir + $filename
if (Test-Path $filename) {
Write-Host "Reusing" $filepath
return $filepath
}
# Download and retry up to 3 times in case of network transient errors.
Write-Host "Downloading" $filename "from" $url
$retry_attempts = 2
for ($i = 0; $i -lt $retry_attempts; $i++) {
try {
$webclient.DownloadFile($url, $filepath)
break
}
Catch [Exception]{
Start-Sleep 1
}
}
if (Test-Path $filepath) {
Write-Host "File saved at" $filepath
} else {
# Retry once to get the error message if any at the last try
$webclient.DownloadFile($url, $filepath)
}
return $filepath
}
function ParsePythonVersion ($python_version) {
if ($python_version -match $PYTHON_PRERELEASE_REGEX) {
return ([int]$matches.major, [int]$matches.minor, [int]$matches.micro,
$matches.prerelease)
}
$version_obj = [version]$python_version
return ($version_obj.major, $version_obj.minor, $version_obj.build, "")
}
function DownloadPython ($python_version, $platform_suffix) {
$major, $minor, $micro, $prerelease = ParsePythonVersion $python_version
if (($major -le 2 -and $micro -eq 0) `
-or ($major -eq 3 -and $minor -le 2 -and $micro -eq 0) `
) {
$dir = "$major.$minor"
$python_version = "$major.$minor$prerelease"
} else {
$dir = "$major.$minor.$micro"
}
if ($prerelease) {
if (($major -le 2) `
-or ($major -eq 3 -and $minor -eq 1) `
-or ($major -eq 3 -and $minor -eq 2) `
-or ($major -eq 3 -and $minor -eq 3) `
) {
$dir = "$dir/prev"
}
}
if (($major -le 2) -or ($major -le 3 -and $minor -le 4)) {
$ext = "msi"
if ($platform_suffix) {
$platform_suffix = ".$platform_suffix"
}
} else {
$ext = "exe"
if ($platform_suffix) {
$platform_suffix = "-$platform_suffix"
}
}
$filename = "python-$python_version$platform_suffix.$ext"
$url = "$BASE_URL$dir/$filename"
$filepath = Download $filename $url
return $filepath
}
function InstallPython ($python_version, $architecture, $python_home) {
Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home
if (Test-Path $python_home) {
Write-Host $python_home "already exists, skipping."
return $false
}
if ($architecture -eq "32") {
$platform_suffix = ""
} else {
$platform_suffix = "amd64"
}
$installer_path = DownloadPython $python_version $platform_suffix
$installer_ext = [System.IO.Path]::GetExtension($installer_path)
Write-Host "Installing $installer_path to $python_home"
$install_log = $python_home + ".log"
if ($installer_ext -eq '.msi') {
InstallPythonMSI $installer_path $python_home $install_log
} else {
InstallPythonEXE $installer_path $python_home $install_log
}
if (Test-Path $python_home) {
Write-Host "Python $python_version ($architecture) installation complete"
} else {
Write-Host "Failed to install Python in $python_home"
Get-Content -Path $install_log
Exit 1
}
}
function InstallPythonEXE ($exepath, $python_home, $install_log) {
$install_args = "/quiet InstallAllUsers=1 TargetDir=$python_home"
RunCommand $exepath $install_args
}
function InstallPythonMSI ($msipath, $python_home, $install_log) {
$install_args = "/qn /log $install_log /i $msipath TARGETDIR=$python_home"
$uninstall_args = "/qn /x $msipath"
RunCommand "msiexec.exe" $install_args
if (-not(Test-Path $python_home)) {
Write-Host "Python seems to be installed else-where, reinstalling."
RunCommand "msiexec.exe" $uninstall_args
RunCommand "msiexec.exe" $install_args
}
}
function RunCommand ($command, $command_args) {
Write-Host $command $command_args
Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru
}
function InstallPip ($python_home) {
$pip_path = $python_home + "\Scripts\pip.exe"
$python_path = $python_home + "\python.exe"
if (-not(Test-Path $pip_path)) {
Write-Host "Installing pip..."
$webclient = New-Object System.Net.WebClient
$webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH)
Write-Host "Executing:" $python_path $GET_PIP_PATH
& $python_path $GET_PIP_PATH
} else {
Write-Host "pip already installed."
}
}
function DownloadMiniconda ($python_version, $platform_suffix) {
if ($python_version -eq "3.4") {
$filename = "Miniconda3-3.5.5-Windows-" + $platform_suffix + ".exe"
} else {
$filename = "Miniconda-3.5.5-Windows-" + $platform_suffix + ".exe"
}
$url = $MINICONDA_URL + $filename
$filepath = Download $filename $url
return $filepath
}
function InstallMiniconda ($python_version, $architecture, $python_home) {
Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home
if (Test-Path $python_home) {
Write-Host $python_home "already exists, skipping."
return $false
}
if ($architecture -eq "32") {
$platform_suffix = "x86"
} else {
$platform_suffix = "x86_64"
}
$filepath = DownloadMiniconda $python_version $platform_suffix
Write-Host "Installing" $filepath "to" $python_home
$install_log = $python_home + ".log"
$args = "/S /D=$python_home"
Write-Host $filepath $args
Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru
if (Test-Path $python_home) {
Write-Host "Python $python_version ($architecture) installation complete"
} else {
Write-Host "Failed to install Python in $python_home"
Get-Content -Path $install_log
Exit 1
}
}
function InstallMinicondaPip ($python_home) {
$pip_path = $python_home + "\Scripts\pip.exe"
$conda_path = $python_home + "\Scripts\conda.exe"
if (-not(Test-Path $pip_path)) {
Write-Host "Installing pip..."
$args = "install --yes pip"
Write-Host $conda_path $args
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru
} else {
Write-Host "pip already installed."
}
}
function main () {
InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON
InstallPip $env:PYTHON
}
main

View File

@@ -1,56 +0,0 @@
# AppVeyor.yml from https://github.com/ogrisel/python-appveyor-demo
# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
build: off
environment:
matrix:
- PYTHON: "C:\\Python27-x64"
PYTHON_VERSION: "2.7.x"
PYTHON_ARCH: "64"
TOXENV: "py27"
- PYTHON: "C:\\Python33-x64"
PYTHON_VERSION: "3.3.x"
PYTHON_ARCH: "64"
TOXENV: "py33"
- PYTHON: "C:\\Python34-x64"
PYTHON_VERSION: "3.4.x"
PYTHON_ARCH: "64"
TOXENV: "py34"
- PYTHON: "C:\\Python35-x64"
PYTHON_VERSION: "3.5.x"
PYTHON_ARCH: "64"
TOXENV: "py35"
- PYTHON: "C:\\Python36-x64"
PYTHON_VERSION: "3.6.x"
PYTHON_ARCH: "64"
TOXENV: "py36"
install:
# Install Python (from the official .msi of http://python.org) and pip when
# not already installed.
- ps: if (-not(Test-Path($env:PYTHON))) { & _appveyor\install.ps1 }
# Prepend newly installed Python to the PATH of this build (this cannot be
# done from inside the powershell script as it would require to restart
# the parent CMD process).
- "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
# Check that we have the expected version and architecture for Python
- "python --version"
- "python -c \"import struct; print(struct.calcsize('P') * 8)\""
# Upgrade to the latest version of pip to avoid it displaying warnings
# about it being out of date.
- "pip install --disable-pip-version-check --user --upgrade pip"
- "C:\\MinGW\\bin\\mingw32-make"
test_script:
- "C:\\MinGW\\bin\\mingw32-make coverage"
on_success:
- "codecov -f coverage.xml"

1
docs/.nojekyll Normal file
View File

@@ -0,0 +1 @@

View File

@@ -1,12 +1,21 @@
body > div.document > div.sphinxsidebar > div > form > table > tbody > tr:nth-child(2) > td > select {
width: 100%!important;
}
#python27 > a {
color: white;
}
/* Carbon by BuySellAds */
#carbonads {
display: block;
overflow: hidden;
margin: 1.5em 0 2em;
padding: 1em;
border: solid 1px #cccccc;
border-radius: 2px;
background-color: #eeeeee;
text-align: center;
border: solid 1px #cccccc;
margin: 1.5em 0 2em;
border-radius: 2px;
line-height: 1.5;
}
@@ -34,6 +43,135 @@
display: block;
text-transform: uppercase;
letter-spacing: 1px;
font-size: 10px;
line-height: 1;
}
/* Native CPC by BuySellAds */
#native-ribbon #_custom_ {
position: fixed;
right: 0;
bottom: 0;
left: 0;
box-shadow: 0 -1px 4px 1px hsla(0, 0%, 0%, .15);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu,
Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif;
transition: all .25s ease-in-out;
transform: translateY(calc(100% - 35px));
flex-flow: column nowrap;
}
#native-ribbon #_custom_:hover {
transform: translateY(0);
}
.native-img {
margin-right: 20px;
max-height: 50px;
border-radius: 3px;
}
.native-sponsor {
margin: 10px 20px;
text-align: center;
text-transform: uppercase;
letter-spacing: .5px;
font-size: 12px;
transition: all .3s ease-in-out;
transform-origin: left;
}
#native-ribbon #_custom_:hover .native-sponsor {
margin: 0 20px;
opacity: 0;
transform: scaleY(0);
}
.native-flex {
display: flex;
padding: 10px 20px 25px;
text-decoration: none;
flex-flow: row nowrap;
justify-content: center;
align-items: center;
}
.native-main {
display: flex;
flex-flow: row nowrap;
align-items: center;
}
.native-details {
display: flex;
margin-right: 30px;
flex-flow: column nowrap;
}
.native-company {
margin-bottom: 4px;
text-transform: uppercase;
letter-spacing: 2px;
font-size: 10px;
}
.native-desc {
letter-spacing: 1px;
font-weight: 300;
font-size: 14px;
line-height: 1.4;
}
.native-cta {
padding: 10px 14px;
border-radius: 3px;
box-shadow: 0 6px 13px 0 hsla(0, 0%, 0%, .15);
text-transform: uppercase;
white-space: nowrap;
letter-spacing: 1px;
font-weight: 400;
font-size: 12px;
transition: all .3s ease-in-out;
transform: translateY(-1px);
}
.native-cta:hover {
box-shadow: none;
transform: translateY(1px);
}
@media only screen and (min-width: 320px) and (max-width: 759px) {
.native-flex {
padding: 5px 5px 15px;
flex-direction: column;
flex-wrap: wrap;
}
.native-img {
margin: 0;
display: none;
}
.native-details {
margin: 0;
}
.native-main {
flex-direction: column;
text-align: left;
flex-wrap: wrap;
align-content: center;
}
.native-cta {
display: none;
}
}

116
docs/_static/konami.js vendored
View File

@@ -1,116 +0,0 @@
/*
* Konami-JS ~
* :: Now with support for touch events and multiple instances for
* :: those situations that call for multiple easter eggs!
* Code: http://konami-js.googlecode.com/
* Examples: http://www.snaptortoise.com/konami-js
* Copyright (c) 2009 George Mandis (georgemandis.com, snaptortoise.com)
* Version: 1.4.2 (9/2/2013)
* Licensed under the MIT License (http://opensource.org/licenses/MIT)
* Tested in: Safari 4+, Google Chrome 4+, Firefox 3+, IE7+, Mobile Safari 2.2.1 and Dolphin Browser
*/
var Konami = function (callback) {
var konami = {
addEvent: function (obj, type, fn, ref_obj) {
if (obj.addEventListener)
obj.addEventListener(type, fn, false);
else if (obj.attachEvent) {
// IE
obj["e" + type + fn] = fn;
obj[type + fn] = function () {
obj["e" + type + fn](window.event, ref_obj);
};
obj.attachEvent("on" + type, obj[type + fn]);
}
},
input: "",
pattern: "38384040373937396665",
load: function (link) {
this.addEvent(document, "keydown", function (e, ref_obj) {
if (ref_obj) konami = ref_obj; // IE
konami.input += e ? e.keyCode : event.keyCode;
if (konami.input.length > konami.pattern.length)
konami.input = konami.input.substr((konami.input.length - konami.pattern.length));
if (konami.input == konami.pattern) {
konami.code(link);
konami.input = "";
e.preventDefault();
return false;
}
}, this);
this.iphone.load(link);
},
code: function (link) {
window.location = link
},
iphone: {
start_x: 0,
start_y: 0,
stop_x: 0,
stop_y: 0,
tapTolerance: 8,
capture: false,
orig_keys: "",
keys: ["UP", "UP", "DOWN", "DOWN", "LEFT", "RIGHT", "LEFT", "RIGHT", "TAP", "TAP"],
code: function (link) {
konami.code(link);
},
touchCapture: function(evt) {
konami.iphone.start_x = evt.changedTouches[0].pageX;
konami.iphone.start_y = evt.changedTouches[0].pageY;
konami.iphone.capture = true;
},
load: function (link) {
this.orig_keys = this.keys;
konami.addEvent(document, "touchmove", function (e) {
if (e.touches.length == 1 && konami.iphone.capture == true) {
var touch = e.touches[0];
konami.iphone.stop_x = touch.pageX;
konami.iphone.stop_y = touch.pageY;
konami.iphone.check_direction();
}
});
konami.addEvent(document, "touchend", function (evt) {
konami.touchCapture(evt);
konami.iphone.check_direction(link);
}, false);
konami.addEvent(document, "touchstart", function (evt) {
konami.touchCapture(evt);
});
},
check_direction: function (link) {
var x_magnitude = Math.abs(this.start_x - this.stop_x);
var y_magnitude = Math.abs(this.start_y - this.stop_y);
var hasMoved = (x_magnitude > this.tapTolerance || y_magnitude > this.tapTolerance);
var result;
if (this.capture === true && hasMoved) {
this.capture = false;
var x = ((this.start_x - this.stop_x) < 0) ? "RIGHT" : "LEFT";
var y = ((this.start_y - this.stop_y) < 0) ? "DOWN" : "UP";
var result = (x_magnitude > y_magnitude) ? x : y;
}
else if (this.capture === false && !hasMoved) {
result = (this.tap == true) ? "TAP" : result;
result = "TAP";
}
if (result) {
if (result == this.keys[0]) this.keys = this.keys.slice(1, this.keys.length);
else this.keys = this.orig_keys;
}
if (this.keys.length == 0) {
this.keys = this.orig_keys;
this.code(link);
}
}
}
}
typeof callback === "string" && konami.load(callback);
if (typeof callback === "function") {
konami.code = callback;
konami.load();
}
return konami;
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 155 KiB

View File

@@ -23,32 +23,58 @@
/* Have code blocks escape the document right-margin. */
div.highlight pre {margin-right: -30px;}
}
</style>
<!-- Analytics tracking for Kenneth. -->
<script type="text/javascript">
var _gauges = _gauges || [];
(function() {
var t = document.createElement('script');
t.type = 'text/javascript';
t.async = true;
t.id = 'gauges-tracker';
t.setAttribute('data-site-id', '56ca7a57c88d9011080024dd');
t.setAttribute('data-track-path', 'https://track.gaug.es/track.gif');
t.src = 'https://d36ee2fcip1434.cloudfront.net/track.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(t, s);
})();
</script>
<!-- Native CPC by BuySellAds -->
<!-- There are no more hacks. -->
<!-- இڿڰۣ-ڰۣ— -->
<!-- Love, Kenneth Reitz -->
<script type="text/javascript" src="//m.servedby-buysellads.com/monetization.js"></script>
<div id="native-ribbon">
</div>
<script src="{{ pathto('_static/', 1) }}/konami.js"></script>
<script>
var easter_egg = new Konami('http://fortunes.herokuapp.com/random/raw');
</script>
_bsa.init('custom', 'CK7D62JU', 'placement:pythonrequestsorg',
{
target: '#native-ribbon',
template: `
<div class="native-sponsor">Sponsored by ##company## — Learn More</div>
<a href="##link##" class="native-flex">
<style>
#native-ribbon #_custom_ {
background: linear-gradient(-30deg, ##backgroundColor##E5, ##backgroundColor##E5 45%, ##backgroundColor## 45%) #fff;
}
<!-- That was not a hack. That was art. -->
.native-details,
.native-sponsor,
.native-bsa {
color: ##textColor## !important;
}
.native-details:hover {
color: ##textColorHover## !important;
}
.native-cta {
color: ##ctaTextColor##;
background-color: ##ctaBackgroundColor##;
}
.native-cta:hover {
color: ##ctaTextColorHover##;
background-color: ##ctaBackgroundColorHover##;
}
</style>
<div class="native-main">
<img class="native-img" src="##logo##">
<div class="native-details">
<span class="native-company">##title##</span>
<span class="native-desc">##description##</span>
</div>
</div>
<span class="native-cta">##callToAction##</span>
</a>
</div>
`
}
);
</script>

View File

@@ -1,11 +1,11 @@
<p class="logo">
<a href="{{ pathto(master_doc) }}">
<img class="logo" src="{{ pathto('_static/requests-sidebar.png', 1) }}" title="https://kennethreitz.org/tattoos"/>
<img class="logo" src="{{ pathto('_static/requests-sidebar.png', 1) }}" alt="Requests logo" />
</a>
</p>
<p>
<iframe src="http://ghbtns.com/github-btn.html?user=requests&repo=requests&type=watch&count=true&size=large"
<iframe src="https://ghbtns.com/github-btn.html?user=psf&repo=requests&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe>
</p>
@@ -14,61 +14,24 @@
human beings.
</p>
<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=pythonrequestsorg" id="_carbonads_js"></script>
<h3>Stay Informed</h3>
<p>Receive updates on new releases and upcoming projects.</p>
<p><iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20"></iframe></p>
<p><a href="https://twitter.com/kennethreitz" class="twitter-follow-button" data-show-count="false">Follow @kennethreitz</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script></p>
<p><a href="https://saythanks.io/to/kennethreitz">Say Thanks!</a></p>
<p><a href="http://tinyletter.com/kennethreitz">Join Mailing List</a>.</p>
<h3>Other Projects</h3>
<p>More <a href="http://kennethreitz.org/">Kenneth Reitz</a> projects:</p>
<ul>
<li><a href="http://edmsynths.com/">edmsynths.com</a></li>
<li><a href="http://pipenv.org/">pipenv</a></li>
<li><a href="http://pep8.org/">pep8.org</a></li>
<li><a href="http://httpbin.org/">httpbin.org</a></li>
<li><a href="http://python-guide.org">The Python Guide</a></li>
<li><a href="https://github.com/kennethreitz/maya">Maya: Datetimes for Humans</a></li>
<li><a href="https://github.com/kennethreitz/records">Records: SQL for Humans</a></li>
<li><a href="http://www.git-legit.org">Legit: Git for Humans</a></li>
<li><a href="http://docs.python-tablib.org/en/latest/">Tablib: Tabular Datasets</a></li>
</ul>
<h3>Useful Links</h3>
<ul>
<li><a href="http://docs.python-requests.org/en/latest/community/recommended/">Recommended Packages and Extensions</a></li>
<li><a href="{{ pathto('user/quickstart') }}">Quickstart</a></li>
<li><a href="{{ pathto('user/advanced') }}">Advanced Usage</a></li>
<li><a href="{{ pathto('api') }}">API Reference</a></li>
<li><a href="{{ pathto('community/updates') + '#release-history' }}">Release History</a></li>
<li><a href="{{ pathto('dev/contributing') }}">Contributors Guide</a></li>
<p></p>
<li><a href="http://github.com/requests/requests">Requests @ GitHub</a></li>
<li><a href="http://pypi.python.org/pypi/requests">Requests @ PyPI</a></li>
<li><a href="http://github.com/requests/requests/issues">Issue Tracker</a></li>
<li><a href="http://docs.python-requests.org/en/latest/community/updates/#software-updates">Release History</a></li>
</ul>
<h3>Translations</h3>
<ul>
<li><a href="http://docs.python-requests.org/">English</a></li>
<li><a href="http://fr.python-requests.org/">French</a></li>
<li><a href="http://de.python-requests.org/">German</a></li>
<li><a href="http://jp.python-requests.org/">Japanese</a></li>
<li><a href="http://cn.python-requests.org/">Chinese</a></li>
<li><a href="http://pt.python-requests.org/">Portuguese</a></li>
<li><a href="http://it.python-requests.org/">Italian</a></li>
<li><a href="http://es.python-requests.org/">Spanish</a></li>
<li><a href="{{ pathto('community/recommended') }}">Recommended Packages and Extensions</a></li>
<p></p>
<li><a href="https://github.com/psf/requests">Requests @ GitHub</a></li>
<li><a href="https://pypi.org/project/requests/">Requests @ PyPI</a></li>
<li><a href="https://github.com/psf/requests/issues">Issue Tracker</a></li>
</ul>
<div id="native-ribbon">
</div>

View File

@@ -1,11 +1,6 @@
<p class="logo">
<a href="{{ pathto(master_doc) }}">
<img class="logo" src="{{ pathto('_static/requests-sidebar.png', 1) }}" title="https://kennethreitz.org/tattoos"/>
</a>
</p>
<p>
<iframe src="http://ghbtns.com/github-btn.html?user=requests&repo=requests&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe>
<iframe src="https://ghbtns.com/github-btn.html?user=psf&repo=requests&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe>
</p>
<p>
@@ -14,49 +9,22 @@
development release.
</p>
<h3>Stay Informed</h3>
<p>Receive updates on new releases and upcoming projects.</p>
<p><a href="http://tinyletter.com/kennethreitz">Join Mailing List</a>.</p>
<hr/>
<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=pythonrequestsorg" id="_carbonads_js"></script>
<p>If you enjoy using this project, <a href="https://saythanks.io/to/kennethreitz">Say Thanks!</a></p>
<p><iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false"
allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20"></iframe></p>
<p><a href="https://twitter.com/kennethreitz" class="twitter-follow-button" data-show-count="false">Follow @kennethreitz</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script></p>
<h3>Other Projects</h3>
<p>More <a href="http://kennethreitz.org/">Kenneth Reitz</a> projects:</p>
<h3>Useful Links</h3>
<ul>
<li><a href="http://edmsynths.com/">edmsynths.com</a></li>
<li><a href="http://pipenv.org/">pipenv</a></li>
<li><a href="http://pep8.org/">pep8.org</a></li>
<li><a href="http://httpbin.org/">httpbin.org</a></li>
<li><a href="http://python-guide.org">The Python Guide</a></li>
<li><a href="https://github.com/kennethreitz/maya">Maya: Datetimes for Humans</a></li>
<li><a href="https://github.com/kennethreitz/records">Records: SQL for Humans</a></li>
<li><a href="http://www.git-legit.org">Legit: Git for Humans</a></li>
<li><a href="http://docs.python-tablib.org/en/latest/">Tablib: Tabular Datasets</a></li>
</ul>
<h3>Translations</h3>
<ul>
<li><a href="http://docs.python-requests.org/">English</a></li>
<li><a href="http://fr.python-requests.org/">French</a></li>
<li><a href="http://de.python-requests.org/">German</a></li>
<li><a href="http://jp.python-requests.org/">Japanese</a></li>
<li><a href="http://cn.python-requests.org/">Chinese</a></li>
<li><a href="http://pt.python-requests.org/">Portuguese</a></li>
<li><a href="http://it.python-requests.org/">Italian</a></li>
<li><a href="http://es.python-requests.org/">Spanish</a></li>
<li><a href="{{ pathto('user/quickstart') }}">Quickstart</a></li>
<li><a href="{{ pathto('user/advanced') }}">Advanced Usage</a></li>
<li><a href="{{ pathto('api') }}">API Reference</a></li>
<li><a href="{{ pathto('community/updates') + '#release-history' }}">Release History</a></li>
<li><a href="{{ pathto('dev/contributing') }}">Contributors Guide</a></li>
<p></p>
<li><a href="{{ pathto('community/recommended') }}">Recommended Packages and Extensions</a></li>
<p></p>
<li><a href="https://github.com/psf/requests">Requests @ GitHub</a></li>
<li><a href="https://pypi.org/project/requests/">Requests @ PyPI</a></li>
<li><a href="https://github.com/psf/requests/issues">Issue Tracker</a></li>
</ul>

View File

@@ -36,6 +36,7 @@ Exceptions
.. autoexception:: requests.ConnectTimeout
.. autoexception:: requests.ReadTimeout
.. autoexception:: requests.Timeout
.. autoexception:: requests.JSONDecodeError
Request Sessions
@@ -109,17 +110,7 @@ Status Code Lookup
.. autoclass:: requests.codes
::
>>> requests.codes['temporary_redirect']
307
>>> requests.codes.teapot
418
>>> requests.codes['\o/']
200
.. automodule:: requests.status_codes
Migrating to 1.x
@@ -137,7 +128,7 @@ API Changes
::
import requests
r = requests.get('https://github.com/timeline.json')
r = requests.get('https://api.github.com/events')
r.json() # This *call* raises an exception if JSON decoding fails
* The ``Session`` API has changed. Sessions objects no longer take parameters.
@@ -149,7 +140,7 @@ API Changes
s = requests.Session() # formerly, session took parameters
s.auth = auth
s.headers.update(headers)
r = s.get('http://httpbin.org/headers')
r = s.get('https://httpbin.org/headers')
* All request hooks have been removed except 'response'.
@@ -166,7 +157,7 @@ API Changes
::
# in 0.x, passing prefetch=False would accomplish the same thing
r = requests.get('https://github.com/timeline.json', stream=True)
r = requests.get('https://api.github.com/events', stream=True)
for chunk in r.iter_content(8192):
...
@@ -191,11 +182,11 @@ API Changes
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log = logging.getLogger("urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
requests.get('http://httpbin.org/headers')
requests.get('https://httpbin.org/headers')
@@ -207,8 +198,8 @@ license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0
license ensures that contributions to Requests are also covered by the Apache
2.0 license.
.. _ISC: http://opensource.org/licenses/ISC
.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0
.. _ISC: https://opensource.org/licenses/ISC
.. _Apache 2.0: https://opensource.org/licenses/Apache-2.0
Migrating to 2.x
@@ -223,7 +214,7 @@ For more details on the changes in this release including new APIs, links
to the relevant GitHub issues and some of the bug fixes, read Cory's blog_
on the subject.
.. _blog: http://lukasa.co.uk/2013/09/Requests_20/
.. _blog: https://lukasa.co.uk/2013/09/Requests_20/
API Changes

View File

@@ -11,6 +11,9 @@ Encoded Data?
Requests automatically decompresses gzip-encoded responses, and does
its best to decode response content to unicode when possible.
When either the `brotli <https://pypi.org/project/Brotli/>`_ or `brotlicffi <https://pypi.org/project/brotlicffi/>`_
package is installed, requests also decodes Brotli-encoded responses.
You can get direct access to the raw response (and even the socket),
if needed as well.
@@ -19,7 +22,8 @@ Custom User-Agents?
-------------------
Requests allows you to easily override User-Agent strings, along with
any other HTTP Header.
any other HTTP Header. See :ref:`documentation about headers <custom-headers>`.
Why not Httplib2?
@@ -51,16 +55,17 @@ Chris Adams gave an excellent summary on
Python 3 Support?
-----------------
Yes! Here's a list of Python platforms that are officially
supported:
Yes! Requests officially supports Python 3.8+ and PyPy.
* Python 2.6
* Python 2.7
* Python 3.3
* Python 3.4
* Python 3.5
* Python 3.6
* PyPy
Python 2 Support?
-----------------
No! As of Requests 2.28.0, Requests no longer supports Python 2.7. Users who
have been unable to migrate should pin to `requests<2.28`. Full information
can be found in `psf/requests#6023 <https://github.com/psf/requests/issues/6023>`_.
It is *highly* recommended users migrate to Python 3.8+ now since Python
2.7 is no longer receiving bug fixes or security updates as of January 1, 2020.
What are "hostname doesn't match" errors?
-----------------------------------------
@@ -69,7 +74,7 @@ These errors occur when :ref:`SSL certificate verification <verification>`
fails to match the certificate the server responds with to the hostname
Requests thinks it's contacting. If you're certain the server's SSL setup is
correct (for example, because you can visit the site with your browser) and
you're using Python 2.6 or 2.7, a possible explanation is that you need
you're using Python 2.7, a possible explanation is that you need
Server-Name-Indication.
`Server-Name-Indication`_, or SNI, is an official extension to SSL where the
@@ -78,10 +83,7 @@ when servers are using `Virtual Hosting`_. When such servers are hosting
more than one SSL site they need to be able to return the appropriate
certificate based on the hostname the client is connecting to.
Python3 and Python 2.7.9+ include native support for SNI in their SSL modules.
For information on using SNI with Requests on Python < 2.7.9 refer to this
`Stack Overflow answer`_.
Python 3 already includes native support for SNI in their SSL modules.
.. _`Server-Name-Indication`: https://en.wikipedia.org/wiki/Server_Name_Indication
.. _`virtual hosting`: https://en.wikipedia.org/wiki/Virtual_hosting
.. _`Stack Overflow answer`: https://stackoverflow.com/questions/18578439/using-requests-with-tls-doesnt-give-sni-support/18579484#18579484

View File

@@ -1,22 +1,10 @@
Integrations
============
Python for iOS
--------------
Requests is built into the wonderful `Python for iOS <https://itunes.apple.com/us/app/python-2.7-for-ios/id485729872?mt=Python8>`_ runtime!
To give it a try, simply::
import requests
Articles & Talks
================
- `Python for the Web <http://gun.io/blog/python-for-the-web/>`_ teaches how to use Python to interact with the web, using Requests.
- `Daniel Greenfeld's Review of Requests <http://pydanny.blogspot.com/2011/05/python-http-requests-for-humans.html>`_
- `My 'Python for Humans' talk <http://python-for-humans.heroku.com>`_ ( `audio <http://codeconf.s3.amazonaws.com/2011/pycodeconf/talks/PyCodeConf2011%20-%20Kenneth%20Reitz.m4a>`_ )
- `Issac Kelly's 'Consuming Web APIs' talk <http://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_
- `Blog post about Requests via Yum <http://arunsag.wordpress.com/2011/08/17/new-package-python-requests-http-for-humans/>`_
- `Russian blog post introducing Requests <http://habrahabr.ru/blogs/python/126262/>`_
- `Daniel Greenfeld's Review of Requests <https://pydanny.blogspot.com/2011/05/python-http-requests-for-humans.html>`_
- `Issac Kelly's 'Consuming Web APIs' talk <https://issackelly.github.io/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_
- `Blog post about Requests via Yum <https://arunsag.wordpress.com/2011/08/17/new-package-python-requests-http-for-humans/>`_
- `Russian blog post introducing Requests <https://habr.com/post/126262/>`_
- `Sending JSON in Requests <http://www.coglib.com/~icordasc/blog/2014/11/sending-json-in-requests.html>`_

View File

@@ -13,7 +13,7 @@ Certifi CA Bundle
validating the trustworthiness of SSL certificates while verifying the
identity of TLS hosts. It has been extracted from the Requests project.
.. _Certifi: http://certifi.io/en/latest/
.. _Certifi: https://github.com/certifi/python-certifi
CacheControl
------------
@@ -32,7 +32,15 @@ but do not belong in Requests proper. This library is actively maintained
by members of the Requests core team, and reflects the functionality most
requested by users within the community.
.. _Requests-Toolbelt: http://toolbelt.readthedocs.io/en/latest/index.html
.. _Requests-Toolbelt: https://toolbelt.readthedocs.io/en/latest/index.html
Requests-Threads
----------------
`Requests-Threads`_ is a Requests session that returns the amazing Twisted's awaitable Deferreds instead of Response objects. This allows the use of ``async``/``await`` keyword usage on Python 3, or Twisted's style of programming, if desired.
.. _Requests-Threads: https://github.com/requests/requests-threads
Requests-OAuthlib
-----------------
@@ -51,7 +59,4 @@ Betamax
`Betamax`_ records your HTTP interactions so the NSA does not have to.
A VCR imitation designed only for Python-Requests.
.. _betamax: https://github.com/sigmavirus24/betamax
.. _betamax: https://github.com/betamaxpy/betamax

View File

@@ -17,19 +17,18 @@ Breaking changes are changes that break backwards compatibility with prior
versions. If the project were to change the ``text`` attribute on a
``Response`` object to a method, that would only happen in a Major release.
Major releases may also include miscellaneous bug fixes and upgrades to
vendored packages. The core developers of Requests are committed to providing
a good user experience. This means we're also committed to preserving
backwards compatibility as much as possible. Major releases will be infrequent
and will need strong justifications before they are considered.
Major releases may also include miscellaneous bug fixes. The core developers of
Requests are committed to providing a good user experience. This means we're
also committed to preserving backwards compatibility as much as possible. Major
releases will be infrequent and will need strong justifications before they are
considered.
Minor Releases
--------------
A minor release will not include breaking changes but may include
miscellaneous bug fixes and upgrades to vendored packages. If the previous
version of Requests released was ``v10.2.7`` a minor release would be
versioned as ``v10.3.0``.
A minor release will not include breaking changes but may include miscellaneous
bug fixes. If the previous version of Requests released was ``v10.2.7`` a minor
release would be versioned as ``v10.3.0``.
Minor releases will be backwards compatible with releases that have the same
major version number. In other words, all versions that would start with

View File

@@ -5,47 +5,27 @@ Support
If you have questions or issues about Requests, there are several options:
StackOverflow
-------------
Stack Overflow
--------------
If your question does not contain sensitive (possibly proprietary)
information or can be properly anonymized, please ask a question on
`StackOverflow <https://stackoverflow.com/questions/tagged/python-requests>`_
`Stack Overflow <https://stackoverflow.com/questions/tagged/python-requests>`_
and use the tag ``python-requests``.
Send a Tweet
------------
If your question is less than 140 characters, feel free to send a tweet to
`@kennethreitz <https://twitter.com/kennethreitz>`_,
`@sigmavirus24 <https://twitter.com/sigmavirus24>`_, or
`@lukasaoz <https://twitter.com/lukasaoz>`_.
File an Issue
-------------
If you notice some unexpected behaviour in Requests, or want to see support
for a new feature,
`file an issue on GitHub <https://github.com/requests/requests/issues>`_.
`file an issue on GitHub <https://github.com/psf/requests/issues>`_.
E-mail
------
Send a Tweet
------------
I'm more than happy to answer any personal or in-depth questions about
Requests. Feel free to email
`requests@kennethreitz.com <mailto:requests@kennethreitz.com>`_.
IRC
---
The official Freenode channel for Requests is
`#python-requests <irc://irc.freenode.net/python-requests>`_
The core developers of requests are on IRC throughout the day.
You can find them in ``#python-requests`` as:
- kennethreitz
- lukasa
- sigmavirus24
If your question is less than 280 characters, feel free to send a tweet to
`@nateprewitt <https://twitter.com/nateprewitt>`_,
`@sethmlarson <https://twitter.com/sethmlarson>`_, or
`@sigmavirus24 <https://twitter.com/sigmavirus24>`_.

View File

@@ -12,19 +12,7 @@ GitHub
------
The best way to track the development of Requests is through
`the GitHub repo <https://github.com/requests/requests>`_.
Twitter
-------
The author, Kenneth Reitz, often tweets about new features and releases of Requests.
Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.
`the GitHub repo <https://github.com/psf/requests>`_.
Release and Version History
===========================
.. include:: ../../HISTORY.rst
.. include:: ../../HISTORY.md

View File

@@ -2,14 +2,16 @@ Vulnerability Disclosure
========================
If you think you have found a potential security vulnerability in requests,
please email `sigmavirus24 <mailto:graffatcolmingov@gmail.com>`_ and
`Lukasa <mailto:cory@lukasa.co.uk>`_ directly. **Do not file a public issue.**
please email `Nate <mailto:nate.prewitt@gmail.com>`_ and `Seth <mailto:@sethmichaellarson@gmail.com>`_ directly. **Do not file a public issue.**
Our PGP Key fingerprints are:
- 0161 BB7E B208 B5E0 4FDC 9F81 D9DA 0A04 9113 F853 (@sigmavirus24)
- 8722 7E29 AD9C FF5C FAC3 EA6A 44D3 FF97 B80D C864 (`@nateprewitt <https://keybase.io/nateprewitt>`_)
- 90DC AE40 FEA7 4B14 9B70 662D F25F 2144 EEC1 373D (@lukasa)
- EDD5 6765 A9D8 4653 CBC8 A134 51B0 6736 1740 F5FC (`@sethmlarson <https://keybase.io/sethmlarson>`_)
You can also contact us on `Keybase <https://keybase.io/>`_ with the
profiles above if desired.
If English is not your first language, please try to describe the problem and
its impact to the best of your ability. For greater detail, please use your
@@ -70,7 +72,7 @@ time, to ensure that they are able to promptly release their downstream
packages. Currently the list of people we actively contact *ahead of a public
release* is:
- Jeremy Cline, Red Hat (@jeremycline)
- Python Maintenance Team, Red Hat (python-maint@redhat.com)
- Daniele Tricoli, Debian (@eriol)
We will notify these individuals at least a week ahead of our planned release
@@ -93,13 +95,16 @@ if upgrading is not an option.
Previous CVEs
-------------
- Fixed in 2.20.0
- `CVE 2018-18074 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=2018-18074>`_
- Fixed in 2.6.0
- `CVE 2015-2296 <http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=2015-2296>`_,
- `CVE 2015-2296 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=2015-2296>`_,
reported by Matthew Daley of `BugFuzz <https://bugfuzz.com/>`_.
- Fixed in 2.3.0
- `CVE 2014-1829 <http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=2014-1829>`_
- `CVE 2014-1829 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=2014-1829>`_
- `CVE 2014-1830 <http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=2014-1830>`_
- `CVE 2014-1830 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=2014-1830>`_

View File

@@ -18,11 +18,11 @@ import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# sys.path.insert(0, os.path.abspath('.'))
# Insert Requests' path into the system.
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('_themes'))
sys.path.insert(0, os.path.abspath(".."))
sys.path.insert(0, os.path.abspath("_themes"))
import requests
@@ -30,36 +30,36 @@ import requests
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.viewcode',
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = u'Requests'
copyright = u'MMXVII. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'
author = u'Kenneth Reitz'
project = u"Requests"
copyright = u'MMXVIX. A <a href="https://kenreitz.org/projects">Kenneth Reitz</a> Project'
author = u"Kenneth Reitz"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -79,17 +79,17 @@ language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = False
@@ -100,16 +100,16 @@ add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'flask_theme_support.FlaskyStyle'
pygments_style = "flask_theme_support.FlaskyStyle"
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
@@ -119,51 +119,52 @@ todo_include_todos = True
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'show_powered_by': False,
'github_user': 'requests',
'github_repo': 'requests',
'github_banner': True,
'show_related': False
"show_powered_by": False,
"github_user": "requests",
"github_repo": "requests",
"github_banner": True,
"show_related": False,
"note_bg": "#FFF59C",
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
@@ -171,24 +172,29 @@ html_use_smartypants = False
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html',
'hacks.html'],
'**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html', 'hacks.html']
"index": ["sidebarintro.html", "sourcelink.html", "searchbox.html", "hacks.html"],
"**": [
"sidebarlogo.html",
"localtoc.html",
"relations.html",
"sourcelink.html",
"searchbox.html",
"hacks.html",
],
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
@@ -202,84 +208,77 @@ html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'Requestsdoc'
htmlhelp_basename = "Requestsdoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Requests.tex', u'Requests Documentation',
u'Kenneth Reitz', 'manual'),
(master_doc, "Requests.tex", u"Requests Documentation", u"Kenneth Reitz", "manual")
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'requests', u'Requests Documentation',
[author], 1)
]
man_pages = [(master_doc, "requests", u"Requests Documentation", [author], 1)]
# If true, show URL addresses after external links.
#man_show_urls = False
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
@@ -288,22 +287,28 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Requests', u'Requests Documentation',
author, 'Requests', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"Requests",
u"Requests Documentation",
author,
"Requests",
"One line description of project.",
"Miscellaneous",
)
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
@@ -315,64 +320,67 @@ epub_publisher = author
epub_copyright = copyright
# The basename for the epub file. It defaults to the project name.
#epub_basename = project
# epub_basename = project
# The HTML theme for the epub output. Since the default themes are not
# optimized for small screen space, using the same theme for HTML and epub
# output is usually not wise. This defaults to 'epub', a theme designed to save
# visual space.
#epub_theme = 'epub'
# epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#epub_language = ''
# epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# epub_pre_files = []
# HTML files that should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
epub_exclude_files = ["search.html"]
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# epub_tocscope = 'default'
# Fix unsupported image types using the Pillow.
#epub_fix_images = False
# epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'
# epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
# epub_use_index = True
intersphinx_mapping = {'urllib3': ('http://urllib3.readthedocs.io/en/latest', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"urllib3": ("https://urllib3.readthedocs.io/en/latest", None),
}

View File

@@ -1,5 +1,4 @@
Authors
=======
.. include:: ../../AUTHORS.rst

View File

@@ -11,22 +11,17 @@ contributing to the Requests project is *very* generous of you.
This document lays out guidelines and advice for contributing to this project.
If you're thinking of contributing, please start by reading this document and
getting a feel for how contributing to this project works. If you have any
questions, feel free to reach out to either `Ian Cordasco`_ or `Cory Benfield`_,
the primary maintainers.
questions, feel free to reach out to either `Nate Prewitt`_, `Ian Cordasco`_,
or `Seth Michael Larson`_, the primary maintainers.
.. _Ian Cordasco: http://www.coglib.com/~icordasc/
.. _Cory Benfield: https://lukasa.co.uk/about
If you have non-technical feedback, philosophical ponderings, crazy ideas, or
other general thoughts about Requests or its position within the Python
ecosystem, the BDFL, `Kenneth Reitz`_, would love to hear from you.
.. _Nate Prewitt: https://www.nateprewitt.com/
.. _Seth Michael Larson: https://sethmlarson.dev/
The guide is split into sections based on the type of contribution you're
thinking of making, with a section that covers general guidelines for all
contributors.
.. _Kenneth Reitz: mailto:me@kennethreitz.org
Be Cordial
----------
@@ -39,7 +34,7 @@ including reporting bugs or requesting features. This golden rule is
**All contributions are welcome**, as long as
everyone involved is treated with respect.
.. _be cordial or be on your way: http://kennethreitz.org/be-cordial-or-be-on-your-way/
.. _be cordial or be on your way: https://kenreitz.org/essays/2013/01/27/be-cordial-or-be-on-your-way
.. _early-feedback:
@@ -83,7 +78,7 @@ When contributing code, you'll want to follow this checklist:
4. Make your change.
5. Run the entire test suite again, confirming that all tests pass *including
the ones you just added*.
6. Send a GitHub Pull Request to the main repository's ``master`` branch.
6. Send a GitHub Pull Request to the main repository's ``main`` branch.
GitHub Pull Requests are the expected method of code collaboration on this
project.
@@ -98,6 +93,21 @@ event that you object to the code review feedback, you should make your case
clearly and calmly. If, after doing so, the feedback is judged to still apply,
you must either apply the feedback or withdraw your contribution.
Code Style
~~~~~~~~~~
Requests uses a collection of tools to ensure the code base has a consistent
style as it grows. We have these orchestrated using a tool called
`pre-commit`_. This can be installed locally and run over your changes prior
to opening a PR, and will also be run as part of the CI approval process
before a change is merged.
You can find the full list of formatting requirements specified in the
`.pre-commit-config.yaml`_ at the top level directory of Requests.
.. _pre-commit: https://pre-commit.com/
.. _.pre-commit-config.yaml: https://github.com/psf/requests/blob/main/.pre-commit-config.yaml
New Contributors
~~~~~~~~~~~~~~~~
@@ -108,55 +118,6 @@ asking for help.
Please also check the :ref:`early-feedback` section.
Kenneth Reitz's Code Style™
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Requests codebase uses the `PEP 8`_ code style.
In addition to the standards outlined in PEP 8, we have a few guidelines:
- Line-length can exceed 79 characters, to 100, when convenient.
- Line-length can exceed 100 characters, when doing otherwise would be *terribly* inconvenient.
- Always use single-quoted strings (e.g. ``'#flatearth'``), unless a single-quote occurs within the string.
Additionally, one of the styles that PEP8 recommends for `line continuations`_
completely lacks all sense of taste, and is not to be permitted within
the Requests codebase::
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
No. Just don't. Please.
Docstrings are to follow the following syntaxes::
def the_earth_is_flat():
"""NASA divided up the seas into thirty-three degrees."""
pass
::
def fibonacci_spiral_tool():
"""With my feet upon the ground I lose myself / between the sounds
and open wide to suck it in. / I feel it move across my skin. / I'm
reaching up and reaching out. / I'm reaching for the random or
whatever will bewilder me. / Whatever will bewilder me. / And
following our will and wind we may just go where no one's been. /
We'll ride the spiral to the end and may just go where no one's
been.
Spiral out. Keep going...
"""
pass
All functions, methods, and classes are to contain docstrings. Object data
model methods (e.g. ``__repr__``) are typically the exception to this rule.
Thanks for helping to make the world a better place!
.. _PEP 8: http://pep8.org
.. _line continuations: https://www.python.org/dev/peps/pep-0008/#indentation
Documentation Contributions
---------------------------
@@ -187,7 +148,7 @@ through the `GitHub issues`_, **both open and closed**, to confirm that the bug
hasn't been reported before. Duplicate bug reports are a huge drain on the time
of other contributors, and should be avoided as much as possible.
.. _GitHub issues: https://github.com/requests/requests/issues
.. _GitHub issues: https://github.com/psf/requests/issues
Feature Requests
@@ -203,4 +164,4 @@ while keeping an open ear and mind.
If you believe there is a feature missing, feel free to raise a feature
request, but please do be aware that the overwhelming likelihood is that your
feature request will not be accepted.
feature request will not be accepted.

View File

@@ -1,41 +0,0 @@
Development Philosophy
======================
Requests is an open but opinionated library, created by an open but opinionated developer.
Management Style
~~~~~~~~~~~~~~~~
`Kenneth Reitz <http://kennethreitz.org>`_ is the BDFL. He has final say in any decision related to the Requests project. Kenneth is responsible for the direction and form of the library, as well as its presentation. In addition to making decisions based on technical merit, he is responsible for making decisions based on the development philosophy of Requests.
`Ian Cordasco <http://www.coglib.com/~icordasc/>`_ and `Cory Benfield <https://lukasa.co.uk/about/>`_ are the core contributors. They are responsible for triaging bug reports, reviewing pull requests and ensuring that Kenneth is kept up to speed with developments around the library. The day-to-day managing of the project is done by the core contributors. They are responsible for making judgements about whether or not a feature request is likely to be accepted by Kenneth. Their word is, in some ways, more final than Kenneth's.
Values
~~~~~~
- Simplicity is always better than functionality.
- Listen to everyone, then disregard it.
- The API is all that matters. Everything else is secondary.
- Fit the 90% use-case. Ignore the nay-sayers.
Semantic Versioning
~~~~~~~~~~~~~~~~~~~
For many years, the open source community has been plagued with version number dystonia. Numbers vary so greatly from project to project, they are practically meaningless.
Requests uses `Semantic Versioning <http://semver.org>`_. This specification seeks to put an end to this madness with a small set of practical guidelines for you and your colleagues to use in your next project.
Standard Library?
~~~~~~~~~~~~~~~~~
Requests has no *active* plans to be included in the standard library. This decision has been discussed at length with Guido as well as numerous core developers.
Essentially, the standard library is where a library goes to die. It is appropriate for a module to be included when active development is no longer necessary.
Linux Distro Packages
~~~~~~~~~~~~~~~~~~~~~
Distributions have been made for many Linux repositories, including: Ubuntu, Debian, RHEL, and Arch.
These distributions are sometimes divergent forks, or are otherwise not kept up-to-date with the latest code and bugfixes. PyPI (and its mirrors) and GitHub are the official distribution sources; alternatives are not supported by the Requests project.

View File

@@ -1,64 +0,0 @@
How to Help
===========
Requests is under active development, and contributions are more than welcome!
#. Check for open issues or open a fresh issue to start a discussion around a bug.
There is a Contributor Friendly tag for issues that should be ideal for people who are not very
familiar with the codebase yet.
#. Fork `the repository <https://github.com/requests/requests>`_ on GitHub and start making your
changes to a new branch.
#. Write a test which shows that the bug was fixed.
#. Send a pull request and bug the maintainer until it gets merged and published. :)
Make sure to add yourself to `AUTHORS <https://github.com/requests/requests/blob/master/AUTHORS.rst>`_.
Feature Freeze
--------------
As of v1.0.0, Requests has now entered a feature freeze. Requests for new
features and Pull Requests implementing those features will not be accepted.
Development Dependencies
------------------------
You'll need to install py.test in order to run the Requests' test suite::
$ venv .venv
$ source .venv/bin/activate
$ make
$ python setup.py test
============================= test session starts ==============================
platform darwin -- Python 3.4.4, pytest-3.0.6, py-1.4.32, pluggy-0.4.0
...
collected 445 items
tests/test_hooks.py ...
tests/test_lowlevel.py ............
tests/test_requests.py ...........................................................
tests/test_structures.py ....................
tests/test_testserver.py ...........
tests/test_utils.py ..s...........................................................
============== 442 passed, 1 skipped, 2 xpassed in 46.48 seconds ===============
You can also run ``$ make tests`` to run against all supported Python versions, using tox/detox.
Runtime Environments
--------------------
Requests currently supports the following versions of Python:
- Python 2.6
- Python 2.7
- Python 3.3
- Python 3.4
- Python 3.5
- Python 3.6
- PyPy
Google AppEngine is not officially supported although support is available
with the `Requests-Toolbelt`_.
.. _Requests-Toolbelt: http://toolbelt.readthedocs.io/

View File

@@ -3,34 +3,29 @@
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Requests: HTTP for Humans
=========================
Requests: HTTP for Humans
==========================
Release v\ |version|. (:ref:`Installation <install>`)
.. image:: https://static.pepy.tech/badge/requests/month
:target: https://pepy.tech/project/requests
:alt: Requests Downloads Per Month Badge
.. image:: https://img.shields.io/pypi/l/requests.svg
:target: https://pypi.python.org/pypi/requests
:target: https://pypi.org/project/requests/
:alt: License Badge
.. image:: https://img.shields.io/pypi/wheel/requests.svg
:target: https://pypi.python.org/pypi/requests
:target: https://pypi.org/project/requests/
:alt: Wheel Support Badge
.. image:: https://img.shields.io/pypi/pyversions/requests.svg
:target: https://pypi.python.org/pypi/requests
:target: https://pypi.org/project/requests/
:alt: Python Version Support Badge
.. image:: https://codecov.io/github/requests/requests/coverage.svg?branch=master
:target: https://codecov.io/github/requests/requests
:alt: codecov.io
.. image:: https://img.shields.io/badge/Say%20Thanks!-🦉-1EAEDB.svg
:target: https://saythanks.io/to/kennethreitz
**Requests** is the only *Non-GMO* HTTP library for Python, safe for human
consumption.
*Warning: Recreational use of the Python standard library for HTTP may result in dangerous side-effects,
including: security vulnerabilities, verbose code, reinventing the wheel,
constantly reading documentation, depression, headaches, or even death.*
**Requests** is an elegant and simple HTTP library for Python, built for human beings.
-------------------
@@ -44,44 +39,17 @@ constantly reading documentation, depression, headaches, or even death.*
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
{'private_gists': 419, 'total_private_repos': 77, ...}
See `similar code, sans Requests <https://gist.github.com/973705>`_.
**Requests** allows you to send *organic, grass-fed* HTTP/1.1 requests, without the
need for manual labor. There's no need to manually add query strings to your
**Requests** allows you to send HTTP/1.1 requests extremely easily.
There's no need to manually add query strings to your
URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling
are 100% automatic, thanks to `urllib3 <https://github.com/shazow/urllib3>`_.
User Testimonials
-----------------
Twitter, Spotify, Microsoft, Amazon, Lyft, BuzzFeed, Reddit, The NSA, Her Majesty's Government, Google, Twilio, Runscope, Mozilla, Heroku,
PayPal, NPR, Obama for America, Transifex, Native Instruments, The Washington
Post, SoundCloud, Kippt, Sony, and Federal U.S.
Institutions that prefer to be unnamed claim to use Requests internally.
**Armin Ronacher**
*Requests is the perfect example how beautiful an API can be with the
right level of abstraction.*
**Matt DeBoard**
*I'm going to get Kenneth Reitz's Python requests module tattooed
on my body, somehow. The whole thing.*
**Daniel Greenfeld**
*Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to
Kenneth Reitz's request library. Today has been AWESOME.*
**Kenny Meyers**
*Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,
simple, Pythonic.*
Requests is one of the most downloaded Python packages of all time, pulling in
over 11,000,000 downloads every month. All the cool kids are doing it!
are 100% automatic, thanks to `urllib3 <https://github.com/urllib3/urllib3>`_.
Beloved Features
----------------
@@ -104,7 +72,7 @@ Requests is ready for today's web.
- Chunked Requests
- ``.netrc`` Support
Requests officially supports Python 2.62.7 & 3.33.7, and runs great on PyPy.
Requests officially supports Python 3.8+, and runs great on PyPy.
The User Guide
@@ -117,7 +85,6 @@ instructions for getting the most out of Requests.
.. toctree::
:maxdepth: 2
user/intro
user/install
user/quickstart
user/advanced
@@ -131,16 +98,20 @@ This part of the documentation, which is mostly prose, details the
Requests ecosystem and community.
.. toctree::
:maxdepth: 1
:maxdepth: 2
community/faq
community/recommended
community/faq
community/out-there
community/support
community/vulnerabilities
community/updates
community/release-process
.. toctree::
:maxdepth: 1
community/updates
The API Documentation / Guide
-----------------------------
@@ -163,8 +134,6 @@ you.
:maxdepth: 3
dev/contributing
dev/philosophy
dev/todo
dev/authors
There are no more guides. You are now guideless.

3
docs/requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
# Pinning to avoid unexpected breakages.
# Used by RTD to generate docs.
Sphinx==7.2.6

View File

@@ -23,8 +23,8 @@ Let's persist some cookies across requests::
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('http://httpbin.org/cookies')
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('https://httpbin.org/cookies')
print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'
@@ -38,7 +38,7 @@ is done by providing data to the properties on a Session object::
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})
Any dictionaries that you pass to a request method will be merged with the
@@ -51,11 +51,11 @@ with the first request, but not the second::
s = requests.Session()
r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})
r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})
print(r.text)
# '{"cookies": {"from-my": "browser"}}'
r = s.get('http://httpbin.org/cookies')
r = s.get('https://httpbin.org/cookies')
print(r.text)
# '{"cookies": {}}'
@@ -67,7 +67,7 @@ If you want to manually add cookies to your session, use the
Sessions can also be used as context managers::
with requests.Session() as s:
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
This will make sure the session is closed as soon as the ``with`` block is
exited, even if unhandled exceptions occurred.
@@ -95,7 +95,7 @@ The ``Response`` object contains all of the information returned by the server a
also contains the ``Request`` object you created originally. Here is a simple
request to get some very important information from Wikipedia's servers::
>>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')
>>> r = requests.get('https://en.wikipedia.org/wiki/Monty_Python')
If we want to access the headers the server sent back to us, we do this::
@@ -187,6 +187,25 @@ applied, replace the call to :meth:`Request.prepare()
print(resp.status_code)
When you are using the prepared request flow, keep in mind that it does not take into account the environment.
This can cause problems if you are using environment variables to change the behaviour of requests.
For example: Self-signed SSL certificates specified in ``REQUESTS_CA_BUNDLE`` will not be taken into account.
As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.
You can get around this behaviour by explicitly merging the environment settings into your session::
from requests import Request, Session
s = Session()
req = Request('GET', url)
prepped = s.prepare_request(req)
# Merge environment settings into session
settings = s.merge_environment_settings(prepped.url, {}, None, None, None)
resp = s.send(prepped, **settings)
print(resp.status_code)
.. _verification:
SSL Cert Verification
@@ -214,15 +233,22 @@ or persistent::
s.verify = '/path/to/certfile'
.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using
the c_rehash utility supplied with OpenSSL.
the ``c_rehash`` utility supplied with OpenSSL.
This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.
If ``REQUESTS_CA_BUNDLE`` is not set, ``CURL_CA_BUNDLE`` will be used as fallback.
Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::
>>> requests.get('https://kennethreitz.org', verify=False)
<Response [200]>
Note that when ``verify`` is set to ``False``, requests will accept any TLS
certificate presented by the server, and will ignore hostname mismatches
and/or expired certificates, which will make your application vulnerable to
man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful
during local development or testing.
By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.
Client Side Certificates
@@ -253,21 +279,20 @@ If you specify a wrong path or an invalid cert, you'll get a SSLError::
CA Certificates
---------------
By default, Requests bundles a set of root CAs that it trusts, sourced from the
`Mozilla trust store`_. However, these are only updated once for each Requests
version. This means that if you pin a Requests version your certificates can
become extremely out of date.
Requests uses certificates from the package `certifi`_. This allows for users
to update their trusted certificates without changing the version of Requests.
From Requests version 2.4.0 onwards, Requests will attempt to use certificates
from `certifi`_ if it is present on the system. This allows for users to update
their trusted certificates without having to change the code that runs on their
system.
Before version 2.16, Requests bundled a set of root CAs that it trusted,
sourced from the `Mozilla trust store`_. The certificates were only updated
once for each Requests version. When ``certifi`` was not installed, this led to
extremely out-of-date certificate bundles when using significantly older
versions of Requests.
For the sake of security we recommend upgrading certifi frequently!
.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection
.. _connection pooling: http://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool
.. _certifi: http://certifi.io/
.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/urllib3.connectionpool.html
.. _certifi: https://certifiio.readthedocs.io/
.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt
.. _body-content-workflow:
@@ -280,7 +305,7 @@ immediately. You can override this behaviour and defer downloading the response
body until you access the :attr:`Response.content <requests.Response.content>`
attribute with the ``stream`` parameter::
tarball_url = 'https://github.com/requests/requests/tarball/master'
tarball_url = 'https://github.com/psf/requests/tarball/main'
r = requests.get(tarball_url, stream=True)
At this point only the response headers have been downloaded and the connection
@@ -303,7 +328,7 @@ inefficiency with connections. If you find yourself partially reading request
bodies (or not reading them at all) while using ``stream=True``, you should
make the request within a ``with`` statement to ensure it's always closed::
with requests.get('http://httpbin.org/get', stream=True) as r:
with requests.get('https://httpbin.org/get', stream=True) as r:
# Do things with the response here.
.. _keep-alive:
@@ -331,13 +356,11 @@ file-like object for your body::
with open('massive-body', 'rb') as f:
requests.post('http://some.url/streamed', data=f)
.. warning:: It is strongly recommended that you open files in `binary mode`_.
This is because Requests may attempt to provide the
``Content-Length`` header for you, and if it does this value will
be set to the number of *bytes* in the file. Errors may occur if
you open the file in *text mode*.
.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
.. warning:: It is strongly recommended that you open files in :ref:`binary
mode <tut-files>`. This is because Requests may attempt to provide
the ``Content-Length`` header for you, and if it does this value
will be set to the number of *bytes* in the file. Errors may occur
if you open the file in *text mode*.
.. _chunk-encoding:
@@ -375,10 +398,10 @@ upload image files to an HTML form with a multiple file field 'images'::
To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::
>>> url = 'http://httpbin.org/post'
>>> 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'))]
... ('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
{
@@ -388,13 +411,11 @@ To do that, just set files to a list of tuples of ``(form_field_name, file_info)
...
}
.. warning:: It is strongly recommended that you open files in `binary mode`_.
This is because Requests may attempt to provide the
``Content-Length`` header for you, and if it does this value will
be set to the number of *bytes* in the file. Errors may occur if
you open the file in *text mode*.
.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
.. warning:: It is strongly recommended that you open files in :ref:`binary
mode <tut-files>`. This is because Requests may attempt to provide
the ``Content-Length`` header for you, and if it does this value
will be set to the number of *bytes* in the file. Errors may occur
if you open the file in *text mode*.
.. _event-hooks:
@@ -415,7 +436,7 @@ You can assign a hook function on a per-request basis by passing a
``{hook_name: callback_function}`` dictionary to the ``hooks`` request
parameter::
hooks=dict(response=print_url)
hooks={'response': print_url}
That ``callback_function`` will receive a chunk of data as its first
argument.
@@ -425,24 +446,48 @@ argument.
def print_url(r, *args, **kwargs):
print(r.url)
If an error occurs while executing your callback, a warning is given.
Your callback function must handle its own exceptions. Any unhandled exception won't be passed silently and thus should be handled by the code calling Requests.
If the callback function returns a value, it is assumed that it is to
replace the data that was passed in. If the function doesn't return
anything, nothing else is effected.
anything, nothing else is affected.
::
def record_hook(r, *args, **kwargs):
r.hook_called = True
return r
Let's print some request method arguments at runtime::
>>> requests.get('http://httpbin.org', hooks=dict(response=print_url))
http://httpbin.org
>>> requests.get('https://httpbin.org/', hooks={'response': print_url})
https://httpbin.org/
<Response [200]>
You can add multiple hooks to a single request. Let's call two hooks at once::
>>> r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})
>>> r.hook_called
True
You can also add hooks to a ``Session`` instance. Any hooks you add will then
be called on every request made to the session. For example::
>>> s = requests.Session()
>>> s.hooks['response'].append(print_url)
>>> s.get('https://httpbin.org/')
https://httpbin.org/
<Response [200]>
A ``Session`` can have multiple hooks, which will be called in the order
they are added.
.. _custom-auth:
Custom Authentication
---------------------
Requests allows you to use specify your own authentication mechanism.
Requests allows you to specify your own authentication mechanism.
Any callable which is passed as the ``auth`` argument to a request method will
have the opportunity to modify the request before it is dispatched.
@@ -489,7 +534,7 @@ set ``stream`` to ``True`` and iterate over the response with
import json
import requests
r = requests.get('http://httpbin.org/stream/20', stream=True)
r = requests.get('https://httpbin.org/stream/20', stream=True)
for line in r.iter_lines():
@@ -503,7 +548,7 @@ When using `decode_unicode=True` with
:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want
to provide a fallback encoding in the event the server doesn't provide one::
r = requests.get('http://httpbin.org/stream/20', stream=True)
r = requests.get('https://httpbin.org/stream/20', stream=True)
if r.encoding is None:
r.encoding = 'utf-8'
@@ -544,21 +589,55 @@ If you need to use a proxy, you can configure individual requests with the
requests.get('http://example.org', proxies=proxies)
You can also configure proxies by setting the environment variables
``HTTP_PROXY`` and ``HTTPS_PROXY``.
Alternatively you can configure it once for an entire
:class:`Session <requests.Session>`::
::
import requests
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
session = requests.Session()
session.proxies.update(proxies)
session.get('http://example.org')
.. warning:: Setting ``session.proxies`` may behave differently than expected.
Values provided will be overwritten by environmental proxies
(those returned by `urllib.request.getproxies <https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies>`_).
To ensure the use of proxies in the presence of environmental proxies,
explicitly specify the ``proxies`` argument on all individual requests as
initially explained above.
See `#2018 <https://github.com/psf/requests/issues/2018>`_ for details.
When the proxies configuration is not overridden per request as shown above,
Requests relies on the proxy configuration defined by standard
environment variables ``http_proxy``, ``https_proxy``, ``no_proxy``,
and ``all_proxy``. Uppercase variants of these variables are also supported.
You can therefore set them to configure Requests (only set the ones relevant
to your needs)::
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"
$ export ALL_PROXY="socks5://10.10.1.10:3434"
$ python
>>> import requests
>>> requests.get('http://example.org')
To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::
To use HTTP Basic Auth with your proxy, use the `http://user:password@host/`
syntax in any of the above configuration entries::
proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}
$ export HTTPS_PROXY="http://user:pass@10.10.1.10:1080"
$ python
>>> proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}
.. warning:: Storing sensitive username and password information in an
environment variable or a version-controlled file is a security risk and is
highly discouraged.
To give a proxy for a specific scheme and host, use the
`scheme://hostname` form for the key. This will match for
@@ -570,6 +649,25 @@ any request to the given scheme and exact hostname.
Note that proxy URLs must include the scheme.
Finally, note that using a proxy for https connections typically requires your
local machine to trust the proxy's root certificate. By default the list of
certificates trusted by Requests can be found with::
from requests.utils import DEFAULT_CA_BUNDLE_PATH
print(DEFAULT_CA_BUNDLE_PATH)
You override this default certificate bundle by setting the ``REQUESTS_CA_BUNDLE``
(or ``CURL_CA_BUNDLE``) environment variable to another file path::
$ export REQUESTS_CA_BUNDLE="/usr/local/myproxy_info/cacert.pem"
$ export https_proxy="http://10.10.1.10:1080"
$ python
>>> import requests
>>> requests.get('https://example.org')
.. _socks:
SOCKS
^^^^^
@@ -583,7 +681,7 @@ You can get the dependencies for this feature from ``pip``:
.. code-block:: bash
$ pip install requests[socks]
$ python -m pip install requests[socks]
Once you've installed those dependencies, using a SOCKS proxy is just as easy
as using a HTTP one::
@@ -593,6 +691,8 @@ as using a HTTP one::
'https': 'socks5://user:pass@host:port'
}
Using the scheme ``socks5`` causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, use ``socks5h`` as the scheme.
.. _compliance:
Compliance
@@ -609,13 +709,24 @@ Encodings
When you receive a response, Requests makes a guess at the encoding to
use for decoding the response when you access the :attr:`Response.text
<requests.Response.text>` attribute. Requests will first check for an
encoding in the HTTP header, and if none is present, will use `chardet
<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.
encoding in the HTTP header, and if none is present, will use
`charset_normalizer <https://pypi.org/project/charset_normalizer/>`_
or `chardet <https://github.com/chardet/chardet>`_ to attempt to
guess the encoding.
The only time Requests will not do this is if no explicit charset
If ``chardet`` is installed, ``requests`` uses it, however for python3
``chardet`` is no longer a mandatory dependency. The ``chardet``
library is an LGPL-licenced dependency and some users of requests
cannot depend on mandatory LGPL-licensed dependencies.
When you install ``requests`` without specifying ``[use_chardet_on_py3]`` extra,
and ``chardet`` is not already installed, ``requests`` uses ``charset-normalizer``
(MIT-licensed) to guess the encoding.
The only time Requests will not guess the encoding is if no explicit charset
is present in the HTTP headers **and** the ``Content-Type``
header contains ``text``. In this situation, `RFC 2616
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies
<https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies
that the default charset must be ``ISO-8859-1``. Requests follows the
specification in this case. If you require a different encoding, you can
manually set the :attr:`Response.encoding <requests.Response.encoding>`
@@ -638,7 +749,7 @@ from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it
like so::
>>> import requests
>>> r = requests.get('https://api.github.com/repos/requests/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')
>>> r = requests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')
We should confirm that GitHub responded correctly. If it has, we want to work
out what type of content it is. Do this like so::
@@ -656,12 +767,12 @@ So, GitHub returns JSON. That's great, we can use the :meth:`r.json
>>> commit_data = r.json()
>>> print(commit_data.keys())
[u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']
['committer', 'author', 'url', 'tree', 'sha', 'parents', 'message']
>>> print(commit_data[u'committer'])
{u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}
>>> print(commit_data['committer'])
{'date': '2012-05-10T11:10:50-07:00', 'email': 'me@kennethreitz.com', 'name': 'Kenneth Reitz'}
>>> print(commit_data[u'message'])
>>> print(commit_data['message'])
makin' history
So far, so simple. Well, let's investigate the GitHub API a little bit. Now,
@@ -693,37 +804,37 @@ we should probably avoid making ham-handed POSTS to it. Instead, let's play
with the Issues feature of GitHub.
This documentation was added in response to
`Issue #482 <https://github.com/requests/requests/issues/482>`_. Given that
`Issue #482 <https://github.com/psf/requests/issues/482>`_. Given that
this issue already exists, we will use it as an example. Let's start by getting it.
::
>>> r = requests.get('https://api.github.com/repos/requests/requests/issues/482')
>>> r = requests.get('https://api.github.com/repos/psf/requests/issues/482')
>>> r.status_code
200
>>> issue = json.loads(r.text)
>>> print(issue[u'title'])
>>> print(issue['title'])
Feature any http verb in docs
>>> print(issue[u'comments'])
>>> print(issue['comments'])
3
Cool, we have three comments. Let's take a look at the last of them.
::
>>> r = requests.get(r.url + u'/comments')
>>> r = requests.get(r.url + '/comments')
>>> r.status_code
200
>>> comments = r.json()
>>> print(comments[0].keys())
[u'body', u'url', u'created_at', u'updated_at', u'user', u'id']
['body', 'url', 'created_at', 'updated_at', 'user', 'id']
>>> print(comments[2][u'body'])
>>> print(comments[2]['body'])
Probably in the "advanced" section
Well, that seems like a silly place. Let's post a comment telling the poster
@@ -731,7 +842,7 @@ that he's silly. Who is the poster, anyway?
::
>>> print(comments[2][u'user'][u'login'])
>>> print(comments[2]['user']['login'])
kennethreitz
OK, so let's tell this Kenneth guy that we think this example should go in the
@@ -741,7 +852,7 @@ is to POST to the thread. Let's do it.
::
>>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})
>>> url = u"https://api.github.com/repos/requests/requests/issues/482/comments"
>>> url = u"https://api.github.com/repos/psf/requests/issues/482/comments"
>>> r = requests.post(url=url, data=body)
>>> r.status_code
@@ -761,7 +872,7 @@ the very common Basic Auth.
201
>>> content = r.json()
>>> print(content[u'body'])
>>> print(content['body'])
Sounds great! I'll get right on it.
Brilliant. Oh, wait, no! I meant to add that it would take me a while, because
@@ -775,7 +886,7 @@ that.
5804413
>>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})
>>> url = u"https://api.github.com/repos/requests/requests/issues/comments/5804413"
>>> url = u"https://api.github.com/repos/psf/requests/issues/comments/5804413"
>>> r = requests.patch(url=url, data=body, auth=auth)
>>> r.status_code
@@ -837,7 +948,7 @@ Link Headers
Many HTTP APIs feature Link headers. They make APIs more self describing and
discoverable.
GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_
GitHub uses these for `pagination <https://docs.github.com/en/rest/guides/using-pagination-in-the-rest-api>`_
in their API, for example::
>>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'
@@ -879,12 +990,16 @@ it should apply to.
::
>>> s = requests.Session()
>>> s.mount('http://www.github.com', MyAdapter())
>>> s.mount('https://github.com/', MyAdapter())
The mount call registers a specific instance of a Transport Adapter to a
prefix. Once mounted, any HTTP request made using that session whose URL starts
with the given prefix will use the given Transport Adapter.
.. note:: The adapter will be chosen based on a longest prefix match. Be mindful
prefixes such as ``http://localhost`` will also match ``http://localhost.other.com``
or ``http://localhost@other.com``. It's recommended to terminate full hostnames with a ``/``.
Many of the details of implementing a Transport Adapter are beyond the scope of
this documentation, but take a look at the next example for a simple SSL use-
case. For more than that, you might look at subclassing the
@@ -904,9 +1019,9 @@ passed-through to `urllib3`. We'll make a Transport Adapter that instructs the
library to use SSLv3::
import ssl
from urllib3.poolmanager import PoolManager
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
class Ssl3HttpAdapter(HTTPAdapter):
@@ -917,8 +1032,30 @@ library to use SSLv3::
num_pools=connections, maxsize=maxsize,
block=block, ssl_version=ssl.PROTOCOL_SSLv3)
.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http
.. _`urllib3`: https://github.com/shazow/urllib3
Example: Automatic Retries
^^^^^^^^^^^^^^^^^^^^^^^^^^
By default, Requests does not retry failed connections. However, it is possible
to implement automatic retries with a powerful array of features, including
backoff, within a Requests :class:`Session <requests.Session>` using the
`urllib3.util.Retry`_ class::
from urllib3.util import Retry
from requests import Session
from requests.adapters import HTTPAdapter
s = Session()
retries = Retry(
total=3,
backoff_factor=0.1,
status_forcelist=[502, 503, 504],
allowed_methods={'POST'},
)
s.mount('https://', HTTPAdapter(max_retries=retries))
.. _`described here`: https://kenreitz.org/essays/2012/06/14/the-future-of-python-http
.. _`urllib3`: https://github.com/urllib3/urllib3
.. _`urllib3.util.Retry`: https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html#urllib3.util.Retry
.. _blocking-or-nonblocking:
@@ -934,17 +1071,19 @@ response at a time. However, these calls will still block.
If you are concerned about the use of blocking IO, there are lots of projects
out there that combine Requests with one of Python's asynchronicity frameworks.
Two excellent examples are `grequests`_ and `requests-futures`_.
Some excellent examples are `requests-threads`_, `grequests`_, `requests-futures`_, and `httpx`_.
.. _`grequests`: https://github.com/kennethreitz/grequests
.. _`requests-threads`: https://github.com/requests/requests-threads
.. _`grequests`: https://github.com/spyoungtech/grequests
.. _`requests-futures`: https://github.com/ross/requests-futures
.. _`httpx`: https://github.com/encode/httpx
Header Ordering
---------------
In unusual circumstances you may want to provide headers in an ordered manner. If you pass an ``OrderedDict`` to the ``headers`` keyword argument, that will provide the headers with an ordering. *However*, the ordering of the default headers used by Requests will be preferred, which means that if you override default headers in the ``headers`` keyword argument, they may appear out of order compared to other headers in that keyword argument.
If this is problematic, users should consider setting the default headers on a :class:`Session <requests.Session>` object, by setting :attr:`Session <requests.Session.headers>` to a custom ``OrderedDict``. That ordering will always be preferred.
If this is problematic, users should consider setting the default headers on a :class:`Session <requests.Session>` object, by setting :attr:`Session.headers <requests.Session.headers>` to a custom ``OrderedDict``. That ordering will always be preferred.
.. _timeouts:
@@ -960,7 +1099,7 @@ The **connect** timeout is the number of seconds Requests will wait for your
client to establish a connection to a remote machine (corresponding to the
`connect()`_) call on the socket. It's a good practice to set connect timeouts
to slightly larger than a multiple of 3, which is the default `TCP packet
retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.
retransmission window <https://datatracker.ietf.org/doc/html/rfc2988>`_.
Once your client has connected to the server and sent the HTTP request, the
**read** timeout is the number of seconds the client will wait for the server
@@ -985,4 +1124,18 @@ coffee.
r = requests.get('https://github.com', timeout=None)
.. _`connect()`: http://linux.die.net/man/2/connect
.. note:: The connect timeout applies to each connection attempt to an IP address.
If multiple addresses exist for a domain name, the underlying ``urllib3`` will
try each address sequentially until one successfully connects.
This may lead to an effective total connection timeout *multiple* times longer
than the specified time, e.g. an unresponsive server having both IPv4 and IPv6
addresses will have its perceived timeout *doubled*, so take that into account
when setting the connection timeout.
.. note:: Neither the connect nor read timeouts are `wall clock`_. This means
that if you start a request, and look at the time, and then look at
the time when the request finishes or times out, the real-world time
may be greater than what you specified.
.. _`wall clock`: https://wiki.php.net/rfc/max_execution_wall_time
.. _`connect()`: https://linux.die.net/man/2/connect

View File

@@ -19,13 +19,14 @@ the simplest kind, and Requests supports it straight out of the box.
Making requests with HTTP Basic Auth is very simple::
>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
>>> basic = HTTPBasicAuth('user', 'pass')
>>> requests.get('https://httpbin.org/basic-auth/user/pass', auth=basic)
<Response [200]>
In fact, HTTP Basic Auth is so common that Requests provides a handy shorthand
for using it::
>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
<Response [200]>
Providing the credentials in a tuple like this is exactly the same as the
@@ -51,7 +52,7 @@ Another very popular form of HTTP Authentication is Digest Authentication,
and Requests supports this out of the box as well::
>>> from requests.auth import HTTPDigestAuth
>>> url = 'http://httpbin.org/digest-auth/auth/user/pass'
>>> url = 'https://httpbin.org/digest-auth/auth/user/pass'
>>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
<Response [200]>
@@ -120,7 +121,7 @@ To do so, subclass :class:`AuthBase <requests.auth.AuthBase>` and implement the
... # Implement my authentication
... return r
...
>>> url = 'http://httpbin.org/get'
>>> url = 'https://httpbin.org/get'
>>> requests.get(url, auth=MyAuth())
<Response [200]>
@@ -132,13 +133,13 @@ authentication will additionally add hooks to provide further functionality.
Further examples can be found under the `Requests organization`_ and in the
``auth.py`` file.
.. _OAuth: http://oauth.net/
.. _OAuth: https://oauth.net/
.. _requests_oauthlib: https://github.com/requests/requests-oauthlib
.. _requests-oauthlib OAuth2 documentation: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html
.. _Web Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#web-application-flow
.. _Mobile Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#mobile-application-flow
.. _Legacy Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#legacy-application-flow
.. _Backend Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow
.. _requests-oauthlib OAuth2 documentation: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html
.. _Web Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#web-application-flow
.. _Mobile Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#mobile-application-flow
.. _Legacy Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#legacy-application-flow
.. _Backend Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow
.. _Kerberos: https://github.com/requests/requests-kerberos
.. _NTLM: https://github.com/requests/requests-ntlm
.. _Requests organization: https://github.com/requests

View File

@@ -7,34 +7,30 @@ This part of the documentation covers the installation of Requests.
The first step to using any software package is getting it properly installed.
$ pip install requests
----------------------
$ python -m pip install requests
--------------------------------
To install Requests, simply run this simple command in your terminal of choice::
$ pip install requests
If you don't have `pip <https://pip.pypa.io>`_ installed (tisk tisk!),
`this Python installation guide <http://docs.python-guide.org/en/latest/starting/installation/>`_
can guide you through the process.
$ python -m pip install requests
Get the Source Code
-------------------
Requests is actively developed on GitHub, where the code is
`always available <https://github.com/requests/requests>`_.
`always available <https://github.com/psf/requests>`_.
You can either clone the public repository::
$ git clone git://github.com/requests/requests.git
$ git clone https://github.com/psf/requests.git
Or, download the `tarball <https://github.com/requests/requests/tarball/master>`_::
Or, download the `tarball <https://github.com/psf/requests/tarball/main>`_::
$ curl -OL https://github.com/requests/requests/tarball/master
$ curl -OL https://github.com/psf/requests/tarball/main
# optionally, zipball is also available (for Windows users).
Once you have a copy of the source, you can embed it in your own Python
package, or install it into your site-packages easily::
$ cd requests
$ pip install .
$ python -m pip install .

View File

@@ -1,45 +0,0 @@
.. _introduction:
Introduction
============
Philosophy
----------
Requests was developed with a few :pep:`20` idioms in mind.
#. Beautiful is better than ugly.
#. Explicit is better than implicit.
#. Simple is better than complex.
#. Complex is better than complicated.
#. Readability counts.
All contributions to Requests should keep these important rules in mind.
.. _`apache2`:
Apache2 License
---------------
A large number of open source projects you find today are `GPL Licensed`_.
While the GPL has its time and place, it should most certainly not be your
go-to license for your next open source project.
A project that is released as GPL cannot be used in any commercial product
without the product itself also being offered as open source.
The MIT, BSD, ISC, and Apache2 licenses are great alternatives to the GPL
that allow your open-source software to be used freely in proprietary,
closed-source software.
Requests is released under terms of `Apache2 License`_.
.. _`GPL Licensed`: http://www.opensource.org/licenses/gpl-license.php
.. _`Apache2 License`: http://opensource.org/licenses/Apache-2.0
Requests License
----------------
.. include:: ../../LICENSE

View File

@@ -37,15 +37,15 @@ get all the information we need from this object.
Requests' simple API means that all forms of HTTP request are as obvious. For
example, this is how you make an HTTP POST request::
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
>>> r = requests.post('https://httpbin.org/post', data={'key': 'value'})
Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
OPTIONS? These are all just as simple::
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')
>>> r = requests.put('https://httpbin.org/put', data={'key': 'value'})
>>> r = requests.delete('https://httpbin.org/delete')
>>> r = requests.head('https://httpbin.org/get')
>>> r = requests.options('https://httpbin.org/get')
That's all well and good, but it's also only the start of what Requests can
do.
@@ -63,12 +63,12 @@ using the ``params`` keyword argument. As an example, if you wanted to pass
following code::
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> r = requests.get('https://httpbin.org/get', params=payload)
You can see that the URL has been correctly encoded by printing the URL::
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
https://httpbin.org/get?key2=value2&key1=value1
Note that any dictionary key whose value is ``None`` will not be added to the
URL's query string.
@@ -77,9 +77,9 @@ You can also pass a list of items as a value::
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> r = requests.get('https://httpbin.org/get', params=payload)
>>> print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
https://httpbin.org/get?key1=value1&key2=value2&key2=value3
Response Content
----------------
@@ -91,7 +91,7 @@ again::
>>> r = requests.get('https://api.github.com/events')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
'[{"repository":{"open_issues":0,"url":"https://github.com/...
Requests will automatically decode content from the server. Most unicode
charsets are seamlessly decoded.
@@ -108,7 +108,7 @@ using, and change it, using the ``r.encoding`` property::
If you change the encoding, Requests will use the new value of ``r.encoding``
whenever you call ``r.text``. You might want to do this in any situation where
you can apply special logic to work out what the encoding of the content will
be. For example, HTTP and XML have the ability to specify their encoding in
be. For example, HTML and XML have the ability to specify their encoding in
their body. In situations like this, you should use ``r.content`` to find the
encoding, and then set ``r.encoding``. This will let you use ``r.text`` with
the correct encoding.
@@ -128,6 +128,9 @@ You can also access the response body as bytes, for non-text requests::
The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.
The ``br`` transfer-encoding is automatically decoded for you if a Brotli library
like `brotli <https://pypi.org/project/brotli>`_ or `brotlicffi <https://pypi.org/project/brotlicffi>`_ is installed.
For example, to create an image from binary data returned by a request, you can
use the following code::
@@ -146,11 +149,13 @@ There's also a builtin JSON decoder, in case you're dealing with JSON data::
>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
[{'repository': {'open_issues': 0, 'url': 'https://github.com/...
In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if
the response gets a 204 (No Content), or if the response contains invalid JSON,
attempting ``r.json()`` raises ``ValueError: No JSON object could be decoded``.
attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception
provides interoperability for multiple exceptions that may be thrown by different
python versions and json serialization libraries.
It should be noted that the success of the call to ``r.json()`` does **not**
indicate the success of the response. Some servers may return a JSON object in a
@@ -169,10 +174,10 @@ server, you can access ``r.raw``. If you want to do this, make sure you set
>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
<urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
In general, however, you should use a pattern like this to save what is being
streamed to a file::
@@ -187,6 +192,16 @@ download, the above is the preferred and recommended way to retrieve the
content. Note that ``chunk_size`` can be freely adjusted to a number that
may better fit your use cases.
.. note::
An important note about using ``Response.iter_content`` versus ``Response.raw``.
``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``
transfer-encodings. ``Response.raw`` is a raw stream of bytes -- it does not
transform the response content. If you really need access to the bytes as they
were returned, use ``Response.raw``.
.. _custom-headers:
Custom Headers
--------------
@@ -205,7 +220,8 @@ Note: Custom headers are given less precedence than more specific sources of inf
* Authorization headers set with `headers=` will be overridden if credentials
are specified in ``.netrc``, which in turn will be overridden by the ``auth=``
parameter.
parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,
or at the path specified by the `NETRC` environment variable.
* Authorization headers will be removed if you get redirected off-host.
* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.
* Content-Length headers will be overridden when we can determine the length of the content.
@@ -223,7 +239,7 @@ dictionary of data will automatically be form-encoded when the request is made::
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> r = requests.post('https://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
@@ -234,12 +250,16 @@ dictionary of data will automatically be form-encoded when the request is made::
...
}
You can also pass a list of tuples to the ``data`` argument. This is particularly
useful when the form has multiple elements that use the same key::
The ``data`` argument can also have multiple values for each key. This can be
done by making ``data`` either a list of tuples or a dictionary with lists
as values. This is particularly useful when the form has multiple elements that
use the same key::
>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
>>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
>>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
>>> payload_dict = {'key1': ['value1', 'value2']}
>>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)
>>> print(r1.text)
{
...
"form": {
@@ -250,6 +270,8 @@ useful when the form has multiple elements that use the same key::
},
...
}
>>> r1.text == r2.text
True
There are times that you may want to send data that is not form-encoded. If
you pass in a ``string`` instead of a ``dict``, that data will be posted directly.
@@ -263,21 +285,26 @@ For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::
>>> r = requests.post(url, data=json.dumps(payload))
Instead of encoding the ``dict`` yourself, you can also pass it directly using
the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::
Please note that the above code will NOT add the ``Content-Type`` header
(so in particular it will NOT set it to ``application/json``).
If you need that header set and you don't want to encode the ``dict`` yourself,
you can also pass it directly using the ``json`` parameter (added in version 2.4.2)
and it will be encoded automatically:
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.
POST a Multipart-Encoded File
-----------------------------
Requests makes it simple to upload Multipart-encoded files::
>>> url = 'http://httpbin.org/post'
>>> url = 'https://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
@@ -292,7 +319,7 @@ Requests makes it simple to upload Multipart-encoded files::
You can set the filename, content_type and headers explicitly::
>>> url = 'http://httpbin.org/post'
>>> url = 'https://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
>>> r = requests.post(url, files=files)
@@ -307,7 +334,7 @@ You can set the filename, content_type and headers explicitly::
If you want, you can send strings to be received as files::
>>> url = 'http://httpbin.org/post'
>>> url = 'https://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)
@@ -329,13 +356,11 @@ support this, but there is a separate package which does -
For sending multiple files in one request refer to the :ref:`advanced <advanced>`
section.
.. warning:: It is strongly recommended that you open files in `binary mode`_.
This is because Requests may attempt to provide the
``Content-Length`` header for you, and if it does this value will
be set to the number of *bytes* in the file. Errors may occur if
you open the file in *text mode*.
.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
.. warning:: It is strongly recommended that you open files in :ref:`binary
mode <tut-files>`. This is because Requests may attempt to provide
the ``Content-Length`` header for you, and if it does this value
will be set to the number of *bytes* in the file. Errors may occur
if you open the file in *text mode*.
Response Status Codes
@@ -343,7 +368,7 @@ Response Status Codes
We can check the response status code::
>>> r = requests.get('http://httpbin.org/get')
>>> r = requests.get('https://httpbin.org/get')
>>> r.status_code
200
@@ -357,7 +382,7 @@ If we made a bad request (a 4XX client error or 5XX server error response), we
can raise it with
:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r = requests.get('https://httpbin.org/status/404')
>>> bad_r.status_code
404
@@ -393,7 +418,7 @@ We can view the server's response headers using a Python dictionary::
}
The dictionary is special, though: it's made just for HTTP headers. According to
`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names
`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names
are case-insensitive.
So, we can access the headers using any capitalization we want::
@@ -407,7 +432,7 @@ So, we can access the headers using any capitalization we want::
It is also special in that the server could have sent the same header multiple
times with different values, but requests combines them so they can be
represented in the dictionary within a single mapping, as per
`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:
`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_:
A recipient MAY combine multiple header fields with the same field name
into one "field-name: field-value" pair, without changing the semantics
@@ -428,7 +453,7 @@ If a response contains some Cookies, you can quickly access them::
To send your own cookies to the server, you can use the ``cookies``
parameter::
>>> url = 'http://httpbin.org/cookies'
>>> url = 'https://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
@@ -443,7 +468,7 @@ also be passed in to requests::
>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
>>> url = 'http://httpbin.org/cookies'
>>> url = 'https://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{"cookies": {"tasty_cookie": "yum"}}'
@@ -464,7 +489,7 @@ response.
For example, GitHub redirects all HTTP requests to HTTPS::
>>> r = requests.get('http://github.com')
>>> r = requests.get('http://github.com/')
>>> r.url
'https://github.com/'
@@ -479,7 +504,7 @@ For example, GitHub redirects all HTTP requests to HTTPS::
If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable
redirection handling with the ``allow_redirects`` parameter::
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r = requests.get('http://github.com/', allow_redirects=False)
>>> r.status_code
301
@@ -489,7 +514,7 @@ redirection handling with the ``allow_redirects`` parameter::
If you're using HEAD, you can enable redirection as well::
>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r = requests.head('http://github.com/', allow_redirects=True)
>>> r.url
'https://github.com/'
@@ -506,7 +531,7 @@ seconds with the ``timeout`` parameter. Nearly all production code should use
this parameter in nearly all requests. Failure to do so can cause your program
to hang indefinitely::
>>> requests.get('http://github.com', timeout=0.001)
>>> requests.get('https://github.com/', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

1
ext/LICENSE Normal file
View File

@@ -0,0 +1 @@
Copyright 2019 Kenneth Reitz. All rights reserved.

BIN
ext/flower-of-life.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
ext/kr-compressed.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

BIN
ext/kr.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

BIN
ext/psf-compressed.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
ext/psf.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

BIN
ext/requests-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

BIN
ext/ss-compressed.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

BIN
ext/ss.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

10
pyproject.toml Normal file
View File

@@ -0,0 +1,10 @@
[tool.isort]
profile = "black"
src_paths = ["src/requests", "test"]
honor_noqa = true
[tool.pytest.ini_options]
addopts = "--doctest-modules"
doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"
minversion = "6.2"
testpaths = ["tests"]

View File

@@ -1,2 +0,0 @@
[pytest]
addopts = -p no:warnings

View File

@@ -1,121 +0,0 @@
# -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
The other HTTP methods are supported - see `requests.api`. Full documentation
is at <http://python-requests.org>.
:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
"""
import urllib3
import chardet
import warnings
from .exceptions import RequestsDependencyWarning
def check_compatibility(urllib3_version, chardet_version):
urllib3_version = urllib3_version.split('.')
assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.
# Sometimes, urllib3 only reports its version as 16.1.
if len(urllib3_version) == 2:
urllib3_version.append('0')
# Check urllib3 for compatibility.
major, minor, patch = urllib3_version # noqa: F811
major, minor, patch = int(major), int(minor), int(patch)
# urllib3 >= 1.21.1, < 1.22
assert major == 1
assert minor >= 21
assert minor <= 22
# Check chardet for compatibility.
major, minor, patch = chardet_version.split('.')[:3]
major, minor, patch = int(major), int(minor), int(patch)
# chardet >= 3.0.2, < 3.1.0
assert major == 3
assert minor < 1
assert patch >= 2
# Check imported dependencies for compatibility.
try:
check_compatibility(urllib3.__version__, chardet.__version__)
except (AssertionError, ValueError):
warnings.warn("urllib3 ({0}) or chardet ({1}) doesn't match a supported "
"version!".format(urllib3.__version__, chardet.__version__),
RequestsDependencyWarning)
# Attempt to enable urllib3's SNI support, if possible
try:
from urllib3.contrib import pyopenssl
pyopenssl.inject_into_urllib3()
except ImportError:
pass
# urllib3's DependencyWarnings should be silenced.
from urllib3.exceptions import DependencyWarning
warnings.simplefilter('ignore', DependencyWarning)
from .__version__ import __title__, __description__, __url__, __version__
from .__version__ import __build__, __author__, __author_email__, __license__
from .__version__ import __copyright__, __cake__
from . import utils
from . import packages
from .models import Request, Response, PreparedRequest
from .api import request, get, head, post, patch, put, delete, options
from .sessions import session, Session
from .status_codes import codes
from .exceptions import (
RequestException, Timeout, URLRequired,
TooManyRedirects, HTTPError, ConnectionError,
FileModeWarning, ConnectTimeout, ReadTimeout
)
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
# FileModeWarnings go off per the default.
warnings.simplefilter('default', FileModeWarning, append=True)

View File

@@ -1,14 +0,0 @@
# .-. .-. .-. . . .-. .-. .-. .-.
# |( |- |.| | | |- `-. | `-.
# ' ' `-' `-`.`-' `-' `-' ' `-'
__title__ = 'requests'
__description__ = 'Python HTTP for Humans.'
__url__ = 'http://python-requests.org'
__version__ = '2.18.0'
__build__ = 0x021800
__author__ = 'Kenneth Reitz'
__author_email__ = 'me@kennethreitz.org'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2017 Kenneth Reitz'
__cake__ = u'\u2728 \U0001f370 \u2728'

View File

@@ -1,71 +0,0 @@
# -*- coding: utf-8 -*-
"""
requests.compat
~~~~~~~~~~~~~~~
This module handles import compatibility issues between Python 2 and
Python 3.
"""
import chardet
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplejson as json
except (ImportError, SyntaxError):
# simplejson does not support Python 3.2, it throws a SyntaxError
# because of u'...' Unicode literals.
import json
# ---------
# Specifics
# ---------
if is_py2:
from urllib import (
quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,
proxy_bypass, proxy_bypass_environment, getproxies_environment)
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
from urllib2 import parse_http_list
import cookielib
from Cookie import Morsel
from StringIO import StringIO
from urllib3.packages.ordered_dict import OrderedDict
builtin_str = str
bytes = str
str = unicode
basestring = basestring
numeric_types = (int, long, float)
integer_types = (int, long)
elif is_py3:
from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag
from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment
from http import cookiejar as cookielib
from http.cookies import Morsel
from io import StringIO
from collections import OrderedDict
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)

View File

@@ -1,111 +0,0 @@
"""Module containing bug report helper(s)."""
from __future__ import print_function
import json
import platform
import sys
import ssl
import urllib3
import chardet
from . import __version__ as requests_version
try:
from .packages.urllib3.contrib import pyopenssl
except ImportError:
pyopenssl = None
OpenSSL = None
cryptography = None
else:
import OpenSSL
import cryptography
def _implementation():
"""Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 2.7.5 it will return
{'name': 'CPython', 'version': '2.7.5'}.
This function works best on CPython and PyPy: in particular, it probably
doesn't work for Jython or IronPython. Future investigation should be done
to work out the correct shape of the code for those platforms.
"""
implementation = platform.python_implementation()
if implementation == 'CPython':
implementation_version = platform.python_version()
elif implementation == 'PyPy':
implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
sys.pypy_version_info.minor,
sys.pypy_version_info.micro)
if sys.pypy_version_info.releaselevel != 'final':
implementation_version = ''.join([
implementation_version, sys.pypy_version_info.releaselevel
])
elif implementation == 'Jython':
implementation_version = platform.python_version() # Complete Guess
elif implementation == 'IronPython':
implementation_version = platform.python_version() # Complete Guess
else:
implementation_version = 'Unknown'
return {'name': implementation, 'version': implementation_version}
def info():
"""Generate information for a bug report."""
try:
platform_info = {
'system': platform.system(),
'release': platform.release(),
}
except IOError:
platform_info = {
'system': 'Unknown',
'release': 'Unknown',
}
implementation_info = _implementation()
urllib3_info = {'version': urllib3.__version__}
chardet_info = {'version': chardet.__version__}
pyopenssl_info = {
'version': None,
'openssl_version': '',
}
if OpenSSL:
pyopenssl_info = {
'version': OpenSSL.__version__,
'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER,
}
cryptography_info = {
'version': getattr(cryptography, '__version__', ''),
}
return {
'platform': platform_info,
'implementation': implementation_info,
'system_ssl': {
'version': '%x' % ssl.OPENSSL_VERSION_NUMBER,
},
'using_pyopenssl': pyopenssl is not None,
'pyOpenSSL': pyopenssl_info,
'urllib3': urllib3_info,
'chardet': chardet_info,
'cryptography': cryptography_info,
'requests': {
'version': requests_version,
},
}
def main():
"""Pretty-print the bug information as JSON."""
print(json.dumps(info(), sort_keys=True, indent=2))
if __name__ == '__main__':
main()

View File

@@ -1,14 +0,0 @@
import sys
# This code exists for backwards compatibility reasons.
# I don't like it either. Just look the other way. :)
for package in ('urllib3', 'idna', 'chardet'):
locals()[package] = __import__(package)
# This traversal is apparently necessary such that the identities are
# preserved (requests.packages.urllib3.* is urllib3.*)
for mod in list(sys.modules):
if mod == package or mod.startswith(package + '.'):
sys.modules['requests.packages.' + mod] = sys.modules[mod]
# Kinda cool, though, right?

View File

@@ -1,91 +0,0 @@
# -*- coding: utf-8 -*-
from .structures import LookupDict
_codes = {
# Informational.
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', ''),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', ''),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),
}
codes = LookupDict(name='status_codes')
for code, titles in _codes.items():
for title in titles:
setattr(codes, title, code)
if not title.startswith(('\\', '/')):
setattr(codes, title.upper(), code)

7
requirements-dev.txt Normal file
View File

@@ -0,0 +1,7 @@
-e .[socks]
pytest>=2.8.0,<9
pytest-cov
pytest-httpbin==2.0.0
httpbin~=0.10.0
trustme
wheel

View File

@@ -1,16 +0,0 @@
-e .[socks]
pytest>=2.8.0
codecov
pytest-httpbin==0.0.7
pytest-mock
pytest-cov
pytest-xdist
alabaster
readme_renderer
Sphinx<=1.5.5
PySocks
setuptools>=18.5
docutils
flake8
tox
detox

View File

@@ -1,2 +1,17 @@
[bdist_wheel]
universal = 1
[metadata]
license_file = LICENSE
provides-extra =
socks
use_chardet_on_py3
requires-dist =
certifi>=2017.4.17
charset_normalizer>=2,<4
idna>=2.5,<4
urllib3>=1.21.1,<3
[flake8]
ignore = E203, E501, W503
per-file-ignores =
src/requests/__init__.py:E402, F401
src/requests/compat.py:E402, F401
tests/compat.py:F401

139
setup.py
View File

@@ -1,26 +1,44 @@
#!/usr/bin/env python
import os
import re
import sys
from codecs import open
from setuptools import setup
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 8)
if CURRENT_PYTHON < REQUIRED_PYTHON:
sys.stderr.write(
"""
==========================
Unsupported Python version
==========================
This version of Requests requires at least Python {}.{}, but
you're trying to install it on Python {}.{}. To resolve this,
consider upgrading to a supported Python version.
If you can't upgrade your Python version, you'll need to
pin to an older version of Requests (<2.32.0).
""".format(
*(REQUIRED_PYTHON + CURRENT_PYTHON)
)
)
sys.exit(1)
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]
user_options = [("pytest-args=", "a", "Arguments to pass into py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
try:
from multiprocessing import cpu_count
self.pytest_args = ['-n', str(cpu_count()), '--boxed']
self.pytest_args = ["-n", str(cpu_count()), "--boxed"]
except (ImportError, NotImplementedError):
self.pytest_args = ['-n', '1', '--boxed']
self.pytest_args = ["-n", "1", "--boxed"]
def finalize_options(self):
TestCommand.finalize_options(self)
@@ -33,69 +51,82 @@ class PyTest(TestCommand):
errno = pytest.main(self.pytest_args)
sys.exit(errno)
# 'setup.py publish' shortcut.
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wheel')
os.system('twine upload dist/*')
if sys.argv[-1] == "publish":
os.system("python setup.py sdist bdist_wheel")
os.system("twine upload dist/*")
sys.exit()
packages = ['requests']
requires = [
'chardet>=3.0.2,<3.1.0',
'idna>=2.5,<2.6',
'urllib3>=1.21.1,<1.22',
'certifi>=2017.4.17'
"charset_normalizer>=2,<4",
"idna>=2.5,<4",
"urllib3>=1.21.1,<3",
"certifi>=2017.4.17",
]
test_requirements = [
"pytest-httpbin==2.0.0",
"pytest-cov",
"pytest-mock",
"pytest-xdist",
"PySocks>=1.5.6, !=1.5.7",
"pytest>=3",
]
test_requirements = ['pytest-httpbin==0.0.7', 'pytest-cov', 'pytest-mock', 'pytest-xdist', 'PySocks>=1.5.6, !=1.5.7', 'pytest>=2.8.0']
about = {}
with open(os.path.join(here, 'requests', '__version__.py'), 'r', 'utf-8') as f:
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "src", "requests", "__version__.py"), "r", "utf-8") as f:
exec(f.read(), about)
with open('README.rst', 'r', 'utf-8') as f:
with open("README.md", "r", "utf-8") as f:
readme = f.read()
with open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name=about['__title__'],
version=about['__version__'],
description=about['__description__'],
long_description=readme + '\n\n' + history,
author=about['__author__'],
author_email=about['__author_email__'],
url=about['__url__'],
packages=packages,
package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']},
package_dir={'requests': 'requests'},
name=about["__title__"],
version=about["__version__"],
description=about["__description__"],
long_description=readme,
long_description_content_type="text/markdown",
author=about["__author__"],
author_email=about["__author_email__"],
url=about["__url__"],
packages=["requests"],
package_data={"": ["LICENSE", "NOTICE"]},
package_dir={"": "src"},
include_package_data=True,
python_requires=">=3.8",
install_requires=requires,
license=about['__license__'],
license=about["__license__"],
zip_safe=False,
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy'
),
cmdclass={'test': PyTest},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries",
],
cmdclass={"test": PyTest},
tests_require=test_requirements,
extras_require={
'security': ['pyOpenSSL>=0.14', 'cryptography>=1.3.4', 'idna>=2.0.0'],
'socks': ['PySocks>=1.5.6, !=1.5.7'],
'socks:sys_platform == "win32" and (python_version == "2.7" or python_version == "2.6")': ['win_inet_pton'],
"security": [],
"socks": ["PySocks>=1.5.6, !=1.5.7"],
"use_chardet_on_py3": ["chardet>=3.0.2,<6"],
},
project_urls={
"Documentation": "https://requests.readthedocs.io",
"Source": "https://github.com/psf/requests",
},
)

184
src/requests/__init__.py Normal file
View File

@@ -0,0 +1,184 @@
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings.
Basic GET usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> b'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('https://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key1": "value1",
"key2": "value2"
},
...
}
The other HTTP methods are supported - see `requests.api`. Full documentation
is at <https://requests.readthedocs.io>.
:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
"""
import warnings
import urllib3
from .exceptions import RequestsDependencyWarning
try:
from charset_normalizer import __version__ as charset_normalizer_version
except ImportError:
charset_normalizer_version = None
try:
from chardet import __version__ as chardet_version
except ImportError:
chardet_version = None
def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):
urllib3_version = urllib3_version.split(".")
assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git.
# Sometimes, urllib3 only reports its version as 16.1.
if len(urllib3_version) == 2:
urllib3_version.append("0")
# Check urllib3 for compatibility.
major, minor, patch = urllib3_version # noqa: F811
major, minor, patch = int(major), int(minor), int(patch)
# urllib3 >= 1.21.1
assert major >= 1
if major == 1:
assert minor >= 21
# Check charset_normalizer for compatibility.
if chardet_version:
major, minor, patch = chardet_version.split(".")[:3]
major, minor, patch = int(major), int(minor), int(patch)
# chardet_version >= 3.0.2, < 6.0.0
assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)
elif charset_normalizer_version:
major, minor, patch = charset_normalizer_version.split(".")[:3]
major, minor, patch = int(major), int(minor), int(patch)
# charset_normalizer >= 2.0.0 < 4.0.0
assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)
else:
warnings.warn(
"Unable to find acceptable character detection dependency "
"(chardet or charset_normalizer).",
RequestsDependencyWarning,
)
def _check_cryptography(cryptography_version):
# cryptography < 1.3.4
try:
cryptography_version = list(map(int, cryptography_version.split(".")))
except ValueError:
return
if cryptography_version < [1, 3, 4]:
warning = "Old version of cryptography ({}) may cause slowdown.".format(
cryptography_version
)
warnings.warn(warning, RequestsDependencyWarning)
# Check imported dependencies for compatibility.
try:
check_compatibility(
urllib3.__version__, chardet_version, charset_normalizer_version
)
except (AssertionError, ValueError):
warnings.warn(
"urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "
"version!".format(
urllib3.__version__, chardet_version, charset_normalizer_version
),
RequestsDependencyWarning,
)
# Attempt to enable urllib3's fallback for SNI support
# if the standard library doesn't support SNI or the
# 'ssl' library isn't available.
try:
try:
import ssl
except ImportError:
ssl = None
if not getattr(ssl, "HAS_SNI", False):
from urllib3.contrib import pyopenssl
pyopenssl.inject_into_urllib3()
# Check cryptography version
from cryptography import __version__ as cryptography_version
_check_cryptography(cryptography_version)
except ImportError:
pass
# urllib3's DependencyWarnings should be silenced.
from urllib3.exceptions import DependencyWarning
warnings.simplefilter("ignore", DependencyWarning)
# Set default logging handler to avoid "No handler found" warnings.
import logging
from logging import NullHandler
from . import packages, utils
from .__version__ import (
__author__,
__author_email__,
__build__,
__cake__,
__copyright__,
__description__,
__license__,
__title__,
__url__,
__version__,
)
from .api import delete, get, head, options, patch, post, put, request
from .exceptions import (
ConnectionError,
ConnectTimeout,
FileModeWarning,
HTTPError,
JSONDecodeError,
ReadTimeout,
RequestException,
Timeout,
TooManyRedirects,
URLRequired,
)
from .models import PreparedRequest, Request, Response
from .sessions import Session, session
from .status_codes import codes
logging.getLogger(__name__).addHandler(NullHandler())
# FileModeWarnings go off per the default.
warnings.simplefilter("default", FileModeWarning, append=True)

View File

@@ -0,0 +1,14 @@
# .-. .-. .-. . . .-. .-. .-. .-.
# |( |- |.| | | |- `-. | `-.
# ' ' `-' `-`.`-' `-' `-' ' `-'
__title__ = "requests"
__description__ = "Python HTTP for Humans."
__url__ = "https://requests.readthedocs.io"
__version__ = "2.32.1"
__build__ = 0x023201
__author__ = "Kenneth Reitz"
__author_email__ = "me@kennethreitz.org"
__license__ = "Apache-2.0"
__copyright__ = "Copyright Kenneth Reitz"
__cake__ = "\u2728 \U0001f370 \u2728"

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests._internal_utils
~~~~~~~~~~~~~~
@@ -7,11 +5,24 @@ requests._internal_utils
Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
"""
import re
from .compat import is_py2, builtin_str, str
from .compat import builtin_str
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")
_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")
_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")
_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR)
_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE)
HEADER_VALIDATORS = {
bytes: _HEADER_VALIDATORS_BYTE,
str: _HEADER_VALIDATORS_STR,
}
def to_native_string(string, encoding='ascii'):
def to_native_string(string, encoding="ascii"):
"""Given a string object, regardless of type, returns a representation of
that string in the native string type, encoding and decoding where
necessary. This assumes ASCII unless told otherwise.
@@ -19,10 +30,7 @@ def to_native_string(string, encoding='ascii'):
if isinstance(string, builtin_str):
out = string
else:
if is_py2:
out = string.encode(encoding)
else:
out = string.decode(encoding)
out = string.decode(encoding)
return out
@@ -36,7 +44,7 @@ def unicode_is_ascii(u_string):
"""
assert isinstance(u_string, str)
try:
u_string.encode('ascii')
u_string.encode("ascii")
return True
except UnicodeEncodeError:
return False

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.adapters
~~~~~~~~~~~~~~~~~
@@ -9,54 +7,123 @@ and maintain connections.
"""
import os.path
import socket
import socket # noqa: F401
import typing
from urllib3.poolmanager import PoolManager, proxy_from_url
from urllib3.response import HTTPResponse
from urllib3.util import Timeout as TimeoutSauce
from urllib3.util.retry import Retry
from urllib3.exceptions import ClosedPoolError
from urllib3.exceptions import ConnectTimeoutError
from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError
from urllib3.exceptions import HTTPError as _HTTPError
from urllib3.exceptions import MaxRetryError
from urllib3.exceptions import NewConnectionError
from urllib3.exceptions import InvalidHeader as _InvalidHeader
from urllib3.exceptions import (
LocationValueError,
MaxRetryError,
NewConnectionError,
ProtocolError,
)
from urllib3.exceptions import ProxyError as _ProxyError
from urllib3.exceptions import ProtocolError
from urllib3.exceptions import ReadTimeoutError
from urllib3.exceptions import ReadTimeoutError, ResponseError
from urllib3.exceptions import SSLError as _SSLError
from urllib3.exceptions import ResponseError
from urllib3.poolmanager import PoolManager, proxy_from_url
from urllib3.util import Timeout as TimeoutSauce
from urllib3.util import parse_url
from urllib3.util.retry import Retry
from urllib3.util.ssl_ import create_urllib3_context
from .models import Response
from .compat import urlparse, basestring
from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,
prepend_scheme_if_needed, get_auth_from_url, urldefragauth,
select_proxy)
from .structures import CaseInsensitiveDict
from .cookies import extract_cookies_to_jar
from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
ProxyError, RetryError, InvalidSchema)
from .auth import _basic_auth_str
from .compat import basestring, urlparse
from .cookies import extract_cookies_to_jar
from .exceptions import (
ConnectionError,
ConnectTimeout,
InvalidHeader,
InvalidProxyURL,
InvalidSchema,
InvalidURL,
ProxyError,
ReadTimeout,
RetryError,
SSLError,
)
from .models import Response
from .structures import CaseInsensitiveDict
from .utils import (
DEFAULT_CA_BUNDLE_PATH,
extract_zipped_paths,
get_auth_from_url,
get_encoding_from_headers,
prepend_scheme_if_needed,
select_proxy,
urldefragauth,
)
try:
from urllib3.contrib.socks import SOCKSProxyManager
except ImportError:
def SOCKSProxyManager(*args, **kwargs):
raise InvalidSchema("Missing dependencies for SOCKS support.")
if typing.TYPE_CHECKING:
from .models import PreparedRequest
DEFAULT_POOLBLOCK = False
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0
DEFAULT_POOL_TIMEOUT = None
_preloaded_ssl_context = create_urllib3_context()
_preloaded_ssl_context.load_verify_locations(
extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
)
class BaseAdapter(object):
def _urllib3_request_context(
request: "PreparedRequest",
verify: "bool | str | None",
client_cert: "typing.Tuple[str, str] | str | None",
) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])":
host_params = {}
pool_kwargs = {}
parsed_request_url = urlparse(request.url)
scheme = parsed_request_url.scheme.lower()
port = parsed_request_url.port
cert_reqs = "CERT_REQUIRED"
if verify is False:
cert_reqs = "CERT_NONE"
elif verify is True:
pool_kwargs["ssl_context"] = _preloaded_ssl_context
elif isinstance(verify, str):
if not os.path.isdir(verify):
pool_kwargs["ca_certs"] = verify
else:
pool_kwargs["ca_cert_dir"] = verify
pool_kwargs["cert_reqs"] = cert_reqs
if client_cert is not None:
if isinstance(client_cert, tuple) and len(client_cert) == 2:
pool_kwargs["cert_file"] = client_cert[0]
pool_kwargs["key_file"] = client_cert[1]
else:
# According to our docs, we allow users to specify just the client
# cert path
pool_kwargs["cert_file"] = client_cert
host_params = {
"scheme": scheme,
"host": parsed_request_url.hostname,
"port": port,
}
return host_params, pool_kwargs
class BaseAdapter:
"""The Base Transport Adapter"""
def __init__(self):
super(BaseAdapter, self).__init__()
super().__init__()
def send(self, request, stream=False, timeout=None, verify=True,
cert=None, proxies=None):
def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
@@ -104,12 +171,22 @@ class HTTPAdapter(BaseAdapter):
>>> a = requests.adapters.HTTPAdapter(max_retries=3)
>>> s.mount('http://', a)
"""
__attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',
'_pool_block']
def __init__(self, pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK):
__attrs__ = [
"max_retries",
"config",
"_pool_connections",
"_pool_maxsize",
"_pool_block",
]
def __init__(
self,
pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE,
max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK,
):
if max_retries == DEFAULT_RETRIES:
self.max_retries = Retry(0, read=False)
else:
@@ -117,7 +194,7 @@ class HTTPAdapter(BaseAdapter):
self.config = {}
self.proxy_manager = {}
super(HTTPAdapter, self).__init__()
super().__init__()
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
@@ -126,8 +203,7 @@ class HTTPAdapter(BaseAdapter):
self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
def __getstate__(self):
return dict((attr, getattr(self, attr, None)) for attr in
self.__attrs__)
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
def __setstate__(self, state):
# Can't handle by adding 'proxy_manager' to self.__attrs__ because
@@ -138,10 +214,13 @@ class HTTPAdapter(BaseAdapter):
for attr, value in state.items():
setattr(self, attr, value)
self.init_poolmanager(self._pool_connections, self._pool_maxsize,
block=self._pool_block)
self.init_poolmanager(
self._pool_connections, self._pool_maxsize, block=self._pool_block
)
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
def init_poolmanager(
self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs
):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
@@ -158,8 +237,12 @@ class HTTPAdapter(BaseAdapter):
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs)
self.poolmanager = PoolManager(
num_pools=connections,
maxsize=maxsize,
block=block,
**pool_kwargs,
)
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
@@ -175,7 +258,7 @@ class HTTPAdapter(BaseAdapter):
"""
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
elif proxy.lower().startswith('socks'):
elif proxy.lower().startswith("socks"):
username, password = get_auth_from_url(proxy)
manager = self.proxy_manager[proxy] = SOCKSProxyManager(
proxy,
@@ -184,7 +267,7 @@ class HTTPAdapter(BaseAdapter):
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs
**proxy_kwargs,
)
else:
proxy_headers = self.proxy_headers(proxy)
@@ -194,7 +277,8 @@ class HTTPAdapter(BaseAdapter):
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
**proxy_kwargs,
)
return manager
@@ -210,29 +294,29 @@ class HTTPAdapter(BaseAdapter):
to a CA bundle to use
:param cert: The SSL certificate to verify.
"""
if url.lower().startswith('https') and verify:
if url.lower().startswith("https") and verify:
conn.cert_reqs = "CERT_REQUIRED"
cert_loc = None
# Allow self-specified cert location.
# Only load the CA certificates if 'verify' is a string indicating the CA bundle to use.
# Otherwise, if verify is a boolean, we don't load anything since
# the connection will be using a context with the default certificates already loaded,
# and this avoids a call to the slow load_verify_locations()
if verify is not True:
# `verify` must be a str with a path then
cert_loc = verify
if not cert_loc:
cert_loc = DEFAULT_CA_BUNDLE_PATH
if not os.path.exists(cert_loc):
raise OSError(
f"Could not find a suitable TLS CA certificate bundle, "
f"invalid path: {cert_loc}"
)
if not cert_loc or not os.path.exists(cert_loc):
raise IOError("Could not find a suitable TLS CA certificate bundle, "
"invalid path: {0}".format(cert_loc))
conn.cert_reqs = 'CERT_REQUIRED'
if not os.path.isdir(cert_loc):
conn.ca_certs = cert_loc
else:
conn.ca_cert_dir = cert_loc
if not os.path.isdir(cert_loc):
conn.ca_certs = cert_loc
else:
conn.ca_cert_dir = cert_loc
else:
conn.cert_reqs = 'CERT_NONE'
conn.cert_reqs = "CERT_NONE"
conn.ca_certs = None
conn.ca_cert_dir = None
@@ -244,11 +328,14 @@ class HTTPAdapter(BaseAdapter):
conn.cert_file = cert
conn.key_file = None
if conn.cert_file and not os.path.exists(conn.cert_file):
raise IOError("Could not find the TLS certificate file, "
"invalid path: {0}".format(conn.cert_file))
raise OSError(
f"Could not find the TLS certificate file, "
f"invalid path: {conn.cert_file}"
)
if conn.key_file and not os.path.exists(conn.key_file):
raise IOError("Could not find the TLS key file, "
"invalid path: {0}".format(conn.key_file))
raise OSError(
f"Could not find the TLS key file, invalid path: {conn.key_file}"
)
def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
@@ -263,10 +350,10 @@ class HTTPAdapter(BaseAdapter):
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
response.status_code = getattr(resp, "status", None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
@@ -274,7 +361,7 @@ class HTTPAdapter(BaseAdapter):
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
response.url = req.url.decode("utf-8")
else:
response.url = req.url
@@ -287,6 +374,35 @@ class HTTPAdapter(BaseAdapter):
return response
def _get_connection(self, request, verify, proxies=None, cert=None):
# Replace the existing get_connection without breaking things and
# ensure that TLS settings are considered when we interact with
# urllib3 HTTP Pools
proxy = select_proxy(request.url, proxies)
try:
host_params, pool_kwargs = _urllib3_request_context(request, verify, cert)
except ValueError as e:
raise InvalidURL(e, request=request)
if proxy:
proxy = prepend_scheme_if_needed(proxy, "http")
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise InvalidProxyURL(
"Please check proxy URL. It is malformed "
"and could be missing the host."
)
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_host(
**host_params, pool_kwargs=pool_kwargs
)
else:
# Only scheme should be lower case
conn = self.poolmanager.connection_from_host(
**host_params, pool_kwargs=pool_kwargs
)
return conn
def get_connection(self, url, proxies=None):
"""Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
@@ -299,7 +415,13 @@ class HTTPAdapter(BaseAdapter):
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy = prepend_scheme_if_needed(proxy, "http")
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise InvalidProxyURL(
"Please check proxy URL. It is malformed "
"and could be missing the host."
)
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
@@ -337,13 +459,16 @@ class HTTPAdapter(BaseAdapter):
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
is_proxied_http_request = (proxy and scheme != 'https')
is_proxied_http_request = proxy and scheme != "https"
using_socks_proxy = False
if proxy:
proxy_scheme = urlparse(proxy).scheme.lower()
using_socks_proxy = proxy_scheme.startswith('socks')
using_socks_proxy = proxy_scheme.startswith("socks")
url = request.path_url
if url.startswith("//"): # Don't confuse urllib3
url = f"/{url.lstrip('/')}"
if is_proxied_http_request and not using_socks_proxy:
url = urldefragauth(request.url)
@@ -373,19 +498,20 @@ class HTTPAdapter(BaseAdapter):
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxies: The url of the proxy being used for this request.
:param proxy: The url of the proxy being used for this request.
:rtype: dict
"""
headers = {}
username, password = get_auth_from_url(proxy)
if username:
headers['Proxy-Authorization'] = _basic_auth_str(username,
password)
headers["Proxy-Authorization"] = _basic_auth_str(username, password)
return headers
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
@@ -402,91 +528,54 @@ class HTTPAdapter(BaseAdapter):
:rtype: requests.Response
"""
conn = self.get_connection(request.url, proxies)
try:
conn = self._get_connection(request, verify, proxies=proxies, cert=cert)
except LocationValueError as e:
raise InvalidURL(e, request=request)
self.cert_verify(conn, request.url, verify, cert)
url = self.request_url(request, proxies)
self.add_headers(request)
self.add_headers(
request,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
)
chunked = not (request.body is None or 'Content-Length' in request.headers)
chunked = not (request.body is None or "Content-Length" in request.headers)
if isinstance(timeout, tuple):
try:
connect, read = timeout
timeout = TimeoutSauce(connect=connect, read=read)
except ValueError as e:
# this may raise a string formatting error.
err = ("Invalid timeout {0}. Pass a (connect, read) "
"timeout tuple, or a single float to set "
"both timeouts to the same value".format(timeout))
raise ValueError(err)
except ValueError:
raise ValueError(
f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "
f"or a single float to set both timeouts to the same value."
)
elif isinstance(timeout, TimeoutSauce):
pass
else:
timeout = TimeoutSauce(connect=timeout, read=timeout)
try:
if not chunked:
resp = conn.urlopen(
method=request.method,
url=url,
body=request.body,
headers=request.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.max_retries,
timeout=timeout
)
resp = conn.urlopen(
method=request.method,
url=url,
body=request.body,
headers=request.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.max_retries,
timeout=timeout,
chunked=chunked,
)
# Send the request.
else:
if hasattr(conn, 'proxy_pool'):
conn = conn.proxy_pool
low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)
try:
low_conn.putrequest(request.method,
url,
skip_accept_encoding=True)
for header, value in request.headers.items():
low_conn.putheader(header, value)
low_conn.endheaders()
for i in request.body:
low_conn.send(hex(len(i))[2:].encode('utf-8'))
low_conn.send(b'\r\n')
low_conn.send(i)
low_conn.send(b'\r\n')
low_conn.send(b'0\r\n\r\n')
# Receive the response from the server
try:
# For Python 2.7+ versions, use buffering of HTTP
# responses
r = low_conn.getresponse(buffering=True)
except TypeError:
# For compatibility with Python 2.6 versions and back
r = low_conn.getresponse()
resp = HTTPResponse.from_httplib(
r,
pool=conn,
connection=low_conn,
preload_content=False,
decode_content=False
)
except:
# If we hit any problems here, clean up the connection.
# Then, reraise so that we can handle the actual exception.
low_conn.close()
raise
except (ProtocolError, socket.error) as err:
except (ProtocolError, OSError) as err:
raise ConnectionError(err, request=request)
except MaxRetryError as e:
@@ -501,6 +590,10 @@ class HTTPAdapter(BaseAdapter):
if isinstance(e.reason, _ProxyError):
raise ProxyError(e, request=request)
if isinstance(e.reason, _SSLError):
# This branch is for urllib3 v1.22 and later.
raise SSLError(e, request=request)
raise ConnectionError(e, request=request)
except ClosedPoolError as e:
@@ -511,9 +604,12 @@ class HTTPAdapter(BaseAdapter):
except (_SSLError, _HTTPError) as e:
if isinstance(e, _SSLError):
# This branch is for urllib3 versions earlier than v1.22
raise SSLError(e, request=request)
elif isinstance(e, ReadTimeoutError):
raise ReadTimeout(e, request=request)
elif isinstance(e, _InvalidHeader):
raise InvalidHeader(e, request=request)
else:
raise

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
@@ -16,16 +14,18 @@ from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
@@ -47,7 +47,8 @@ def request(method, url, **kwargs):
Usage::
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
>>> req = requests.request('GET', 'https://httpbin.org/get')
>>> req
<Response [200]>
"""
@@ -62,14 +63,14 @@ def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('get', url, params=params, **kwargs)
return request("get", url, params=params, **kwargs)
def options(url, **kwargs):
@@ -81,63 +82,67 @@ def options(url, **kwargs):
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('options', url, **kwargs)
return request("options", url, **kwargs)
def head(url, **kwargs):
r"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:param \*\*kwargs: Optional arguments that ``request`` takes. If
`allow_redirects` is not provided, it will be set to `False` (as
opposed to the default :meth:`request` behavior).
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return request('head', url, **kwargs)
kwargs.setdefault("allow_redirects", False)
return request("head", url, **kwargs)
def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
return request("post", url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('put', url, data=data, **kwargs)
return request("put", url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
r"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('patch', url, data=data, **kwargs)
return request("patch", url, data=data, **kwargs)
def delete(url, **kwargs):
@@ -149,4 +154,4 @@ def delete(url, **kwargs):
:rtype: requests.Response
"""
return request('delete', url, **kwargs)
return request("delete", url, **kwargs)

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.auth
~~~~~~~~~~~~~
@@ -7,22 +5,21 @@ requests.auth
This module contains the authentication handlers for Requests.
"""
import hashlib
import os
import re
import time
import hashlib
import threading
import time
import warnings
from base64 import b64encode
from .compat import urlparse, str, basestring
from .cookies import extract_cookies_to_jar
from ._internal_utils import to_native_string
from .compat import basestring, str, urlparse
from .cookies import extract_cookies_to_jar
from .utils import parse_dict_header
CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"
CONTENT_TYPE_MULTI_PART = "multipart/form-data"
def _basic_auth_str(username, password):
@@ -38,7 +35,7 @@ def _basic_auth_str(username, password):
if not isinstance(username, basestring):
warnings.warn(
"Non-string usernames will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({0!r}) to "
"3.0.0. Please convert the object you've passed in ({!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(username),
category=DeprecationWarning,
@@ -48,32 +45,32 @@ def _basic_auth_str(username, password):
if not isinstance(password, basestring):
warnings.warn(
"Non-string passwords will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({0!r}) to "
"3.0.0. Please convert the object you've passed in ({!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(password),
"problems.".format(type(password)),
category=DeprecationWarning,
)
password = str(password)
# -- End Removal --
if isinstance(username, str):
username = username.encode('latin1')
username = username.encode("latin1")
if isinstance(password, str):
password = password.encode('latin1')
password = password.encode("latin1")
authstr = 'Basic ' + to_native_string(
b64encode(b':'.join((username, password))).strip()
authstr = "Basic " + to_native_string(
b64encode(b":".join((username, password))).strip()
)
return authstr
class AuthBase(object):
class AuthBase:
"""Base class that all auth implementations derive from"""
def __call__(self, r):
raise NotImplementedError('Auth hooks must be callable.')
raise NotImplementedError("Auth hooks must be callable.")
class HTTPBasicAuth(AuthBase):
@@ -84,16 +81,18 @@ class HTTPBasicAuth(AuthBase):
self.password = password
def __eq__(self, other):
return all([
self.username == getattr(other, 'username', None),
self.password == getattr(other, 'password', None)
])
return all(
[
self.username == getattr(other, "username", None),
self.password == getattr(other, "password", None),
]
)
def __ne__(self, other):
return not self == other
def __call__(self, r):
r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
r.headers["Authorization"] = _basic_auth_str(self.username, self.password)
return r
@@ -101,7 +100,7 @@ class HTTPProxyAuth(HTTPBasicAuth):
"""Attaches HTTP Proxy Authentication to a given Request object."""
def __call__(self, r):
r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)
return r
@@ -116,9 +115,9 @@ class HTTPDigestAuth(AuthBase):
def init_per_thread_state(self):
# Ensure state is initialized just once per-thread
if not hasattr(self._thread_local, 'init'):
if not hasattr(self._thread_local, "init"):
self._thread_local.init = True
self._thread_local.last_nonce = ''
self._thread_local.last_nonce = ""
self._thread_local.nonce_count = 0
self._thread_local.chal = {}
self._thread_local.pos = None
@@ -129,32 +128,52 @@ class HTTPDigestAuth(AuthBase):
:rtype: str
"""
realm = self._thread_local.chal['realm']
nonce = self._thread_local.chal['nonce']
qop = self._thread_local.chal.get('qop')
algorithm = self._thread_local.chal.get('algorithm')
opaque = self._thread_local.chal.get('opaque')
realm = self._thread_local.chal["realm"]
nonce = self._thread_local.chal["nonce"]
qop = self._thread_local.chal.get("qop")
algorithm = self._thread_local.chal.get("algorithm")
opaque = self._thread_local.chal.get("opaque")
hash_utf8 = None
if algorithm is None:
_algorithm = 'MD5'
_algorithm = "MD5"
else:
_algorithm = algorithm.upper()
# lambdas assume digest modules are imported at the top level
if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':
if _algorithm == "MD5" or _algorithm == "MD5-SESS":
def md5_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
x = x.encode("utf-8")
return hashlib.md5(x).hexdigest()
hash_utf8 = md5_utf8
elif _algorithm == 'SHA':
elif _algorithm == "SHA":
def sha_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
x = x.encode("utf-8")
return hashlib.sha1(x).hexdigest()
hash_utf8 = sha_utf8
KD = lambda s, d: hash_utf8("%s:%s" % (s, d))
hash_utf8 = sha_utf8
elif _algorithm == "SHA-256":
def sha256_utf8(x):
if isinstance(x, str):
x = x.encode("utf-8")
return hashlib.sha256(x).hexdigest()
hash_utf8 = sha256_utf8
elif _algorithm == "SHA-512":
def sha512_utf8(x):
if isinstance(x, str):
x = x.encode("utf-8")
return hashlib.sha512(x).hexdigest()
hash_utf8 = sha512_utf8
KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731
if hash_utf8 is None:
return None
@@ -165,10 +184,10 @@ class HTTPDigestAuth(AuthBase):
#: path is request-uri defined in RFC 2616 which should not be empty
path = p_parsed.path or "/"
if p_parsed.query:
path += '?' + p_parsed.query
path += f"?{p_parsed.query}"
A1 = '%s:%s:%s' % (self.username, realm, self.password)
A2 = '%s:%s' % (method, path)
A1 = f"{self.username}:{realm}:{self.password}"
A2 = f"{method}:{path}"
HA1 = hash_utf8(A1)
HA2 = hash_utf8(A2)
@@ -177,22 +196,20 @@ class HTTPDigestAuth(AuthBase):
self._thread_local.nonce_count += 1
else:
self._thread_local.nonce_count = 1
ncvalue = '%08x' % self._thread_local.nonce_count
s = str(self._thread_local.nonce_count).encode('utf-8')
s += nonce.encode('utf-8')
s += time.ctime().encode('utf-8')
ncvalue = f"{self._thread_local.nonce_count:08x}"
s = str(self._thread_local.nonce_count).encode("utf-8")
s += nonce.encode("utf-8")
s += time.ctime().encode("utf-8")
s += os.urandom(8)
cnonce = (hashlib.sha1(s).hexdigest()[:16])
if _algorithm == 'MD5-SESS':
HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
cnonce = hashlib.sha1(s).hexdigest()[:16]
if _algorithm == "MD5-SESS":
HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}")
if not qop:
respdig = KD(HA1, "%s:%s" % (nonce, HA2))
elif qop == 'auth' or 'auth' in qop.split(','):
noncebit = "%s:%s:%s:%s:%s" % (
nonce, ncvalue, cnonce, 'auth', HA2
)
respdig = KD(HA1, f"{nonce}:{HA2}")
elif qop == "auth" or "auth" in qop.split(","):
noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}"
respdig = KD(HA1, noncebit)
else:
# XXX handle auth-int.
@@ -201,18 +218,20 @@ class HTTPDigestAuth(AuthBase):
self._thread_local.last_nonce = nonce
# XXX should the partial digests be encoded too?
base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
'response="%s"' % (self.username, realm, nonce, path, respdig)
base = (
f'username="{self.username}", realm="{realm}", nonce="{nonce}", '
f'uri="{path}", response="{respdig}"'
)
if opaque:
base += ', opaque="%s"' % opaque
base += f', opaque="{opaque}"'
if algorithm:
base += ', algorithm="%s"' % algorithm
base += f', algorithm="{algorithm}"'
if entdig:
base += ', digest="%s"' % entdig
base += f', digest="{entdig}"'
if qop:
base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'
return 'Digest %s' % (base)
return f"Digest {base}"
def handle_redirect(self, r, **kwargs):
"""Reset num_401_calls counter on redirects."""
@@ -227,7 +246,7 @@ class HTTPDigestAuth(AuthBase):
"""
# If response is not 4xx, do not auth
# See https://github.com/requests/requests/issues/3772
# See https://github.com/psf/requests/issues/3772
if not 400 <= r.status_code < 500:
self._thread_local.num_401_calls = 1
return r
@@ -236,13 +255,12 @@ class HTTPDigestAuth(AuthBase):
# Rewind the file position indicator of the body to where
# it was to resend the request.
r.request.body.seek(self._thread_local.pos)
s_auth = r.headers.get('www-authenticate', '')
if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:
s_auth = r.headers.get("www-authenticate", "")
if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:
self._thread_local.num_401_calls += 1
pat = re.compile(r'digest ', flags=re.IGNORECASE)
self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))
pat = re.compile(r"digest ", flags=re.IGNORECASE)
self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1))
# Consume content and release the original connection
# to allow our new request to reuse the same one.
@@ -252,8 +270,9 @@ class HTTPDigestAuth(AuthBase):
extract_cookies_to_jar(prep._cookies, r.request, r.raw)
prep.prepare_cookies(prep._cookies)
prep.headers['Authorization'] = self.build_digest_header(
prep.method, prep.url)
prep.headers["Authorization"] = self.build_digest_header(
prep.method, prep.url
)
_r = r.connection.send(prep, **kwargs)
_r.history.append(r)
_r.request = prep
@@ -268,7 +287,7 @@ class HTTPDigestAuth(AuthBase):
self.init_per_thread_state()
# If we have a saved nonce, skip the 401
if self._thread_local.last_nonce:
r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
r.headers["Authorization"] = self.build_digest_header(r.method, r.url)
try:
self._thread_local.pos = r.body.tell()
except AttributeError:
@@ -277,17 +296,19 @@ class HTTPDigestAuth(AuthBase):
# file position of the previous body. Ensure it's set to
# None.
self._thread_local.pos = None
r.register_hook('response', self.handle_401)
r.register_hook('response', self.handle_redirect)
r.register_hook("response", self.handle_401)
r.register_hook("response", self.handle_redirect)
self._thread_local.num_401_calls = 1
return r
def __eq__(self, other):
return all([
self.username == getattr(other, 'username', None),
self.password == getattr(other, 'password', None)
])
return all(
[
self.username == getattr(other, "username", None),
self.password == getattr(other, "password", None),
]
)
def __ne__(self, other):
return not self == other

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
requests.certs
@@ -14,5 +13,5 @@ packaged CA bundle.
"""
from certifi import where
if __name__ == '__main__':
if __name__ == "__main__":
print(where())

94
src/requests/compat.py Normal file
View File

@@ -0,0 +1,94 @@
"""
requests.compat
~~~~~~~~~~~~~~~
This module previously handled import compatibility issues
between Python 2 and Python 3. It remains for backwards
compatibility until the next major version.
"""
import importlib
import sys
# -------------------
# Character Detection
# -------------------
def _resolve_char_detection():
"""Find supported character detection libraries."""
chardet = None
for lib in ("chardet", "charset_normalizer"):
if chardet is None:
try:
chardet = importlib.import_module(lib)
except ImportError:
pass
return chardet
chardet = _resolve_char_detection()
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = _ver[0] == 2
#: Python 3.x?
is_py3 = _ver[0] == 3
# json/simplejson module import resolution
has_simplejson = False
try:
import simplejson as json
has_simplejson = True
except ImportError:
import json
if has_simplejson:
from simplejson import JSONDecodeError
else:
from json import JSONDecodeError
# Keep OrderedDict for backwards compatibility.
from collections import OrderedDict
from collections.abc import Callable, Mapping, MutableMapping
from http import cookiejar as cookielib
from http.cookies import Morsel
from io import StringIO
# --------------
# Legacy Imports
# --------------
from urllib.parse import (
quote,
quote_plus,
unquote,
unquote_plus,
urldefrag,
urlencode,
urljoin,
urlparse,
urlsplit,
urlunparse,
)
from urllib.request import (
getproxies,
getproxies_environment,
parse_http_list,
proxy_bypass,
proxy_bypass_environment,
)
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)

View File

@@ -1,21 +1,18 @@
# -*- coding: utf-8 -*-
"""
requests.cookies
~~~~~~~~~~~~~~~~
Compatibility code to be able to use `cookielib.CookieJar` with requests.
Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import calendar
import copy
import time
import calendar
import collections
from ._internal_utils import to_native_string
from .compat import cookielib, urlparse, urlunparse, Morsel
from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse
try:
import threading
@@ -23,10 +20,10 @@ except ImportError:
import dummy_threading as threading
class MockRequest(object):
class MockRequest:
"""Wraps a `requests.Request` to mimic a `urllib2.Request`.
The code in `cookielib.CookieJar` expects this interface in order to correctly
The code in `http.cookiejar.CookieJar` expects this interface in order to correctly
manage cookie policies, i.e., determine whether a cookie can be set, given the
domains of the request and the cookie.
@@ -52,16 +49,22 @@ class MockRequest(object):
def get_full_url(self):
# Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get('Host'):
if not self._r.headers.get("Host"):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = to_native_string(self._r.headers['Host'], encoding='utf-8')
host = to_native_string(self._r.headers["Host"], encoding="utf-8")
parsed = urlparse(self._r.url)
# Reconstruct the URL as we expect it
return urlunparse([
parsed.scheme, host, parsed.path, parsed.params, parsed.query,
parsed.fragment
])
return urlunparse(
[
parsed.scheme,
host,
parsed.path,
parsed.params,
parsed.query,
parsed.fragment,
]
)
def is_unverifiable(self):
return True
@@ -73,8 +76,10 @@ class MockRequest(object):
return self._r.headers.get(name, self._new_headers.get(name, default))
def add_header(self, key, val):
"""cookielib has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
"""cookiejar has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError(
"Cookie headers should be added with add_unredirected_header()"
)
def add_unredirected_header(self, name, value):
self._new_headers[name] = value
@@ -95,15 +100,15 @@ class MockRequest(object):
return self.get_host()
class MockResponse(object):
class MockResponse:
"""Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
...what? Basically, expose the parsed HTTP headers from the server response
the way `cookielib` expects to see them.
the way `http.cookiejar` expects to see them.
"""
def __init__(self, headers):
"""Make a MockResponse for `cookielib` to read.
"""Make a MockResponse for `cookiejar` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers
"""
@@ -119,12 +124,11 @@ class MockResponse(object):
def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(response, '_original_response') and
response._original_response):
if not (hasattr(response, "_original_response") and response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
req = MockRequest(request)
@@ -141,7 +145,7 @@ def get_cookie_header(jar, request):
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
return r.get_new_headers().get("Cookie")
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
@@ -169,8 +173,8 @@ class CookieConflictError(RuntimeError):
"""
class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
"""Compatibility class; is a cookielib.CookieJar, but exposes a dict
class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
"""Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict
interface.
This is the CookieJar we create by default for requests and sessions that
@@ -206,7 +210,9 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
"""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
remove_cookie_by_name(
self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
)
return
if isinstance(value, Morsel):
@@ -306,16 +312,15 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
"""
dictionary = {}
for cookie in iter(self):
if (
(domain is None or cookie.domain == domain) and
(path is None or cookie.path == path)
if (domain is None or cookie.domain == domain) and (
path is None or cookie.path == path
):
dictionary[cookie.name] = cookie.value
return dictionary
def __contains__(self, name):
try:
return super(RequestsCookieJar, self).__contains__(name)
return super().__contains__(name)
except CookieConflictError:
return True
@@ -336,15 +341,19 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
self.set(name, value)
def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
"""Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s
``remove_cookie_by_name()``.
"""
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
cookie.value = cookie.value.replace('\\"', '')
return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
if (
hasattr(cookie.value, "startswith")
and cookie.value.startswith('"')
and cookie.value.endswith('"')
):
cookie.value = cookie.value.replace('\\"', "")
return super().set_cookie(cookie, *args, **kwargs)
def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
@@ -352,7 +361,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other)
super().update(other)
def _find(self, name, domain=None, path=None):
"""Requests uses this method internally to get cookie values.
@@ -372,7 +381,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
if path is None or cookie.path == path:
return cookie.value
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
@@ -391,39 +400,48 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn is not None:
# if there are multiple cookies that meet passed in criteria
raise CookieConflictError(
f"There are multiple cookies with name, {name!r}"
)
# we will eventually return this as long as no cookie conflict
toReturn = cookie.value
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
def __getstate__(self):
"""Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop('_cookies_lock')
state.pop("_cookies_lock")
return state
def __setstate__(self, state):
"""Unlike a normal CookieJar, this class is pickleable."""
self.__dict__.update(state)
if '_cookies_lock' not in self.__dict__:
if "_cookies_lock" not in self.__dict__:
self._cookies_lock = threading.RLock()
def copy(self):
"""Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj
def get_policy(self):
"""Return the CookiePolicy instance used."""
return self._policy
def _copy_cookie_jar(jar):
if jar is None:
return None
if hasattr(jar, 'copy'):
if hasattr(jar, "copy"):
# We're dealing with an instance of RequestsCookieJar
return jar.copy()
# We're dealing with a generic CookieJar instance
@@ -440,31 +458,33 @@ def create_cookie(name, value, **kwargs):
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = dict(
version=0,
name=name,
value=value,
port=None,
domain='',
path='/',
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False,)
result = {
"version": 0,
"name": name,
"value": value,
"port": None,
"domain": "",
"path": "/",
"secure": False,
"expires": None,
"discard": True,
"comment": None,
"comment_url": None,
"rest": {"HttpOnly": None},
"rfc2109": False,
}
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
raise TypeError(
f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
)
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
result["port_specified"] = bool(result["port"])
result["domain_specified"] = bool(result["domain"])
result["domain_initial_dot"] = result["domain"].startswith(".")
result["path_specified"] = bool(result["path"])
return cookielib.Cookie(**result)
@@ -473,30 +493,28 @@ def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
if morsel["max-age"]:
try:
expires = int(time.time() + int(morsel['max-age']))
expires = int(time.time() + int(morsel["max-age"]))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
raise TypeError(f"max-age: {morsel['max-age']} must be integer")
elif morsel["expires"]:
time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
expires = calendar.timegm(time.strptime(morsel["expires"], time_template))
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
comment=morsel["comment"],
comment_url=bool(morsel["comment"]),
discard=False,
domain=morsel['domain'],
domain=morsel["domain"],
expires=expires,
name=morsel.key,
path=morsel['path'],
path=morsel["path"],
port=None,
rest={'HttpOnly': morsel['httponly']},
rest={"HttpOnly": morsel["httponly"]},
rfc2109=False,
secure=bool(morsel['secure']),
secure=bool(morsel["secure"]),
value=morsel.value,
version=morsel['version'] or 0,
version=morsel["version"] or 0,
)
@@ -507,6 +525,7 @@ def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
@@ -525,13 +544,13 @@ def merge_cookies(cookiejar, cookies):
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
:rtype: CookieJar
"""
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError('You can only merge into CookieJar')
raise ValueError("You can only merge into CookieJar")
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(
cookies, cookiejar=cookiejar, overwrite=False)
cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)
elif isinstance(cookies, cookielib.CookieJar):
try:
cookiejar.update(cookies)

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.exceptions
~~~~~~~~~~~~~~~~~~~
@@ -8,6 +6,8 @@ This module contains the set of Requests' exceptions.
"""
from urllib3.exceptions import HTTPError as BaseHTTPError
from .compat import JSONDecodeError as CompatJSONDecodeError
class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
@@ -16,13 +16,40 @@ class RequestException(IOError):
def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
response = kwargs.pop("response", None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = kwargs.pop("request", None)
if response is not None and not self.request and hasattr(response, "request"):
self.request = self.response.request
super(RequestException, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
class InvalidJSONError(RequestException):
"""A JSON error occurred."""
class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
"""Couldn't decode the text into json"""
def __init__(self, *args, **kwargs):
"""
Construct the JSONDecodeError instance first with all
args. Then use it's args to construct the IOError so that
the json specific args aren't used as IOError specific args
and the error message from JSONDecodeError is preserved.
"""
CompatJSONDecodeError.__init__(self, *args)
InvalidJSONError.__init__(self, *self.args, **kwargs)
def __reduce__(self):
"""
The __reduce__ method called when pickling the object must
be the one from the JSONDecodeError (be it json/simplejson)
as it expects all the arguments for instantiation, not just
one like the IOError, and the MRO would by default call the
__reduce__ method from the IOError due to the inheritance order.
"""
return CompatJSONDecodeError.__reduce__(self)
class HTTPError(RequestException):
@@ -70,11 +97,11 @@ class TooManyRedirects(RequestException):
class MissingSchema(RequestException, ValueError):
"""The URL schema (e.g. http or https) is missing."""
"""The URL scheme (e.g. http or https) is missing."""
class InvalidSchema(RequestException, ValueError):
"""See defaults.py for valid schemas."""
"""The URL scheme provided is either invalid or unsupported."""
class InvalidURL(RequestException, ValueError):
@@ -85,16 +112,20 @@ class InvalidHeader(RequestException, ValueError):
"""The header value provided was somehow invalid."""
class InvalidProxyURL(InvalidURL):
"""The proxy URL provided is invalid."""
class ChunkedEncodingError(RequestException):
"""The server declared chunked encoding but sent an invalid chunk."""
class ContentDecodingError(RequestException, BaseHTTPError):
"""Failed to decode response content"""
"""Failed to decode response content."""
class StreamConsumedError(RequestException, TypeError):
"""The content for this response was already consumed"""
"""The content for this response was already consumed."""
class RetryError(RequestException):
@@ -102,21 +133,19 @@ class RetryError(RequestException):
class UnrewindableBodyError(RequestException):
"""Requests encountered an error when trying to rewind a body"""
"""Requests encountered an error when trying to rewind a body."""
# Warnings
class RequestsWarning(Warning):
"""Base warning for Requests."""
pass
class FileModeWarning(RequestsWarning, DeprecationWarning):
"""A file was opened in text mode, but Requests determined its binary length."""
pass
class RequestsDependencyWarning(RequestsWarning):
"""An imported dependency doesn't match the expected version range."""
pass

134
src/requests/help.py Normal file
View File

@@ -0,0 +1,134 @@
"""Module containing bug report helper(s)."""
import json
import platform
import ssl
import sys
import idna
import urllib3
from . import __version__ as requests_version
try:
import charset_normalizer
except ImportError:
charset_normalizer = None
try:
import chardet
except ImportError:
chardet = None
try:
from urllib3.contrib import pyopenssl
except ImportError:
pyopenssl = None
OpenSSL = None
cryptography = None
else:
import cryptography
import OpenSSL
def _implementation():
"""Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 3.10.3 it will return
{'name': 'CPython', 'version': '3.10.3'}.
This function works best on CPython and PyPy: in particular, it probably
doesn't work for Jython or IronPython. Future investigation should be done
to work out the correct shape of the code for those platforms.
"""
implementation = platform.python_implementation()
if implementation == "CPython":
implementation_version = platform.python_version()
elif implementation == "PyPy":
implementation_version = "{}.{}.{}".format(
sys.pypy_version_info.major,
sys.pypy_version_info.minor,
sys.pypy_version_info.micro,
)
if sys.pypy_version_info.releaselevel != "final":
implementation_version = "".join(
[implementation_version, sys.pypy_version_info.releaselevel]
)
elif implementation == "Jython":
implementation_version = platform.python_version() # Complete Guess
elif implementation == "IronPython":
implementation_version = platform.python_version() # Complete Guess
else:
implementation_version = "Unknown"
return {"name": implementation, "version": implementation_version}
def info():
"""Generate information for a bug report."""
try:
platform_info = {
"system": platform.system(),
"release": platform.release(),
}
except OSError:
platform_info = {
"system": "Unknown",
"release": "Unknown",
}
implementation_info = _implementation()
urllib3_info = {"version": urllib3.__version__}
charset_normalizer_info = {"version": None}
chardet_info = {"version": None}
if charset_normalizer:
charset_normalizer_info = {"version": charset_normalizer.__version__}
if chardet:
chardet_info = {"version": chardet.__version__}
pyopenssl_info = {
"version": None,
"openssl_version": "",
}
if OpenSSL:
pyopenssl_info = {
"version": OpenSSL.__version__,
"openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}",
}
cryptography_info = {
"version": getattr(cryptography, "__version__", ""),
}
idna_info = {
"version": getattr(idna, "__version__", ""),
}
system_ssl = ssl.OPENSSL_VERSION_NUMBER
system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""}
return {
"platform": platform_info,
"implementation": implementation_info,
"system_ssl": system_ssl_info,
"using_pyopenssl": pyopenssl is not None,
"using_charset_normalizer": chardet is None,
"pyOpenSSL": pyopenssl_info,
"urllib3": urllib3_info,
"chardet": chardet_info,
"charset_normalizer": charset_normalizer_info,
"cryptography": cryptography_info,
"idna": idna_info,
"requests": {
"version": requests_version,
},
}
def main():
"""Pretty-print the bug information as JSON."""
print(json.dumps(info(), sort_keys=True, indent=2))
if __name__ == "__main__":
main()

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
@@ -11,21 +9,22 @@ Available hooks:
``response``:
The response generated from a Request.
"""
HOOKS = ['response']
HOOKS = ["response"]
def default_hooks():
return dict((event, []) for event in HOOKS)
return {event: [] for event in HOOKS}
# TODO: response is the only one
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or dict()
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
if hasattr(hooks, "__call__"):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.models
~~~~~~~~~~~~~~~
@@ -7,47 +5,73 @@ requests.models
This module contains the primary objects that power Requests.
"""
import collections
import datetime
import sys
# Import encoding now, to avoid implicit import later.
# Implicit import within threads may cause LookupError when standard library is in a ZIP,
# such as in Embedded Python. See https://github.com/requests/requests/issues/3578.
import encodings.idna
# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
import encodings.idna # noqa: F401
from io import UnsupportedOperation
from urllib3.exceptions import (
DecodeError,
LocationParseError,
ProtocolError,
ReadTimeoutError,
SSLError,
)
from urllib3.fields import RequestField
from urllib3.filepost import encode_multipart_formdata
from urllib3.util import parse_url
from urllib3.exceptions import (
DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)
from io import UnsupportedOperation
from .hooks import default_hooks
from .structures import CaseInsensitiveDict
from .auth import HTTPBasicAuth
from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar
from .exceptions import (
HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,
ContentDecodingError, ConnectionError, StreamConsumedError)
from ._internal_utils import to_native_string, unicode_is_ascii
from .utils import (
guess_filename, get_auth_from_url, requote_uri,
stream_decode_response_unicode, to_key_val_list, parse_header_links,
iter_slices, guess_json_utf, super_len, check_header_validity)
from .auth import HTTPBasicAuth
from .compat import (
cookielib, urlunparse, urlsplit, urlencode, str, bytes,
is_py2, chardet, builtin_str, basestring)
Callable,
JSONDecodeError,
Mapping,
basestring,
builtin_str,
chardet,
cookielib,
)
from .compat import json as complexjson
from .compat import urlencode, urlsplit, urlunparse
from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header
from .exceptions import (
ChunkedEncodingError,
ConnectionError,
ContentDecodingError,
HTTPError,
InvalidJSONError,
InvalidURL,
)
from .exceptions import JSONDecodeError as RequestsJSONDecodeError
from .exceptions import MissingSchema
from .exceptions import SSLError as RequestsSSLError
from .exceptions import StreamConsumedError
from .hooks import default_hooks
from .status_codes import codes
from .structures import CaseInsensitiveDict
from .utils import (
check_header_validity,
get_auth_from_url,
guess_filename,
guess_json_utf,
iter_slices,
parse_header_links,
requote_uri,
stream_decode_response_unicode,
super_len,
to_key_val_list,
)
#: The set of HTTP status codes that indicate an automatically
#: processable redirect.
REDIRECT_STATI = (
codes.moved, # 301
codes.found, # 302
codes.other, # 303
codes.moved, # 301
codes.found, # 302
codes.other, # 303
codes.temporary_redirect, # 307
codes.permanent_redirect, # 308
)
@@ -57,7 +81,7 @@ CONTENT_CHUNK_SIZE = 10 * 1024
ITER_CHUNK_SIZE = 512
class RequestEncodingMixin(object):
class RequestEncodingMixin:
@property
def path_url(self):
"""Build the path URL to use."""
@@ -68,16 +92,16 @@ class RequestEncodingMixin(object):
path = p.path
if not path:
path = '/'
path = "/"
url.append(path)
query = p.query
if query:
url.append('?')
url.append("?")
url.append(query)
return ''.join(url)
return "".join(url)
@staticmethod
def _encode_params(data):
@@ -90,18 +114,21 @@ class RequestEncodingMixin(object):
if isinstance(data, (str, bytes)):
return data
elif hasattr(data, 'read'):
elif hasattr(data, "read"):
return data
elif hasattr(data, '__iter__'):
elif hasattr(data, "__iter__"):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
(
k.encode("utf-8") if isinstance(k, str) else k,
v.encode("utf-8") if isinstance(v, str) else v,
)
)
return urlencode(result, doseq=True)
else:
return data
@@ -116,7 +143,7 @@ class RequestEncodingMixin(object):
The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
or 4-tuples (filename, fileobj, contentype, custom_headers).
"""
if (not files):
if not files:
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
@@ -126,7 +153,7 @@ class RequestEncodingMixin(object):
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, '__iter__'):
if isinstance(val, basestring) or not hasattr(val, "__iter__"):
val = [val]
for v in val:
if v is not None:
@@ -135,10 +162,15 @@ class RequestEncodingMixin(object):
v = str(v)
new_fields.append(
(field.decode('utf-8') if isinstance(field, bytes) else field,
v.encode('utf-8') if isinstance(v, str) else v))
(
field.decode("utf-8")
if isinstance(field, bytes)
else field,
v.encode("utf-8") if isinstance(v, str) else v,
)
)
for (k, v) in files:
for k, v in files:
# support for explicit filename
ft = None
fh = None
@@ -155,8 +187,12 @@ class RequestEncodingMixin(object):
if isinstance(fp, (str, bytes, bytearray)):
fdata = fp
else:
elif hasattr(fp, "read"):
fdata = fp.read()
elif fp is None:
continue
else:
fdata = fp
rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
rf.make_multipart(content_type=ft)
@@ -167,17 +203,17 @@ class RequestEncodingMixin(object):
return body, content_type
class RequestHooksMixin(object):
class RequestHooksMixin:
def register_hook(self, event, hook):
"""Properly register a hook."""
if event not in self.hooks:
raise ValueError('Unsupported event specified, with event name "%s"' % (event))
raise ValueError(f'Unsupported event specified, with event name "{event}"')
if isinstance(hook, collections.Callable):
if isinstance(hook, Callable):
self.hooks[event].append(hook)
elif hasattr(hook, '__iter__'):
self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))
elif hasattr(hook, "__iter__"):
self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
@@ -200,9 +236,13 @@ class Request(RequestHooksMixin):
:param url: URL to send.
:param headers: dictionary of headers to send.
:param files: dictionary of {filename: fileobject} files to multipart upload.
:param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.
:param data: the body to attach to the request. If a dictionary or
list of tuples ``[(key, value)]`` is provided, form-encoding will
take place.
:param json: json for the body to attach to the request (if files or data is not specified).
:param params: dictionary of URL parameters to append to the URL.
:param params: URL parameters to append to the URL. If a dictionary or
list of tuples ``[(key, value)]`` is provided, form-encoding will
take place.
:param auth: Auth handler or (user, pass) tuple.
:param cookies: dictionary or CookieJar of cookies to attach to this request.
:param hooks: dictionary of callback hooks, for internal usage.
@@ -210,15 +250,24 @@ class Request(RequestHooksMixin):
Usage::
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req = requests.Request('GET', 'https://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
"""
def __init__(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
def __init__(
self,
method=None,
url=None,
headers=None,
files=None,
data=None,
params=None,
auth=None,
cookies=None,
hooks=None,
json=None,
):
# Default empty dicts for dict params.
data = [] if data is None else data
files = [] if files is None else files
@@ -227,7 +276,7 @@ class Request(RequestHooksMixin):
hooks = {} if hooks is None else hooks
self.hooks = default_hooks()
for (k, v) in list(hooks.items()):
for k, v in list(hooks.items()):
self.register_hook(event=k, hook=v)
self.method = method
@@ -241,7 +290,7 @@ class Request(RequestHooksMixin):
self.cookies = cookies
def __repr__(self):
return '<Request [%s]>' % (self.method)
return f"<Request [{self.method}]>"
def prepare(self):
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
@@ -265,13 +314,16 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
"""The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
containing the exact bytes that will be sent to the server.
Generated from either a :class:`Request <Request>` object or manually.
Instances are generated from a :class:`Request <Request>` object, and
should not be instantiated manually; doing so may produce undesirable
effects.
Usage::
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req = requests.Request('GET', 'https://httpbin.org/get')
>>> r = req.prepare()
>>> r
<PreparedRequest [GET]>
>>> s = requests.Session()
@@ -296,9 +348,19 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
#: integer denoting starting position of a readable file-like body.
self._body_position = None
def prepare(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
def prepare(
self,
method=None,
url=None,
headers=None,
files=None,
data=None,
params=None,
auth=None,
cookies=None,
hooks=None,
json=None,
):
"""Prepares the entire request with the given parameters."""
self.prepare_method(method)
@@ -315,7 +377,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
self.prepare_hooks(hooks)
def __repr__(self):
return '<PreparedRequest [%s]>' % (self.method)
return f"<PreparedRequest [{self.method}]>"
def copy(self):
p = PreparedRequest()
@@ -339,7 +401,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
import idna
try:
host = idna.encode(host, uts46=True).decode('utf-8')
host = idna.encode(host, uts46=True).decode("utf-8")
except idna.IDNAError:
raise UnicodeError
return host
@@ -350,11 +412,11 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/requests/requests/pull/2238
#: https://github.com/psf/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
url = url.decode("utf8")
else:
url = unicode(url) if is_py2 else str(url)
url = str(url)
# Remove leading whitespaces from url
url = url.lstrip()
@@ -362,7 +424,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
if ":" in url and not url.lower().startswith("http"):
self.url = url
return
@@ -373,13 +435,13 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
raise InvalidURL(*e.args)
if not scheme:
error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")
error = error.format(to_native_string(url, 'utf8'))
raise MissingSchema(error)
raise MissingSchema(
f"Invalid URL {url!r}: No scheme supplied. "
f"Perhaps you meant https://{url}?"
)
if not host:
raise InvalidURL("Invalid URL %r: No host supplied" % url)
raise InvalidURL(f"Invalid URL {url!r}: No host supplied")
# In general, we want to try IDNA encoding the hostname if the string contains
# non-ASCII characters. This allows users to automatically get the correct IDNA
@@ -389,33 +451,21 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
try:
host = self._get_idna_encoded_host(host)
except UnicodeError:
raise InvalidURL('URL has an invalid label.')
elif host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
raise InvalidURL("URL has an invalid label.")
elif host.startswith(("*", ".")):
raise InvalidURL("URL has an invalid label.")
# Carefully reconstruct the network location
netloc = auth or ''
netloc = auth or ""
if netloc:
netloc += '@'
netloc += "@"
netloc += host
if port:
netloc += ':' + str(port)
netloc += f":{port}"
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
path = "/"
if isinstance(params, (str, bytes)):
params = to_native_string(params)
@@ -423,7 +473,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
query = f"{query}&{enc_params}"
else:
query = enc_params
@@ -454,42 +504,51 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
if not data and json is not None:
# urllib3 requires a bytes-like body. Python 2's json.dumps
# provides this natively, but Python 3 gives a Unicode string.
content_type = 'application/json'
body = complexjson.dumps(json)
content_type = "application/json"
try:
body = complexjson.dumps(json, allow_nan=False)
except ValueError as ve:
raise InvalidJSONError(ve, request=self)
if not isinstance(body, bytes):
body = body.encode('utf-8')
body = body.encode("utf-8")
is_stream = all([
hasattr(data, '__iter__'),
not isinstance(data, (basestring, list, tuple, collections.Mapping))
])
try:
length = super_len(data)
except (TypeError, AttributeError, UnsupportedOperation):
length = None
is_stream = all(
[
hasattr(data, "__iter__"),
not isinstance(data, (basestring, list, tuple, Mapping)),
]
)
if is_stream:
try:
length = super_len(data)
except (TypeError, AttributeError, UnsupportedOperation):
length = None
body = data
if getattr(body, 'tell', None) is not None:
if getattr(body, "tell", None) is not None:
# Record the current file position before reading.
# This will allow us to rewind a file in the event
# of a redirect.
try:
self._body_position = body.tell()
except (IOError, OSError):
except OSError:
# This differentiates from None, allowing us to catch
# a failed `tell()` later when trying to rewind the body
self._body_position = object()
if files:
raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
raise NotImplementedError(
"Streamed bodies and files are mutually exclusive."
)
if length:
self.headers['Content-Length'] = builtin_str(length)
self.headers["Content-Length"] = builtin_str(length)
else:
self.headers['Transfer-Encoding'] = 'chunked'
self.headers["Transfer-Encoding"] = "chunked"
else:
# Multi-part file uploads.
if files:
@@ -497,16 +556,16 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
else:
if data:
body = self._encode_params(data)
if isinstance(data, basestring) or hasattr(data, 'read'):
if isinstance(data, basestring) or hasattr(data, "read"):
content_type = None
else:
content_type = 'application/x-www-form-urlencoded'
content_type = "application/x-www-form-urlencoded"
self.prepare_content_length(body)
# Add content-type if it wasn't explicitly provided.
if content_type and ('content-type' not in self.headers):
self.headers['Content-Type'] = content_type
if content_type and ("content-type" not in self.headers):
self.headers["Content-Type"] = content_type
self.body = body
@@ -517,13 +576,16 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
if length:
# If length exists, set it. Otherwise, we fallback
# to Transfer-Encoding: chunked.
self.headers['Content-Length'] = builtin_str(length)
elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
self.headers["Content-Length"] = builtin_str(length)
elif (
self.method not in ("GET", "HEAD")
and self.headers.get("Content-Length") is None
):
# Set Content-Length to 0 for methods that can have a body
# but don't provide one. (i.e. not GET or HEAD)
self.headers['Content-Length'] = '0'
self.headers["Content-Length"] = "0"
def prepare_auth(self, auth, url=''):
def prepare_auth(self, auth, url=""):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
@@ -563,7 +625,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
self.headers['Cookie'] = cookie_header
self.headers["Cookie"] = cookie_header
def prepare_hooks(self, hooks):
"""Prepares the given hooks."""
@@ -575,19 +637,25 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
self.register_hook(event, hooks[event])
class Response(object):
class Response:
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
"""
__attrs__ = [
'_content', 'status_code', 'headers', 'url', 'history',
'encoding', 'reason', 'cookies', 'elapsed', 'request'
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
def __init__(self):
super(Response, self).__init__()
self._content = False
self._content_consumed = False
self._next = None
@@ -602,7 +670,7 @@ class Response(object):
#: File-like object representation of response (for advanced usage).
#: Use of ``raw`` requires that ``stream=True`` be set on the request.
# This requirement does not apply for use internally to Requests.
#: This requirement does not apply for use internally to Requests.
self.raw = None
#: Final URL location of Response.
@@ -646,21 +714,18 @@ class Response(object):
if not self._content_consumed:
self.content
return dict(
(attr, getattr(self, attr, None))
for attr in self.__attrs__
)
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
# pickled objects do not have .raw
setattr(self, '_content_consumed', True)
setattr(self, 'raw', None)
setattr(self, "_content_consumed", True)
setattr(self, "raw", None)
def __repr__(self):
return '<Response [%s]>' % (self.status_code)
return f"<Response [{self.status_code}]>"
def __bool__(self):
"""Returns True if :attr:`status_code` is less than 400.
@@ -688,11 +753,11 @@ class Response(object):
@property
def ok(self):
"""Returns True if :attr:`status_code` is less than 400.
"""Returns True if :attr:`status_code` is less than 400, False if not.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
the status code is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
try:
@@ -706,12 +771,15 @@ class Response(object):
"""True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
"""
return ('location' in self.headers and self.status_code in REDIRECT_STATI)
return "location" in self.headers and self.status_code in REDIRECT_STATI
@property
def is_permanent_redirect(self):
"""True if this Response one of the permanent versions of redirect."""
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
return "location" in self.headers and self.status_code in (
codes.moved_permanently,
codes.permanent_redirect,
)
@property
def next(self):
@@ -720,8 +788,13 @@ class Response(object):
@property
def apparent_encoding(self):
"""The apparent encoding, provided by the chardet library."""
return chardet.detect(self.content)['encoding']
"""The apparent encoding, provided by the charset_normalizer or chardet libraries."""
if chardet is not None:
return chardet.detect(self.content)["encoding"]
else:
# If no character detection library is available, we'll fall back
# to a standard Python utf-8 str.
return "utf-8"
def iter_content(self, chunk_size=1, decode_unicode=False):
"""Iterates over the response data. When stream=True is set on the
@@ -742,16 +815,17 @@ class Response(object):
def generate():
# Special case for urllib3.
if hasattr(self.raw, 'stream'):
if hasattr(self.raw, "stream"):
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
yield from self.raw.stream(chunk_size, decode_content=True)
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
except SSLError as e:
raise RequestsSSLError(e)
else:
# Standard file-like object.
while True:
@@ -765,7 +839,9 @@ class Response(object):
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
elif chunk_size is not None and not isinstance(chunk_size, int):
raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))
raise TypeError(
f"chunk_size must be an int, it is instead a {type(chunk_size)}."
)
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
@@ -778,7 +854,9 @@ class Response(object):
return chunks
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
def iter_lines(
self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None
):
"""Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
@@ -788,8 +866,9 @@ class Response(object):
pending = None
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
for chunk in self.iter_content(
chunk_size=chunk_size, decode_unicode=decode_unicode
):
if pending is not None:
chunk = pending + chunk
@@ -803,8 +882,7 @@ class Response(object):
else:
pending = None
for line in lines:
yield line
yield from lines
if pending is not None:
yield pending
@@ -816,13 +894,12 @@ class Response(object):
if self._content is False:
# Read the contents.
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed')
raise RuntimeError("The content for this response was already consumed")
if self.status_code == 0 or self.raw is None:
self._content = None
else:
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""
self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
@@ -834,7 +911,7 @@ class Response(object):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
``charset_normalizer`` or ``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
@@ -847,7 +924,7 @@ class Response(object):
encoding = self.encoding
if not self.content:
return str('')
return ""
# Fallback to auto-detected encoding.
if self.encoding is None:
@@ -855,7 +932,7 @@ class Response(object):
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
content = str(self.content, encoding, errors="replace")
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
@@ -863,7 +940,7 @@ class Response(object):
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors='replace')
content = str(self.content, errors="replace")
return content
@@ -871,67 +948,77 @@ class Response(object):
r"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
:raises ValueError: If the response body does not contain valid json.
:raises requests.exceptions.JSONDecodeError: If the response body does not
contain valid json.
"""
if not self.encoding and self.content and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using chardet to make
# decoding fails, fall back to `self.text` (using charset_normalizer to make
# a best guess).
encoding = guess_json_utf(self.content)
if encoding is not None:
try:
return complexjson.loads(
self.content.decode(encoding), **kwargs
)
return complexjson.loads(self.content.decode(encoding), **kwargs)
except UnicodeDecodeError:
# Wrong UTF codec detected; usually because it's not UTF-8
# but some other 8-bit codec. This is an RFC violation,
# and the server didn't bother to tell us what codec *was*
# used.
pass
return complexjson.loads(self.text, **kwargs)
except JSONDecodeError as e:
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
try:
return complexjson.loads(self.text, **kwargs)
except JSONDecodeError as e:
# Catch JSON-related errors and raise as requests.JSONDecodeError
# This aliases json.JSONDecodeError and simplejson.JSONDecodeError
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
@property
def links(self):
"""Returns the parsed header links of the response, if any."""
header = self.headers.get('link')
header = self.headers.get("link")
# l = MultiDict()
l = {}
resolved_links = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
key = link.get("rel") or link.get("url")
resolved_links[key] = link
return l
return resolved_links
def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
"""Raises :class:`HTTPError`, if one occurred."""
http_error_msg = ''
http_error_msg = ""
if isinstance(self.reason, bytes):
# We attempt to decode utf-8 first because some servers
# choose to localize their reason strings. If the string
# isn't utf-8, we fall back to iso-8859-1 for all other
# encodings. (See PR #3538)
try:
reason = self.reason.decode('utf-8')
reason = self.reason.decode("utf-8")
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
reason = self.reason.decode("iso-8859-1")
else:
reason = self.reason
if 400 <= self.status_code < 500:
http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)
http_error_msg = (
f"{self.status_code} Client Error: {reason} for url: {self.url}"
)
elif 500 <= self.status_code < 600:
http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
http_error_msg = (
f"{self.status_code} Server Error: {reason} for url: {self.url}"
)
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
@@ -945,6 +1032,6 @@ class Response(object):
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, 'release_conn', None)
release_conn = getattr(self.raw, "release_conn", None)
if release_conn is not None:
release_conn()

23
src/requests/packages.py Normal file
View File

@@ -0,0 +1,23 @@
import sys
from .compat import chardet
# This code exists for backwards compatibility reasons.
# I don't like it either. Just look the other way. :)
for package in ("urllib3", "idna"):
locals()[package] = __import__(package)
# This traversal is apparently necessary such that the identities are
# preserved (requests.packages.urllib3.* is urllib3.*)
for mod in list(sys.modules):
if mod == package or mod.startswith(f"{package}."):
sys.modules[f"requests.packages.{mod}"] = sys.modules[mod]
if chardet is not None:
target = chardet.__name__
for mod in list(sys.modules):
if mod == target or mod.startswith(f"{target}."):
imported_mod = sys.modules[mod]
sys.modules[f"requests.packages.{mod}"] = imported_mod
mod = mod.replace(target, "chardet")
sys.modules[f"requests.packages.{mod}"] = imported_mod

View File

@@ -1,48 +1,59 @@
# -*- coding: utf-8 -*-
"""
requests.session
~~~~~~~~~~~~~~~~
requests.sessions
~~~~~~~~~~~~~~~~~
This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
"""
import os
import platform
import sys
import time
from collections import Mapping
from collections import OrderedDict
from datetime import timedelta
from .auth import _basic_auth_str
from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse
from .cookies import (
cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)
from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT
from .hooks import default_hooks, dispatch_hook
from ._internal_utils import to_native_string
from .utils import to_key_val_list, default_headers
from .exceptions import (
TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)
from .structures import CaseInsensitiveDict
from .adapters import HTTPAdapter
from .utils import (
requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,
get_auth_from_url, rewind_body
from .auth import _basic_auth_str
from .compat import Mapping, cookielib, urljoin, urlparse
from .cookies import (
RequestsCookieJar,
cookiejar_from_dict,
extract_cookies_to_jar,
merge_cookies,
)
from .status_codes import codes
from .exceptions import (
ChunkedEncodingError,
ContentDecodingError,
InvalidSchema,
TooManyRedirects,
)
from .hooks import default_hooks, dispatch_hook
# formerly defined here, reexposed here for backward compatibility
from .models import REDIRECT_STATI
from .models import ( # noqa: F401
DEFAULT_REDIRECT_LIMIT,
REDIRECT_STATI,
PreparedRequest,
Request,
)
from .status_codes import codes
from .structures import CaseInsensitiveDict
from .utils import ( # noqa: F401
DEFAULT_PORTS,
default_headers,
get_auth_from_url,
get_environ_proxies,
get_netrc_auth,
requote_uri,
resolve_proxies,
rewind_body,
should_bypass_proxies,
to_key_val_list,
)
# Preferred clock, based on which one is more accurate on a given system.
if platform.system() == 'Windows':
try: # Python 3.3+
preferred_clock = time.perf_counter
except AttributeError: # Earlier than Python 3.
preferred_clock = time.clock
if sys.platform == "win32":
preferred_clock = time.perf_counter
else:
preferred_clock = time.time
@@ -61,8 +72,7 @@ def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
# Bypass if not a dictionary (e.g. verify)
if not (
isinstance(session_setting, Mapping) and
isinstance(request_setting, Mapping)
isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)
):
return request_setting
@@ -84,39 +94,86 @@ def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
This is necessary because when request_hooks == {'response': []}, the
merge breaks Session hooks entirely.
"""
if session_hooks is None or session_hooks.get('response') == []:
if session_hooks is None or session_hooks.get("response") == []:
return request_hooks
if request_hooks is None or request_hooks.get('response') == []:
if request_hooks is None or request_hooks.get("response") == []:
return session_hooks
return merge_setting(request_hooks, session_hooks, dict_class)
class SessionRedirectMixin(object):
class SessionRedirectMixin:
def get_redirect_target(self, resp):
"""Receives a Response. Returns a redirect URI or ``None``"""
# Due to the nature of how requests processes redirects this method will
# be called at least once upon the original response and at least twice
# on each subsequent redirect response (if any).
# If a custom mixin is used to handle this logic, it may be advantageous
# to cache the redirect location onto the response object as a private
# attribute.
if resp.is_redirect:
location = resp.headers['location']
location = resp.headers["location"]
# Currently the underlying http module on py3 decode headers
# in latin1, but empirical evidence suggests that latin1 is very
# rarely used with non-ASCII characters in HTTP headers.
# It is more likely to get UTF8 header rather than latin1.
# This causes incorrect handling of UTF8 encoded location headers.
# To solve this, we re-encode the location in latin1.
if is_py3:
location = location.encode('latin1')
return to_native_string(location, 'utf8')
location = location.encode("latin1")
return to_native_string(location, "utf8")
return None
def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
def should_strip_auth(self, old_url, new_url):
"""Decide whether Authorization header should be removed when redirecting"""
old_parsed = urlparse(old_url)
new_parsed = urlparse(new_url)
if old_parsed.hostname != new_parsed.hostname:
return True
# Special case: allow http -> https redirect when using the standard
# ports. This isn't specified by RFC 7235, but is kept to avoid
# breaking backwards compatibility with older versions of requests
# that allowed any redirects on the same host.
if (
old_parsed.scheme == "http"
and old_parsed.port in (80, None)
and new_parsed.scheme == "https"
and new_parsed.port in (443, None)
):
return False
# Handle default port usage corresponding to scheme.
changed_port = old_parsed.port != new_parsed.port
changed_scheme = old_parsed.scheme != new_parsed.scheme
default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
if (
not changed_scheme
and old_parsed.port in default_port
and new_parsed.port in default_port
):
return False
# Standard case: root URI must match
return changed_port or changed_scheme
def resolve_redirects(
self,
resp,
req,
stream=False,
timeout=None,
verify=True,
cert=None,
proxies=None,
yield_requests=False,
**adapter_kwargs,
):
"""Receives a Response. Returns a generator of Responses or Requests."""
hist = [] # keep track of history
url = self.get_redirect_target(resp)
previous_fragment = urlparse(req.url).fragment
while url:
prepared_request = req.copy()
@@ -131,18 +188,24 @@ class SessionRedirectMixin(object):
resp.raw.read(decode_content=False)
if len(resp.history) >= self.max_redirects:
raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)
raise TooManyRedirects(
f"Exceeded {self.max_redirects} redirects.", response=resp
)
# Release the connection back into the pool.
resp.close()
# Handle redirection without scheme (see: RFC 1808 Section 4)
if url.startswith('//'):
if url.startswith("//"):
parsed_rurl = urlparse(resp.url)
url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)
url = ":".join([to_native_string(parsed_rurl.scheme), url])
# The scheme should be lower case...
# Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
parsed = urlparse(url)
if parsed.fragment == "" and previous_fragment:
parsed = parsed._replace(fragment=previous_fragment)
elif parsed.fragment:
previous_fragment = parsed.fragment
url = parsed.geturl()
# Facilitate relative 'location' headers, as allowed by RFC 7231.
@@ -157,19 +220,19 @@ class SessionRedirectMixin(object):
self.rebuild_method(prepared_request, resp)
# https://github.com/requests/requests/issues/1084
if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
# https://github.com/requests/requests/issues/3490
purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')
# https://github.com/psf/requests/issues/1084
if resp.status_code not in (
codes.temporary_redirect,
codes.permanent_redirect,
):
# https://github.com/psf/requests/issues/3490
purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")
for header in purged_headers:
prepared_request.headers.pop(header, None)
prepared_request.body = None
headers = prepared_request.headers
try:
del headers['Cookie']
except KeyError:
pass
headers.pop("Cookie", None)
# Extract any cookies sent on the response to the cookiejar
# in the new request. Because we've mutated our copied prepared
@@ -185,9 +248,8 @@ class SessionRedirectMixin(object):
# A failed tell() sets `_body_position` to `object()`. This non-None
# value ensures `rewindable` will be True, allowing us to raise an
# UnrewindableBodyError, instead of hanging the connection.
rewindable = (
prepared_request._body_position is not None and
('Content-Length' in headers or 'Transfer-Encoding' in headers)
rewindable = prepared_request._body_position is not None and (
"Content-Length" in headers or "Transfer-Encoding" in headers
)
# Attempt to rewind consumed file-like object.
@@ -200,7 +262,6 @@ class SessionRedirectMixin(object):
if yield_requests:
yield req
else:
resp = self.send(
req,
stream=stream,
@@ -209,7 +270,7 @@ class SessionRedirectMixin(object):
cert=cert,
proxies=proxies,
allow_redirects=False,
**adapter_kwargs
**adapter_kwargs,
)
extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
@@ -226,22 +287,18 @@ class SessionRedirectMixin(object):
headers = prepared_request.headers
url = prepared_request.url
if 'Authorization' in headers:
if "Authorization" in headers and self.should_strip_auth(
response.request.url, url
):
# If we get redirected to a new host, we should strip out any
# authentication headers.
original_parsed = urlparse(response.request.url)
redirect_parsed = urlparse(url)
if (original_parsed.hostname != redirect_parsed.hostname):
del headers['Authorization']
del headers["Authorization"]
# .netrc might have more auth for us on our new host.
new_auth = get_netrc_auth(url) if self.trust_env else None
if new_auth is not None:
prepared_request.prepare_auth(new_auth)
return
def rebuild_proxies(self, prepared_request, proxies):
"""This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
@@ -254,32 +311,22 @@ class SessionRedirectMixin(object):
:rtype: dict
"""
proxies = proxies if proxies is not None else {}
headers = prepared_request.headers
url = prepared_request.url
scheme = urlparse(url).scheme
new_proxies = proxies.copy()
no_proxy = proxies.get('no_proxy')
scheme = urlparse(prepared_request.url).scheme
new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)
bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)
if self.trust_env and not bypass_proxy:
environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
proxy = environ_proxies.get(scheme, environ_proxies.get('all'))
if proxy:
new_proxies.setdefault(scheme, proxy)
if 'Proxy-Authorization' in headers:
del headers['Proxy-Authorization']
if "Proxy-Authorization" in headers:
del headers["Proxy-Authorization"]
try:
username, password = get_auth_from_url(new_proxies[scheme])
except KeyError:
username, password = None, None
if username and password:
headers['Proxy-Authorization'] = _basic_auth_str(username, password)
# urllib3 handles proxy authorization for us in the standard adapter.
# Avoid appending this to TLS tunneled requests where it may be leaked.
if not scheme.startswith("https") and username and password:
headers["Proxy-Authorization"] = _basic_auth_str(username, password)
return new_proxies
@@ -289,19 +336,19 @@ class SessionRedirectMixin(object):
"""
method = prepared_request.method
# http://tools.ietf.org/html/rfc7231#section-6.4.4
if response.status_code == codes.see_other and method != 'HEAD':
method = 'GET'
# https://tools.ietf.org/html/rfc7231#section-6.4.4
if response.status_code == codes.see_other and method != "HEAD":
method = "GET"
# Do what the browsers do, despite standards...
# First, turn 302s into GETs.
if response.status_code == codes.found and method != 'HEAD':
method = 'GET'
if response.status_code == codes.found and method != "HEAD":
method = "GET"
# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == 'POST':
method = 'GET'
if response.status_code == codes.moved and method == "POST":
method = "GET"
prepared_request.method = method
@@ -315,24 +362,32 @@ class Session(SessionRedirectMixin):
>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
>>> s.get('https://httpbin.org/get')
<Response [200]>
Or as a context manager::
>>> with requests.Session() as s:
>>> s.get('http://httpbin.org/get')
... s.get('https://httpbin.org/get')
<Response [200]>
"""
__attrs__ = [
'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
'cert', 'prefetch', 'adapters', 'stream', 'trust_env',
'max_redirects',
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
def __init__(self):
#: A case-insensitive dictionary of headers to be sent on each
#: :class:`Request <Request>` sent from this
#: :class:`Session <Session>`.
@@ -359,6 +414,13 @@ class Session(SessionRedirectMixin):
self.stream = False
#: SSL Verification default.
#: Defaults to `True`, requiring requests to verify the TLS certificate at the
#: remote end.
#: If verify is set to `False`, requests will accept any TLS certificate
#: presented by the server, and will ignore hostname mismatches and/or
#: expired certificates, which will make your application vulnerable to
#: man-in-the-middle (MitM) attacks.
#: Only set this to `False` for testing.
self.verify = True
#: SSL client certificate default, if String, path to ssl client
@@ -383,8 +445,8 @@ class Session(SessionRedirectMixin):
# Default connection adapters.
self.adapters = OrderedDict()
self.mount('https://', HTTPAdapter())
self.mount('http://', HTTPAdapter())
self.mount("https://", HTTPAdapter())
self.mount("http://", HTTPAdapter())
def __enter__(self):
return self
@@ -410,7 +472,8 @@ class Session(SessionRedirectMixin):
# Merge with session cookies
merged_cookies = merge_cookies(
merge_cookies(RequestsCookieJar(), self.cookies), cookies)
merge_cookies(RequestsCookieJar(), self.cookies), cookies
)
# Set environment's basic authentication if not explicitly set.
auth = request.auth
@@ -424,7 +487,9 @@ class Session(SessionRedirectMixin):
files=request.files,
data=request.data,
json=request.json,
headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
headers=merge_setting(
request.headers, self.headers, dict_class=CaseInsensitiveDict
),
params=merge_setting(request.params, self.params),
auth=merge_setting(auth, self.auth),
cookies=merged_cookies,
@@ -432,10 +497,25 @@ class Session(SessionRedirectMixin):
)
return p
def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
def request(
self,
method,
url,
params=None,
data=None,
headers=None,
cookies=None,
files=None,
auth=None,
timeout=None,
allow_redirects=True,
proxies=None,
hooks=None,
stream=None,
verify=None,
cert=None,
json=None,
):
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object.
@@ -443,8 +523,8 @@ class Session(SessionRedirectMixin):
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send
in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
@@ -463,11 +543,18 @@ class Session(SessionRedirectMixin):
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param hooks: (optional) Dictionary mapping hook name to one event or
list of events, event must be callable.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
to a CA bundle to use. Defaults to ``True``. When set to
``False``, requests will accept any TLS certificate presented by
the server, and will ignore hostname mismatches and/or expired
certificates, which will make your application vulnerable to
man-in-the-middle (MitM) attacks. Setting verify to ``False``
may be useful during local development or testing.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response
@@ -495,8 +582,8 @@ class Session(SessionRedirectMixin):
# Send the request.
send_kwargs = {
'timeout': timeout,
'allow_redirects': allow_redirects,
"timeout": timeout,
"allow_redirects": allow_redirects,
}
send_kwargs.update(settings)
resp = self.send(prep, **send_kwargs)
@@ -511,8 +598,8 @@ class Session(SessionRedirectMixin):
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs)
kwargs.setdefault("allow_redirects", True)
return self.request("GET", url, **kwargs)
def options(self, url, **kwargs):
r"""Sends a OPTIONS request. Returns :class:`Response` object.
@@ -522,8 +609,8 @@ class Session(SessionRedirectMixin):
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('OPTIONS', url, **kwargs)
kwargs.setdefault("allow_redirects", True)
return self.request("OPTIONS", url, **kwargs)
def head(self, url, **kwargs):
r"""Sends a HEAD request. Returns :class:`Response` object.
@@ -533,42 +620,45 @@ class Session(SessionRedirectMixin):
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return self.request('HEAD', url, **kwargs)
kwargs.setdefault("allow_redirects", False)
return self.request("HEAD", url, **kwargs)
def post(self, url, data=None, json=None, **kwargs):
r"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('POST', url, data=data, json=json, **kwargs)
return self.request("POST", url, data=data, json=json, **kwargs)
def put(self, url, data=None, **kwargs):
r"""Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PUT', url, data=data, **kwargs)
return self.request("PUT", url, data=data, **kwargs)
def patch(self, url, data=None, **kwargs):
r"""Sends a PATCH request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PATCH', url, data=data, **kwargs)
return self.request("PATCH", url, data=data, **kwargs)
def delete(self, url, **kwargs):
r"""Sends a DELETE request. Returns :class:`Response` object.
@@ -578,7 +668,7 @@ class Session(SessionRedirectMixin):
:rtype: requests.Response
"""
return self.request('DELETE', url, **kwargs)
return self.request("DELETE", url, **kwargs)
def send(self, request, **kwargs):
"""Send a given PreparedRequest.
@@ -587,19 +677,20 @@ class Session(SessionRedirectMixin):
"""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify)
kwargs.setdefault('cert', self.cert)
kwargs.setdefault('proxies', self.proxies)
kwargs.setdefault("stream", self.stream)
kwargs.setdefault("verify", self.verify)
kwargs.setdefault("cert", self.cert)
if "proxies" not in kwargs:
kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)
# It's possible that users might accidentally send a Request object.
# Guard against that specific failure case.
if isinstance(request, Request):
raise ValueError('You can only send PreparedRequests.')
raise ValueError("You can only send PreparedRequests.")
# Set up variables needed for resolve_redirects and dispatching of hooks
allow_redirects = kwargs.pop('allow_redirects', True)
stream = kwargs.get('stream')
allow_redirects = kwargs.pop("allow_redirects", True)
stream = kwargs.get("stream")
hooks = request.hooks
# Get the appropriate adapter to use
@@ -616,22 +707,23 @@ class Session(SessionRedirectMixin):
r.elapsed = timedelta(seconds=elapsed)
# Response manipulation hooks
r = dispatch_hook('response', hooks, r, **kwargs)
r = dispatch_hook("response", hooks, r, **kwargs)
# Persist cookies
if r.history:
# If the hooks create history then we want those cookies too
for resp in r.history:
extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
extract_cookies_to_jar(self.cookies, request, r.raw)
# Redirect resolving generator.
gen = self.resolve_redirects(r, request, **kwargs)
# Resolve redirects if allowed.
history = [resp for resp in gen] if allow_redirects else []
if allow_redirects:
# Redirect resolving generator.
gen = self.resolve_redirects(r, request, **kwargs)
history = [resp for resp in gen]
else:
history = []
# Shuffle things around if there's history.
if history:
@@ -644,7 +736,9 @@ class Session(SessionRedirectMixin):
# If redirects aren't being followed, store the response on the Request for Response.next().
if not allow_redirects:
try:
r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs))
r._next = next(
self.resolve_redirects(r, request, yield_requests=True, **kwargs)
)
except StopIteration:
pass
@@ -662,16 +756,19 @@ class Session(SessionRedirectMixin):
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
no_proxy = proxies.get('no_proxy') if proxies is not None else None
no_proxy = proxies.get("no_proxy") if proxies is not None else None
env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
for (k, v) in env_proxies.items():
for k, v in env_proxies.items():
proxies.setdefault(k, v)
# Look for requests environment configuration and be compatible
# with cURL.
# Look for requests environment configuration
# and be compatible with cURL.
if verify is True or verify is None:
verify = (os.environ.get('REQUESTS_CA_BUNDLE') or
os.environ.get('CURL_CA_BUNDLE'))
verify = (
os.environ.get("REQUESTS_CA_BUNDLE")
or os.environ.get("CURL_CA_BUNDLE")
or verify
)
# Merge all the kwargs.
proxies = merge_setting(proxies, self.proxies)
@@ -679,8 +776,7 @@ class Session(SessionRedirectMixin):
verify = merge_setting(verify, self.verify)
cert = merge_setting(cert, self.cert)
return {'verify': verify, 'proxies': proxies, 'stream': stream,
'cert': cert}
return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
def get_adapter(self, url):
"""
@@ -688,13 +784,12 @@ class Session(SessionRedirectMixin):
:rtype: requests.adapters.BaseAdapter
"""
for (prefix, adapter) in self.adapters.items():
if url.lower().startswith(prefix):
for prefix, adapter in self.adapters.items():
if url.lower().startswith(prefix.lower()):
return adapter
# Nothing matches :-/
raise InvalidSchema("No connection adapters were found for '%s'" % url)
raise InvalidSchema(f"No connection adapters were found for {url!r}")
def close(self):
"""Closes all adapters and as such the session"""
@@ -704,7 +799,7 @@ class Session(SessionRedirectMixin):
def mount(self, prefix, adapter):
"""Registers a connection adapter to a prefix.
Adapters are sorted in descending order by key length.
Adapters are sorted in descending order by prefix length.
"""
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
@@ -713,7 +808,7 @@ class Session(SessionRedirectMixin):
self.adapters[key] = self.adapters.pop(key)
def __getstate__(self):
state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
return state
def __setstate__(self, state):
@@ -725,7 +820,12 @@ def session():
"""
Returns a :class:`Session` for context-management.
.. deprecated:: 1.0.0
This method has been deprecated since version 1.0.0 and is only kept for
backwards compatibility. New code should use :class:`~requests.sessions.Session`
to create a session. This may be removed at a future date.
:rtype: Session
"""
return Session()

View File

@@ -0,0 +1,128 @@
r"""
The ``codes`` object defines a mapping from common names for HTTP statuses
to their numerical codes, accessible either as attributes or as dictionary
items.
Example::
>>> import requests
>>> requests.codes['temporary_redirect']
307
>>> requests.codes.teapot
418
>>> requests.codes['\o/']
200
Some codes have multiple names, and both upper- and lower-case versions of
the names are allowed. For example, ``codes.ok``, ``codes.OK``, and
``codes.okay`` all correspond to the HTTP status code 200.
"""
from .structures import LookupDict
_codes = {
# Informational.
100: ("continue",),
101: ("switching_protocols",),
102: ("processing", "early-hints"),
103: ("checkpoint",),
122: ("uri_too_long", "request_uri_too_long"),
200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", ""),
201: ("created",),
202: ("accepted",),
203: ("non_authoritative_info", "non_authoritative_information"),
204: ("no_content",),
205: ("reset_content", "reset"),
206: ("partial_content", "partial"),
207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"),
208: ("already_reported",),
226: ("im_used",),
# Redirection.
300: ("multiple_choices",),
301: ("moved_permanently", "moved", "\\o-"),
302: ("found",),
303: ("see_other", "other"),
304: ("not_modified",),
305: ("use_proxy",),
306: ("switch_proxy",),
307: ("temporary_redirect", "temporary_moved", "temporary"),
308: (
"permanent_redirect",
"resume_incomplete",
"resume",
), # "resume" and "resume_incomplete" to be removed in 3.0
# Client Error.
400: ("bad_request", "bad"),
401: ("unauthorized",),
402: ("payment_required", "payment"),
403: ("forbidden",),
404: ("not_found", "-o-"),
405: ("method_not_allowed", "not_allowed"),
406: ("not_acceptable",),
407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"),
408: ("request_timeout", "timeout"),
409: ("conflict",),
410: ("gone",),
411: ("length_required",),
412: ("precondition_failed", "precondition"),
413: ("request_entity_too_large", "content_too_large"),
414: ("request_uri_too_large", "uri_too_long"),
415: ("unsupported_media_type", "unsupported_media", "media_type"),
416: (
"requested_range_not_satisfiable",
"requested_range",
"range_not_satisfiable",
),
417: ("expectation_failed",),
418: ("im_a_teapot", "teapot", "i_am_a_teapot"),
421: ("misdirected_request",),
422: ("unprocessable_entity", "unprocessable", "unprocessable_content"),
423: ("locked",),
424: ("failed_dependency", "dependency"),
425: ("unordered_collection", "unordered", "too_early"),
426: ("upgrade_required", "upgrade"),
428: ("precondition_required", "precondition"),
429: ("too_many_requests", "too_many"),
431: ("header_fields_too_large", "fields_too_large"),
444: ("no_response", "none"),
449: ("retry_with", "retry"),
450: ("blocked_by_windows_parental_controls", "parental_controls"),
451: ("unavailable_for_legal_reasons", "legal_reasons"),
499: ("client_closed_request",),
# Server Error.
500: ("internal_server_error", "server_error", "/o\\", ""),
501: ("not_implemented",),
502: ("bad_gateway",),
503: ("service_unavailable", "unavailable"),
504: ("gateway_timeout",),
505: ("http_version_not_supported", "http_version"),
506: ("variant_also_negotiates",),
507: ("insufficient_storage",),
509: ("bandwidth_limit_exceeded", "bandwidth"),
510: ("not_extended",),
511: ("network_authentication_required", "network_auth", "network_authentication"),
}
codes = LookupDict(name="status_codes")
def _init():
for code, titles in _codes.items():
for title in titles:
setattr(codes, title, code)
if not title.startswith(("\\", "/")):
setattr(codes, title.upper(), code)
def doc(code):
names = ", ".join(f"``{n}``" for n in _codes[code])
return "* %d: %s" % (code, names)
global __doc__
__doc__ = (
__doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes))
if __doc__ is not None
else None
)
_init()

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.structures
~~~~~~~~~~~~~~~~~~~
@@ -7,16 +5,16 @@ requests.structures
Data structures that power Requests.
"""
import collections
from collections import OrderedDict
from .compat import OrderedDict
from .compat import Mapping, MutableMapping
class CaseInsensitiveDict(collections.MutableMapping):
class CaseInsensitiveDict(MutableMapping):
"""A case-insensitive ``dict``-like object.
Implements all methods and operations of
``collections.MutableMapping`` as well as dict's ``copy``. Also
``MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
@@ -64,14 +62,10 @@ class CaseInsensitiveDict(collections.MutableMapping):
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
)
return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
def __eq__(self, other):
if isinstance(other, collections.Mapping):
if isinstance(other, Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
@@ -91,10 +85,10 @@ class LookupDict(dict):
def __init__(self, name=None):
self.name = name
super(LookupDict, self).__init__()
super().__init__()
def __repr__(self):
return '<lookup \'%s\'>' % (self.name)
return f"<lookup '{self.name}'>"
def __getitem__(self, key):
# We allow fall-through here, so values default to None

View File

@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
@@ -8,53 +6,89 @@ This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""
import cgi
import codecs
import collections
import contextlib
import io
import os
import platform
import re
import socket
import struct
import sys
import tempfile
import warnings
import zipfile
from collections import OrderedDict
from urllib3.util import make_headers, parse_url
from .__version__ import __version__
from . import certs
from .__version__ import __version__
# to_native_string is unused here, but imported here for backwards compatibility
from ._internal_utils import to_native_string
from ._internal_utils import ( # noqa: F401
_HEADER_VALIDATORS_BYTE,
_HEADER_VALIDATORS_STR,
HEADER_VALIDATORS,
to_native_string,
)
from .compat import (
Mapping,
basestring,
bytes,
getproxies,
getproxies_environment,
integer_types,
)
from .compat import parse_http_list as _parse_list_header
from .compat import (
quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,
proxy_bypass, urlunparse, basestring, integer_types, is_py3,
proxy_bypass_environment, getproxies_environment)
proxy_bypass,
proxy_bypass_environment,
quote,
str,
unquote,
urlparse,
urlunparse,
)
from .cookies import cookiejar_from_dict
from .structures import CaseInsensitiveDict
from .exceptions import (
InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)
FileModeWarning,
InvalidHeader,
InvalidURL,
UnrewindableBodyError,
)
from .structures import CaseInsensitiveDict
NETRC_FILES = ('.netrc', '_netrc')
NETRC_FILES = (".netrc", "_netrc")
DEFAULT_CA_BUNDLE_PATH = certs.where()
DEFAULT_PORTS = {"http": 80, "https": 443}
if platform.system() == 'Windows':
# Ensure that ', ' is used to preserve previous delimiter behavior.
DEFAULT_ACCEPT_ENCODING = ", ".join(
re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])
)
if sys.platform == "win32":
# provide a proxy_bypass version on Windows without DNS lookups
def proxy_bypass_registry(host):
if is_py3:
import winreg
else:
import _winreg as winreg
try:
internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
proxyEnable = winreg.QueryValueEx(internetSettings,
'ProxyEnable')[0]
proxyOverride = winreg.QueryValueEx(internetSettings,
'ProxyOverride')[0]
except OSError:
import winreg
except ImportError:
return False
try:
internetSettings = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
)
# ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])
# ProxyOverride is almost always a string
proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]
except (OSError, ValueError):
return False
if not proxyEnable or not proxyOverride:
return False
@@ -62,15 +96,17 @@ if platform.system() == 'Windows':
# make a check value list from the registry entry: replace the
# '<local>' string by the localhost entry and the corresponding
# canonical entry.
proxyOverride = proxyOverride.split(';')
proxyOverride = proxyOverride.split(";")
# filter out empty strings to avoid re.match return true in the following code.
proxyOverride = filter(None, proxyOverride)
# now check if we match one of the registry values.
for test in proxyOverride:
if test == '<local>':
if '.' not in host:
if test == "<local>":
if "." not in host:
return True
test = test.replace(".", r"\.") # mask dots
test = test.replace("*", r".*") # change glob sequence
test = test.replace("?", r".") # change glob char
test = test.replace(".", r"\.") # mask dots
test = test.replace("*", r".*") # change glob sequence
test = test.replace("?", r".") # change glob char
if re.match(test, host, re.I):
return True
return False
@@ -90,7 +126,7 @@ if platform.system() == 'Windows':
def dict_to_sequence(d):
"""Returns an internal sequence dictionary update."""
if hasattr(d, 'items'):
if hasattr(d, "items"):
d = d.items()
return d
@@ -100,37 +136,45 @@ def super_len(o):
total_length = None
current_position = 0
if hasattr(o, '__len__'):
if isinstance(o, str):
o = o.encode("utf-8")
if hasattr(o, "__len__"):
total_length = len(o)
elif hasattr(o, 'len'):
elif hasattr(o, "len"):
total_length = o.len
elif hasattr(o, 'fileno'):
elif hasattr(o, "fileno"):
try:
fileno = o.fileno()
except io.UnsupportedOperation:
except (io.UnsupportedOperation, AttributeError):
# AttributeError is a surprising exception, seeing as how we've just checked
# that `hasattr(o, 'fileno')`. It happens for objects obtained via
# `Tarfile.extractfile()`, per issue 5229.
pass
else:
total_length = os.fstat(fileno).st_size
# Having used fstat to determine the file length, we need to
# confirm that this file was opened up in binary mode.
if 'b' not in o.mode:
warnings.warn((
"Requests has determined the content-length for this "
"request using the binary size of the file: however, the "
"file has been opened in text mode (i.e. without the 'b' "
"flag in the mode). This may lead to an incorrect "
"content-length. In Requests 3.0, support will be removed "
"for files in text mode."),
FileModeWarning
if "b" not in o.mode:
warnings.warn(
(
"Requests has determined the content-length for this "
"request using the binary size of the file: however, the "
"file has been opened in text mode (i.e. without the 'b' "
"flag in the mode). This may lead to an incorrect "
"content-length. In Requests 3.0, support will be removed "
"for files in text mode."
),
FileModeWarning,
)
if hasattr(o, 'tell'):
if hasattr(o, "tell"):
try:
current_position = o.tell()
except (OSError, IOError):
except OSError:
# This can happen in some weird situations, such as when the file
# is actually a special file descriptor like stdin. In this
# instance, we don't know what the length is, so set it to zero and
@@ -138,8 +182,8 @@ def super_len(o):
if total_length is not None:
current_position = total_length
else:
if hasattr(o, 'seek') and total_length is None:
# StringIO and BytesIO have seek but no useable fileno
if hasattr(o, "seek") and total_length is None:
# StringIO and BytesIO have seek but no usable fileno
try:
# seek to end of file
o.seek(0, 2)
@@ -148,7 +192,7 @@ def super_len(o):
# seek back to current position to support
# partially read file-like objects
o.seek(current_position or 0)
except (OSError, IOError):
except OSError:
total_length = 0
if total_length is None:
@@ -160,18 +204,24 @@ def super_len(o):
def get_netrc_auth(url, raise_errors=False):
"""Returns the Requests tuple auth for a given url from netrc."""
netrc_file = os.environ.get("NETRC")
if netrc_file is not None:
netrc_locations = (netrc_file,)
else:
netrc_locations = (f"~/{f}" for f in NETRC_FILES)
try:
from netrc import netrc, NetrcParseError
from netrc import NetrcParseError, netrc
netrc_path = None
for f in NETRC_FILES:
for f in netrc_locations:
try:
loc = os.path.expanduser('~/{0}'.format(f))
loc = os.path.expanduser(f)
except KeyError:
# os.path.expanduser can fail when $HOME is undefined and
# getpwuid fails. See http://bugs.python.org/issue20164 &
# https://github.com/requests/requests/issues/1846
# getpwuid fails. See https://bugs.python.org/issue20164 &
# https://github.com/psf/requests/issues/1846
return
if os.path.exists(loc):
@@ -186,36 +236,85 @@ def get_netrc_auth(url, raise_errors=False):
# Strip port numbers from netloc. This weird `if...encode`` dance is
# used for Python 3.2, which doesn't support unicode literals.
splitstr = b':'
splitstr = b":"
if isinstance(url, str):
splitstr = splitstr.decode('ascii')
splitstr = splitstr.decode("ascii")
host = ri.netloc.split(splitstr)[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
# Return with login / password
login_i = (0 if _netrc[0] else 1)
login_i = 0 if _netrc[0] else 1
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
except (NetrcParseError, OSError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth unless explicitly asked to raise errors.
if raise_errors:
raise
# AppEngine hackiness.
# App Engine hackiness.
except (ImportError, AttributeError):
pass
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if (name and isinstance(name, basestring) and name[0] != '<' and
name[-1] != '>'):
name = getattr(obj, "name", None)
if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":
return os.path.basename(name)
def extract_zipped_paths(path):
"""Replace nonexistent paths that look like they refer to a member of a zip
archive with the location of an extracted copy of the target, or else
just return the provided path unchanged.
"""
if os.path.exists(path):
# this is already a valid path, no need to do anything further
return path
# find the first valid part of the provided path and treat that as a zip archive
# assume the rest of the path is the name of a member in the archive
archive, member = os.path.split(path)
while archive and not os.path.exists(archive):
archive, prefix = os.path.split(archive)
if not prefix:
# If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),
# we _can_ end up in an infinite loop on a rare corner case affecting a small number of users
break
member = "/".join([prefix, member])
if not zipfile.is_zipfile(archive):
return path
zip_file = zipfile.ZipFile(archive)
if member not in zip_file.namelist():
return path
# we have a valid zip archive and a valid member of that archive
tmp = tempfile.gettempdir()
extracted_path = os.path.join(tmp, member.split("/")[-1])
if not os.path.exists(extracted_path):
# use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
with atomic_open(extracted_path) as file_handler:
file_handler.write(zip_file.read(member))
return extracted_path
@contextlib.contextmanager
def atomic_open(filename):
"""Write a file to the disk in an atomic fashion"""
tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
try:
with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
yield tmp_handler
os.replace(tmp_name, filename)
except BaseException:
os.remove(tmp_name)
raise
def from_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
@@ -226,7 +325,9 @@ def from_key_val_list(value):
>>> from_key_val_list([('key', 'val')])
OrderedDict([('key', 'val')])
>>> from_key_val_list('string')
ValueError: need more than 1 value to unpack
Traceback (most recent call last):
...
ValueError: cannot encode objects that are not 2-tuples
>>> from_key_val_list({'key': 'val'})
OrderedDict([('key', 'val')])
@@ -236,7 +337,7 @@ def from_key_val_list(value):
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
raise ValueError("cannot encode objects that are not 2-tuples")
return OrderedDict(value)
@@ -252,7 +353,9 @@ def to_key_val_list(value):
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
ValueError: cannot encode objects that are not 2-tuples.
Traceback (most recent call last):
...
ValueError: cannot encode objects that are not 2-tuples
:rtype: list
"""
@@ -260,9 +363,9 @@ def to_key_val_list(value):
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
raise ValueError("cannot encode objects that are not 2-tuples")
if isinstance(value, collections.Mapping):
if isinstance(value, Mapping):
value = value.items()
return list(value)
@@ -325,10 +428,10 @@ def parse_dict_header(value):
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
if "=" not in item:
result[item] = None
continue
name, value = item.split('=', 1)
name, value = item.split("=", 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
@@ -356,8 +459,8 @@ def unquote_header_value(value, is_filename=False):
# replace sequence below on a UNC path has the effect of turning
# the leading double slash into a single slash and then
# _fix_ie_filename() doesn't work correctly. See #458.
if not is_filename or value[:2] != '\\\\':
return value.replace('\\\\', '\\').replace('\\"', '"')
if not is_filename or value[:2] != "\\\\":
return value.replace("\\\\", "\\").replace('\\"', '"')
return value
@@ -368,11 +471,7 @@ def dict_from_cookiejar(cj):
:rtype: dict
"""
cookie_dict = {}
for cookie in cj:
cookie_dict[cookie.name] = cookie.value
cookie_dict = {cookie.name: cookie.value for cookie in cj}
return cookie_dict
@@ -392,19 +491,49 @@ def get_encodings_from_content(content):
:param content: bytestring to extract encodings from.
"""
warnings.warn((
'In requests 3.0, get_encodings_from_content will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
warnings.warn(
(
"In requests 3.0, get_encodings_from_content will be removed. For "
"more information, please see the discussion on issue #2266. (This"
" warning should only appear once.)"
),
DeprecationWarning,
)
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
return (charset_re.findall(content) +
pragma_re.findall(content) +
xml_re.findall(content))
return (
charset_re.findall(content)
+ pragma_re.findall(content)
+ xml_re.findall(content)
)
def _parse_content_type_header(header):
"""Returns content type and parameters from given header
:param header: string
:return: tuple containing content type and dictionary of
parameters
"""
tokens = header.split(";")
content_type, params = tokens[0].strip(), tokens[1:]
params_dict = {}
items_to_strip = "\"' "
for param in params:
param = param.strip()
if param:
key, value = param, True
index_of_equals = param.find("=")
if index_of_equals != -1:
key = param[:index_of_equals].strip(items_to_strip)
value = param[index_of_equals + 1 :].strip(items_to_strip)
params_dict[key.lower()] = value
return content_type, params_dict
def get_encoding_from_headers(headers):
@@ -414,34 +543,37 @@ def get_encoding_from_headers(headers):
:rtype: str
"""
content_type = headers.get('content-type')
content_type = headers.get("content-type")
if not content_type:
return None
content_type, params = cgi.parse_header(content_type)
content_type, params = _parse_content_type_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
if "charset" in params:
return params["charset"].strip("'\"")
if 'text' in content_type:
return 'ISO-8859-1'
if "text" in content_type:
return "ISO-8859-1"
if "application/json" in content_type:
# Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
return "utf-8"
def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
"""Stream decodes an iterator."""
if r.encoding is None:
for item in iterator:
yield item
yield from iterator
return
decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode(b'', final=True)
rv = decoder.decode(b"", final=True)
if rv:
yield rv
@@ -452,7 +584,7 @@ def iter_slices(string, slice_length):
if slice_length is None or slice_length <= 0:
slice_length = len(string)
while pos < len(string):
yield string[pos:pos + slice_length]
yield string[pos : pos + slice_length]
pos += slice_length
@@ -468,11 +600,14 @@ def get_unicode_from_response(r):
:rtype: str
"""
warnings.warn((
'In requests 3.0, get_unicode_from_response will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
warnings.warn(
(
"In requests 3.0, get_unicode_from_response will be removed. For "
"more information, please see the discussion on issue #2266. (This"
" warning should only appear once.)"
),
DeprecationWarning,
)
tried_encodings = []
@@ -487,14 +622,15 @@ def get_unicode_from_response(r):
# Fall back:
try:
return str(r.content, encoding, errors='replace')
return str(r.content, encoding, errors="replace")
except TypeError:
return r.content
# The unreserved URI characters (RFC 3986)
UNRESERVED_SET = frozenset(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"
)
def unquote_unreserved(uri):
@@ -503,22 +639,22 @@ def unquote_unreserved(uri):
:rtype: str
"""
parts = uri.split('%')
parts = uri.split("%")
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = '%' + parts[i]
parts[i] = f"%{parts[i]}"
else:
parts[i] = '%' + parts[i]
return ''.join(parts)
parts[i] = f"%{parts[i]}"
return "".join(parts)
def requote_uri(uri):
@@ -551,10 +687,10 @@ def address_in_network(ip, net):
:rtype: bool
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
netaddr, bits = net.split("/")
netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
@@ -565,8 +701,8 @@ def dotted_netmask(mask):
:rtype: str
"""
bits = 0xffffffff ^ (1 << 32 - mask) - 1
return socket.inet_ntoa(struct.pack('>I', bits))
bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
return socket.inet_ntoa(struct.pack(">I", bits))
def is_ipv4_address(string_ip):
@@ -575,7 +711,7 @@ def is_ipv4_address(string_ip):
"""
try:
socket.inet_aton(string_ip)
except socket.error:
except OSError:
return False
return True
@@ -586,9 +722,9 @@ def is_valid_cidr(string_network):
:rtype: bool
"""
if string_network.count('/') == 1:
if string_network.count("/") == 1:
try:
mask = int(string_network.split('/')[1])
mask = int(string_network.split("/")[1])
except ValueError:
return False
@@ -596,8 +732,8 @@ def is_valid_cidr(string_network):
return False
try:
socket.inet_aton(string_network.split('/')[0])
except socket.error:
socket.inet_aton(string_network.split("/")[0])
except OSError:
return False
else:
return False
@@ -632,48 +768,52 @@ def should_bypass_proxies(url, no_proxy):
:rtype: bool
"""
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# Prioritize lowercase environment variables over uppercase
# to keep a consistent behaviour with other http projects (curl, wget).
def get_proxy(key):
return os.environ.get(key) or os.environ.get(key.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy_arg = no_proxy
if no_proxy is None:
no_proxy = get_proxy('no_proxy')
netloc = urlparse(url).netloc
no_proxy = get_proxy("no_proxy")
parsed = urlparse(url)
if parsed.hostname is None:
# URLs don't always have hostnames, e.g. file:/// urls.
return True
if no_proxy:
# We need to check whether we match here. We need to see if we match
# the end of the netloc, both with and without the port.
no_proxy = (
host for host in no_proxy.replace(' ', '').split(',') if host
)
# the end of the hostname, both with and without the port.
no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)
ip = netloc.split(':')[0]
if is_ipv4_address(ip):
if is_ipv4_address(parsed.hostname):
for proxy_ip in no_proxy:
if is_valid_cidr(proxy_ip):
if address_in_network(ip, proxy_ip):
if address_in_network(parsed.hostname, proxy_ip):
return True
elif ip == proxy_ip:
elif parsed.hostname == proxy_ip:
# If no_proxy ip was defined in plain IP notation instead of cidr notation &
# matches the IP of the index
return True
else:
host_with_port = parsed.hostname
if parsed.port:
host_with_port += f":{parsed.port}"
for host in no_proxy:
if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
if parsed.hostname.endswith(host) or host_with_port.endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
return True
# If the system proxy settings indicate that this URL should be bypassed,
# don't proxy.
# The proxy_bypass function is incredibly buggy on OS X in early versions
# of Python 2.6, so allow this call to fail. Only catch the specific
# exceptions we've seen, though: this call failing in other ways can reveal
# legitimate problems.
with set_environ('no_proxy', no_proxy_arg):
with set_environ("no_proxy", no_proxy_arg):
# parsed.hostname can be `None` in cases such as a file URI.
try:
bypass = proxy_bypass(netloc)
bypass = proxy_bypass(parsed.hostname)
except (TypeError, socket.gaierror):
bypass = False
@@ -704,13 +844,13 @@ def select_proxy(url, proxies):
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
return proxies.get(urlparts.scheme, proxies.get('all'))
return proxies.get(urlparts.scheme, proxies.get("all"))
proxy_keys = [
urlparts.scheme + '://' + urlparts.hostname,
urlparts.scheme + "://" + urlparts.hostname,
urlparts.scheme,
'all://' + urlparts.hostname,
'all',
"all://" + urlparts.hostname,
"all",
]
proxy = None
for proxy_key in proxy_keys:
@@ -721,29 +861,58 @@ def select_proxy(url, proxies):
return proxy
def resolve_proxies(request, proxies, trust_env=True):
"""This method takes proxy information from a request and configuration
input to resolve a mapping of target proxies. This will consider settings
such as NO_PROXY to strip proxy configurations.
:param request: Request or PreparedRequest
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
:param trust_env: Boolean declaring whether to trust environment configs
:rtype: dict
"""
proxies = proxies if proxies is not None else {}
url = request.url
scheme = urlparse(url).scheme
no_proxy = proxies.get("no_proxy")
new_proxies = proxies.copy()
if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):
environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
proxy = environ_proxies.get(scheme, environ_proxies.get("all"))
if proxy:
new_proxies.setdefault(scheme, proxy)
return new_proxies
def default_user_agent(name="python-requests"):
"""
Return a string representing the default user agent.
:rtype: str
"""
return '%s/%s' % (name, __version__)
return f"{name}/{__version__}"
def default_headers():
"""
:rtype: requests.structures.CaseInsensitiveDict
"""
return CaseInsensitiveDict({
'User-Agent': default_user_agent(),
'Accept-Encoding': ', '.join(('gzip', 'deflate')),
'Accept': '*/*',
'Connection': 'keep-alive',
})
return CaseInsensitiveDict(
{
"User-Agent": default_user_agent(),
"Accept-Encoding": DEFAULT_ACCEPT_ENCODING,
"Accept": "*/*",
"Connection": "keep-alive",
}
)
def parse_header_links(value):
"""Return a dict of parsed link headers proxies.
"""Return a list of parsed link headers proxies.
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
@@ -752,19 +921,23 @@ def parse_header_links(value):
links = []
replace_chars = ' \'"'
replace_chars = " '\""
for val in re.split(', *<', value):
value = value.strip(replace_chars)
if not value:
return links
for val in re.split(", *<", value):
try:
url, params = val.split(';', 1)
url, params = val.split(";", 1)
except ValueError:
url, params = val, ''
url, params = val, ""
link = {'url': url.strip('<> \'"')}
link = {"url": url.strip("<> '\"")}
for param in params.split(';'):
for param in params.split(";"):
try:
key, value = param.split('=')
key, value = param.split("=")
except ValueError:
break
@@ -776,7 +949,7 @@ def parse_header_links(value):
# Null bytes; no need to recreate these on each call to guess_json_utf
_null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
_null = "\x00".encode("ascii") # encoding to ASCII for Python 3
_null2 = _null * 2
_null3 = _null * 3
@@ -790,25 +963,25 @@ def guess_json_utf(data):
# determine the encoding. Also detect a BOM, if present.
sample = data[:4]
if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
return 'utf-32' # BOM included
return "utf-32" # BOM included
if sample[:3] == codecs.BOM_UTF8:
return 'utf-8-sig' # BOM included, MS style (discouraged)
return "utf-8-sig" # BOM included, MS style (discouraged)
if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
return 'utf-16' # BOM included
return "utf-16" # BOM included
nullcount = sample.count(_null)
if nullcount == 0:
return 'utf-8'
return "utf-8"
if nullcount == 2:
if sample[::2] == _null2: # 1st and 3rd are null
return 'utf-16-be'
if sample[::2] == _null2: # 1st and 3rd are null
return "utf-16-be"
if sample[1::2] == _null2: # 2nd and 4th are null
return 'utf-16-le'
return "utf-16-le"
# Did not detect 2 valid UTF-16 ascii-range characters
if nullcount == 3:
if sample[:3] == _null3:
return 'utf-32-be'
return "utf-32-be"
if sample[1:] == _null3:
return 'utf-32-le'
return "utf-32-le"
# Did not detect a valid UTF-32 ascii-range character
return None
@@ -819,15 +992,27 @@ def prepend_scheme_if_needed(url, new_scheme):
:rtype: str
"""
scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
parsed = parse_url(url)
scheme, auth, host, port, path, query, fragment = parsed
# urlparse is a finicky beast, and sometimes decides that there isn't a
# netloc present. Assume that it's being over-cautious, and switch netloc
# and path if urlparse decided there was no netloc.
# A defect in urlparse determines that there isn't a netloc present in some
# urls. We previously assumed parsing was overly cautious, and swapped the
# netloc and path. Due to a lack of tests on the original defect, this is
# maintained with parse_url for backwards compatibility.
netloc = parsed.netloc
if not netloc:
netloc, path = path, netloc
return urlunparse((scheme, netloc, path, params, query, fragment))
if auth:
# parse_url doesn't provide the netloc with auth
# so we'll add it ourselves.
netloc = "@".join([auth, netloc])
if scheme is None:
scheme = new_scheme
if path is None:
path = ""
return urlunparse((scheme, netloc, path, "", query, fragment))
def get_auth_from_url(url):
@@ -841,35 +1026,39 @@ def get_auth_from_url(url):
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth = ('', '')
auth = ("", "")
return auth
# Moved outside of function to avoid recompile every call
_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')
def check_header_validity(header):
"""Verifies that header value is a string which doesn't contain
leading whitespace or return characters. This prevents unintended
header injection.
"""Verifies that header parts don't contain leading whitespace
reserved characters, or return characters.
:param header: tuple, in the format (name, value).
"""
name, value = header
_validate_header_part(header, name, 0)
_validate_header_part(header, value, 1)
if isinstance(value, bytes):
pat = _CLEAN_HEADER_REGEX_BYTE
def _validate_header_part(header, header_part, header_validator_index):
if isinstance(header_part, str):
validator = _HEADER_VALIDATORS_STR[header_validator_index]
elif isinstance(header_part, bytes):
validator = _HEADER_VALIDATORS_BYTE[header_validator_index]
else:
pat = _CLEAN_HEADER_REGEX_STR
try:
if not pat.match(value):
raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
except TypeError:
raise InvalidHeader("Header value %s must be of type str or bytes, "
"not %s" % (value, type(value)))
raise InvalidHeader(
f"Header part ({header_part!r}) from {header} "
f"must be of type str or bytes, not {type(header_part)}"
)
if not validator.match(header_part):
header_kind = "name" if header_validator_index == 0 else "value"
raise InvalidHeader(
f"Invalid leading whitespace, reserved character(s), or return "
f"character(s) in header {header_kind}: {header_part!r}"
)
def urldefragauth(url):
@@ -884,21 +1073,24 @@ def urldefragauth(url):
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit('@', 1)[-1]
netloc = netloc.rsplit("@", 1)[-1]
return urlunparse((scheme, netloc, path, params, query, ''))
return urlunparse((scheme, netloc, path, params, query, ""))
def rewind_body(prepared_request):
"""Move file pointer back to its recorded starting position
so it can be read again on redirect.
"""
body_seek = getattr(prepared_request.body, 'seek', None)
if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
body_seek = getattr(prepared_request.body, "seek", None)
if body_seek is not None and isinstance(
prepared_request._body_position, integer_types
):
try:
body_seek(prepared_request._body_position)
except (IOError, OSError):
raise UnrewindableBodyError("An error occurred when rewinding request "
"body for redirect.")
except OSError:
raise UnrewindableBodyError(
"An error occurred when rewinding request body for redirect."
)
else:
raise UnrewindableBodyError("Unable to rewind request body for redirect.")

View File

@@ -1,13 +1,14 @@
# -*- coding: utf-8 -*-
"""Requests test package initialisation."""
import warnings
import urllib3
from urllib3.exceptions import SNIMissingWarning
try:
from urllib3.exceptions import SNIMissingWarning
# urllib3 sets SNIMissingWarning to only go off once,
# while this test suite requires it to always fire
# so that it occurs during test_requests.test_https_warnings
warnings.simplefilter('always', SNIMissingWarning)
# urllib3 1.x sets SNIMissingWarning to only go off once,
# while this test suite requires it to always fire
# so that it occurs during test_requests.test_https_warnings
warnings.simplefilter("always", SNIMissingWarning)
except ImportError:
# urllib3 2.0 removed that warning and errors out instead
SNIMissingWarning = None

Some files were not shown because too many files have changed in this diff Show More