Compare commits

...

66 Commits

Author SHA1 Message Date
Kenneth Reitz
638532dd9a v0.9.1 2012-01-06 01:10:53 -05:00
Kenneth Reitz
c6fc7d99b5 Merge branch 'develop' of https://github.com/gazpachoking/requests into develop 2012-01-06 01:08:06 -05:00
Kenneth Reitz
281e0598bc Merge pull request #333 from bryanhelmig/develop
Add eager mode for raising errors immediately.
2012-01-05 22:04:11 -08:00
Bryan Helmig
aa39fb0c80 mention of error modes in quickstart 2012-01-05 14:11:19 -06:00
Bryan Helmig
459a91c54f highway to the danger_mode 2012-01-05 12:50:44 -06:00
Bryan Helmig
115b51e68c add eager mode for raising errors immediately 2012-01-04 22:08:01 -06:00
Kenneth Reitz
4441697e49 Update README.rst 2012-01-03 10:21:13 -05:00
Chase Sterling
5174ab4325 Make sure newlines at chunk borders do not get dropped using iter_lines. 2012-01-03 00:38:59 -05:00
Chase Sterling
95911f059a Refactor r.iter_lines to retrieve more than one byte at a time.
Fixes universal line ending handling, but takes away ability to specyfy
custom line endings.
2012-01-02 16:19:35 -05:00
Kenneth Reitz
e3288d5e33 Update docs/user/install.rst 2012-01-02 02:50:09 -05:00
Kenneth Reitz
49140d6880 2012 2012-01-01 00:44:20 -05:00
Chase Sterling
9c6ffc5303 Refactor stream_decode_gzip and _deflate into one function, stream_decompress.
stream_decompress will now iterate over the raw data if there is a problem with decompression
Remove gzip decoding from Response.content, as urllib3 was doing it anyway.
2011-12-30 22:18:08 -05:00
Chase Sterling
f80984f377 Implement automatic deflating when using response.iter_content. refs #327
Refactor response.iter_lines to use responset.iter_content.
2011-12-30 18:55:56 -05:00
Kenneth Reitz
9c0a0fbd01 ch ch changes 2011-12-28 04:49:51 -05:00
Kenneth Reitz
57dbab2932 v0.9.0 history 2011-12-28 04:48:57 -05:00
Kenneth Reitz
7fdb541e2d make it true 2011-12-28 04:48:27 -05:00
Kenneth Reitz
082f4d8948 packaging 2011-12-28 04:38:38 -05:00
Kenneth Reitz
8aa015ffc9 v0.8.9 2011-12-28 04:26:23 -05:00
Kenneth Reitz
cfb1a478ac ssl hostname 2011-12-28 04:25:43 -05:00
Kenneth Reitz
28db6c3f53 engrish 2011-12-28 03:58:08 -05:00
Kenneth Reitz
5f768b191d certifi v0.0.4 2011-12-28 03:51:41 -05:00
Kenneth Reitz
d9a9a981bc certifi v0.0.2 2011-12-28 03:30:33 -05:00
Kenneth Reitz
9fcfec18da ssl docs 2011-12-28 03:18:40 -05:00
Kenneth Reitz
a83268b01b v0.8.8 release 2011-12-28 03:01:36 -05:00
Kenneth Reitz
a1afbfbaa3 external tests 2011-12-28 03:01:00 -05:00
Kenneth Reitz
4114b04521 v0.8.8! 2011-12-28 03:00:53 -05:00
Kenneth Reitz
f7e67c01ea only use session verify when not modified 2011-12-28 02:57:36 -05:00
Kenneth Reitz
544a5fea59 more info 2011-12-28 02:51:49 -05:00
Kenneth Reitz
0a8bb2e1b3 verification support in sessions 2011-12-28 02:51:42 -05:00
Kenneth Reitz
5184f0c5a9 SSL support! 2011-12-28 02:43:13 -05:00
Kenneth Reitz
9a1a4136ac new SSLError 2011-12-28 02:43:03 -05:00
Kenneth Reitz
ca26c1a253 api cleanup 2011-12-28 02:42:57 -05:00
Kenneth Reitz
a91ac242f3 simplify api.request 2011-12-28 01:51:26 -05:00
Kenneth Reitz
31d495fb02 certifi 2011-12-28 01:28:49 -05:00
Kenneth Reitz
bdda99c0c1 urllib3 update 2011-12-27 23:14:54 -05:00
Kenneth Reitz
9ed93044e0 Merge branch 'develop' 2011-12-24 03:16:54 -05:00
Kenneth Reitz
0bfc029b5e v0.8.7 2011-12-24 03:16:40 -05:00
Kenneth Reitz
4eb2759400 force safe mode for async 2011-12-24 03:06:13 -05:00
Kenneth Reitz
0001f5b651 Merge remote-tracking branch 'origin/develop' into develop 2011-12-23 17:24:34 -05:00
Ori Livneh
e1615e0f1e Make safe_mode handle exceptions more consistently 2011-12-23 16:14:46 -05:00
Kenneth Reitz
3483bae24f Update docs/index.rst 2011-12-22 23:09:27 -05:00
Ori Livneh
716d29c49c fix iteration on null responses in safe_mode 2011-12-22 21:10:43 -05:00
Ori Livneh
a7223f86a9 Undo stupid change to while loop 2011-12-22 17:51:22 -05:00
Ori Livneh
2c0ff95d4d Revert "Revert "Make safe_mode play nice with timeout (fixes #312)""
This reverts commit 91766548d1.
2011-12-22 17:50:43 -05:00
Ori Livneh
91766548d1 Revert "Make safe_mode play nice with timeout (fixes #312)"
This reverts commit 805c4db55413c96c5d6e0f95560119c000f660c9.
2011-12-22 17:42:57 -05:00
Ori Livneh
12f3c65e5a Make safe_mode play nice with timeout (fixes #312) 2011-12-22 16:52:29 -05:00
Kenneth Reitz
f5e421e880 1 instead of True
#313
2011-12-22 11:55:55 -05:00
Kenneth Reitz
9d88ac7b50 Merge branch 'develop' of https://github.com/atdt/requests into develop
Conflicts:
	AUTHORS.rst
2011-12-22 11:55:13 -05:00
Kenneth Reitz
75dc012f41 AUTHORS += 'Ori Livneh'
#313
2011-12-22 11:54:07 -05:00
Ori Livneh
f214b91d77 fix bug that causes iter_lines to truncate content
Currently, if the response does not terminate with a newline, iter_lines
truncates the trailing remainder.
2011-12-20 02:01:37 -05:00
Kenneth Reitz
f80fbad4ff Update AUTHORS.rst 2011-12-19 12:25:59 -05:00
Kenneth Reitz
2e38f54b39 Merge pull request #311 from jemerick/patch-1
Add Twitter Streaming API example to Advanced Usage docs
2011-12-19 08:51:15 -08:00
Jason Emerick
2c153c1556 Add Twitter Streaming API example to Advanced Usage docs 2011-12-19 11:45:32 -05:00
Kenneth Reitz
70fbd27d5c Merge commit 'v0.8.6' 2011-12-18 19:19:14 -05:00
Kenneth Reitz
19a2a6c6d1 Merge branch 'develop' 2011-12-14 10:43:41 -05:00
Kenneth Reitz
8c1fd5db95 Merge branch 'develop' 2011-12-11 11:41:42 -05:00
Kenneth Reitz
d1dfa02070 Merge branch 'develop' 2011-11-27 10:45:19 -05:00
Kenneth Reitz
42b33ae1a1 Merge branch 'develop' 2011-11-19 16:19:40 -05:00
Kenneth Reitz
1165bec773 Merge branch 'develop' 2011-11-15 10:00:05 -05:00
Kenneth Reitz
8f20058d0d Merge branch 'master' of github.com:kennethreitz/requests 2011-11-13 00:51:50 -05:00
Kenneth Reitz
6e9cb09fff Merge branch 'develop' 2011-11-13 00:51:40 -05:00
Kenneth Reitz
b40128219f Merge branch 'develop' 2011-11-12 18:35:39 -05:00
Kenneth Reitz
72943d0247 Merge branch 'develop' 2011-11-07 14:21:31 -05:00
Kenneth Reitz
d0b96f8e3b Merge branch 'develop' 2011-11-04 23:33:12 -04:00
Kenneth Reitz
3326030862 Merge branch 'develop' 2011-10-26 18:38:50 -04:00
Kenneth Reitz
c60618ae01 Merge branch 'develop' 2011-10-23 16:57:28 -04:00
24 changed files with 410 additions and 130 deletions

View File

@@ -65,4 +65,7 @@ Patches and Suggestions
- Idan Gazit
- Ed Summers
- Chris Van Horne
- Christopher Davis
- Christopher Davis
- Ori Livneh
- Jason Emerick
- Bryan Helmig

View File

@@ -1,13 +1,47 @@
History
-------
0.9.1 (2012-01-06)
++++++++++++++++++
* danger_mode for automatic Response.raise_for_status()
* Response.iter_lines refator
0.9.0 (2011-12-28)
++++++++++++++++++
* verify ssl is default.
0.8.9 (2011-12-28)
++++++++++++++++++
* Packaging fix.
0.8.8 (2011-12-28)
++++++++++++++++++
* SSL CERT VERIFICATION!
* Release of Cerifi: Mozilla's cert list.
* New 'verify' argument for SSL requests.
* Urllib3 update.
0.8.7 (2011-12-24)
++++++++++++++++++
* iter_lines last-line truncation fix
* Force safe_mode for async requests
* Handle safe_mode exceptions more consistently
* Fix iteration on null responses in safe_mode
0.8.6 (2011-12-18)
++++++++++++++++++
* Socket timeout fixes.
* Proxy Authorization support.
0.8.5 (2011-12-14)
++++++++++++++++++

View File

@@ -1,4 +1,4 @@
Copyright (c) 2011 Kenneth Reitz.
Copyright (c) 2012 Kenneth Reitz.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above

View File

@@ -34,9 +34,10 @@ all the hard work and crazy hacks for you.
Features
--------
- Browser standard SSL verification.
- Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests.
- Gevent support for Asyncronous Requests.
- Sessions with cookie persistience.
- Sessions with cookie persistence.
- Basic, Digest, and Custom Authentication support.
- Automatic form-encoding of dictionaries
- A simple dictionary interface for request/response cookies.
@@ -48,7 +49,7 @@ Features
Usage
-----
It couldn't be simpler. ::
It couldn't be simpler::
>>> import requests
>>> r = requests.get('http://google.com')

View File

@@ -81,3 +81,9 @@ Proxy Support?
You bet!
SSL Verification?
-----------------
Absolutely.

View File

@@ -43,7 +43,7 @@ master_doc = 'index'
# General information about the project.
project = u'Requests'
copyright = u'2011. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'
copyright = u'2012. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the

View File

@@ -38,7 +38,7 @@ Testimonials
`Twitter, Inc <http://twitter.com>`_,
`Readability <http://readability.com>`_, and
Federal US Institutions
use Requests internally. It has been installed over 45,000 times from PyPI.
use Requests internally. It has been installed over 60,000 times from PyPI.
**Armin Ronacher**
Requests is the perfect example how beautiful an API can be with the
@@ -65,14 +65,13 @@ 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
- Unicode Response Bodies
- Multipart File Uploads
- Connection Timeouts
- Zero Dependencies
User Guide

View File

@@ -45,9 +45,24 @@ Any dictionaries that you pass to a request method will be merged with the sessi
All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more.
SSL Cert Verification
---------------------
Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a host's SSL certificate, you can use the ``verify`` argument::
>>> requests.get('https://kennethreitz.com', verify=True)
requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'
I don't have SSL setup on this domain, so it fails. Excellent. I do have certs for httpbin.org though::
>>> requests.get('https://httpbin.org', verify=True)
<Response [200]>
You can also pass ``verify`` the path to a CA_BUNDLE file for private certs. You can also set the ``REQUESTS_CA_BUNDLE`` environment variable.
Body Content Workflow
----------------------
---------------------
By default, when you make a request, the body of the response isn't downloaded immediately. The response headers are downloaded when you make a request, but the content isn't downloaded until you access the :class:`Response.content` attribute.
@@ -243,6 +258,27 @@ Then, we can make a request using our Pizza Auth::
<Response [200]>
Streaming Requests
------------------
With ``requests.Response.iter_lines()`` you can easily iterate over streaming
APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.
To use the Twitter Streaming API to track the keyword "requests":
::
import requests
import json
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'track': 'requests'}, auth=('username', 'password'))
for line in r.iter_lines():
if line: # filter out keep-alive new lines
print json.loads(line)
Verbose Logging
---------------

View File

@@ -26,9 +26,9 @@ Cheeseshop Mirror
-----------------
If the Cheeseshop is down, you can also install Requests from Kenneth Reitz's
personal `Cheeseshop mirror <http://pip.kreitz.co/>`_::
personal `Cheeseshop mirror <http://pip.kennethreitz.com/>`_::
$ pip install -i http://pip.kreitz.co/simple requests
$ pip install -i http://pip.kennethreitz.com/simple requests
Get the Code

View File

@@ -364,6 +364,10 @@ If a request exceeds the configured number of maximum redirections, a :class:`To
All exceptions that Requests explicitly raises inherit from
:class:`requests.exceptions.RequestException`.
You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions
via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions
with the ``safe_mode`` option.
-----------------------
Ready for more? Check out the :ref:`advanced <advanced>` section.

View File

@@ -9,17 +9,17 @@
requests
~~~~~~~~
:copyright: (c) 2011 by Kenneth Reitz.
:copyright: (c) 2012 by Kenneth Reitz.
:license: ISC, see LICENSE for more details.
"""
__title__ = 'requests'
__version__ = '0.8.6'
__build__ = 0x000806
__version__ = '0.9.1'
__build__ = 0x000901
__author__ = 'Kenneth Reitz'
__license__ = 'ISC'
__copyright__ = 'Copyright 2011 Kenneth Reitz'
__copyright__ = 'Copyright 2012 Kenneth Reitz'

View File

@@ -6,28 +6,14 @@ requests.api
This module implements the Requests API.
:copyright: (c) 2011 by Kenneth Reitz.
:copyright: (c) 2012 by Kenneth Reitz.
:license: ISC, see LICENSE for more details.
"""
from . import sessions
def request(method, url,
params=None,
data=None,
headers=None,
cookies=None,
files=None,
auth=None,
timeout=None,
allow_redirects=False,
proxies=None,
hooks=None,
return_response=True,
prefetch=False,
session=None,
config=None):
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
Returns :class:`Response <Response>` object.
@@ -45,26 +31,11 @@ def request(method, url,
:param return_response: (optional) If False, an un-sent Request object will returned.
:param session: (optional) A :class:`Session` object to be used for the request.
:param config: (optional) A configuration dictionary.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
"""
s = session or sessions.session()
return s.request(
method=method,
url=url,
params=params,
data=data,
headers=headers,
cookies=cookies,
files=files,
auth=auth,
timeout=timeout,
allow_redirects=allow_redirects,
proxies=proxies,
hooks=hooks,
return_response=return_response,
config=config,
prefetch=prefetch
)
s = kwargs.get('session') or sessions.session()
return s.request(method=method, url=url, **kwargs)

View File

@@ -36,6 +36,11 @@ def patched(f):
kwargs['return_response'] = False
kwargs['prefetch'] = True
config = kwargs.get('config', {})
config.update(safe_mode=True)
kwargs['config'] = config
return f(*args, **kwargs)
return wrapped

View File

@@ -15,6 +15,7 @@ Configurations:
:decode_unicode: Decode unicode responses automatically?
:keep_alive: Reuse HTTP Connections?
:max_retries: The number of times a request should be retried in the event of a connection failure.
:danger_mode: If true, Requests will raise errors immediately.
:safe_mode: If true, Requests will catch all errors.
:pool_maxsize: The maximium size of an HTTP connection pool.
:pool_connections: The number of active HTTP connection pools to use.
@@ -38,5 +39,6 @@ defaults['decode_unicode'] = True
defaults['pool_connections'] = 10
defaults['pool_maxsize'] = 10
defaults['max_retries'] = 0
defaults['danger_mode'] = False
defaults['safe_mode'] = False
defaults['keep_alive'] = True

View File

@@ -18,6 +18,9 @@ class HTTPError(RequestException):
class ConnectionError(RequestException):
"""A Connection error occurred."""
class SSLError(ConnectionError):
"""An SSL error occurred."""
class Timeout(RequestException):
"""The request timed out."""

View File

@@ -7,8 +7,8 @@ requests.models
This module contains the primary objects that power Requests.
"""
import os
import urllib
import zlib
from urlparse import urlparse, urlunparse, urljoin, urlsplit
from datetime import datetime
@@ -18,16 +18,18 @@ from .structures import CaseInsensitiveDict
from .status_codes import codes
from .packages import oreos
from .auth import HTTPBasicAuth, HTTPProxyAuth
from .packages.urllib3.response import HTTPResponse
from .packages.urllib3.exceptions import MaxRetryError
from .packages.urllib3.exceptions import SSLError as _SSLError
from .packages.urllib3.exceptions import HTTPError as _HTTPError
from .packages.urllib3 import connectionpool, poolmanager
from .packages.urllib3.filepost import encode_multipart_formdata
from .exceptions import (
Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)
ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,
URLRequired, SSLError)
from .utils import (
get_encoding_from_headers, stream_decode_response_unicode,
decode_gzip, stream_decode_gzip, guess_filename, requote_path)
stream_decompress, guess_filename, requote_path)
REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)
@@ -54,7 +56,8 @@ class Request(object):
proxies=None,
hooks=None,
config=None,
_poolmanager=None):
_poolmanager=None,
verify=None):
#: Float describes the timeout of the request.
# (Use socket.setdefaulttimeout() as fallback)
@@ -116,11 +119,15 @@ class Request(object):
#: Session.
self.session = None
#: SSL Verification.
self.verify = verify
if headers:
headers = CaseInsensitiveDict(self.headers)
else:
headers = CaseInsensitiveDict()
# Add configured base headers.
for (k, v) in self.config.get('base_headers', {}).items():
if k not in headers:
headers[k] = v
@@ -171,6 +178,9 @@ class Request(object):
# Save cookies in Response.
response.cookies = cookies
# No exceptions were harmed in the making of this request.
response.error = getattr(resp, 'error', None)
# Save original response for later.
response.raw = resp
@@ -237,6 +247,7 @@ class Request(object):
timeout=self.timeout,
_poolmanager=self._poolmanager,
proxies = self.proxies,
verify = self.verify
)
request.send()
@@ -420,6 +431,30 @@ class Request(object):
else:
conn = connectionpool.connection_from_url(url)
if url.startswith('https') and self.verify:
cert_loc = None
# Allow self-specified cert location.
if self.verify is not True:
cert_loc = self.verify
# Look for configuration.
if not cert_loc:
cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')
# Curl compatiblity.
if not cert_loc:
cert_loc = os.environ.get('CURL_CA_BUNDLE')
# Use the awesome certifi list.
if not cert_loc:
cert_loc = __import__('certifi').where()
conn.cert_reqs = 'CERT_REQUIRED'
conn.ca_certs = cert_loc
if not self.sent or anyway:
if self.cookies:
@@ -439,32 +474,43 @@ class Request(object):
self.headers['Cookie'] = cookie_header
try:
# Send the request.
r = conn.urlopen(
method=self.method,
url=self.path_url,
body=body,
headers=self.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.config.get('max_retries', 0),
timeout=self.timeout,
)
self.sent = True
# The inner try .. except re-raises certain exceptions as
# internal exception types; the outer suppresses exceptions
# when safe mode is set.
try:
# Send the request.
r = conn.urlopen(
method=self.method,
url=self.path_url,
body=body,
headers=self.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=True,
retries=self.config.get('max_retries', 0),
timeout=self.timeout,
)
self.sent = True
except MaxRetryError, e:
if not self.config.get('safe_mode', False):
except MaxRetryError, e:
raise ConnectionError(e)
else:
r = None
except (_SSLError, _HTTPError), e:
if not self.config.get('safe_mode', False):
except (_SSLError, _HTTPError), e:
if self.verify and isinstance(e, _SSLError):
raise SSLError(e)
raise Timeout('Request timed out.')
except RequestException, e:
if self.config.get('safe_mode', False):
# In safe mode, catch the exception and attach it to
# a blank urllib3.HTTPResponse object.
r = HTTPResponse()
r.error = e
else:
raise
self._build_response(r)
# Response manipulation hook.
@@ -478,6 +524,9 @@ class Request(object):
if prefetch:
# Save the response.
self.response.content
if self.config.get('danger_mode'):
self.response.raise_for_status()
return self.sent
@@ -567,7 +616,9 @@ class Response(object):
gen = generate()
if 'gzip' in self.headers.get('content-encoding', ''):
gen = stream_decode_gzip(gen)
gen = stream_decompress(gen, mode='gzip')
elif 'deflate' in self.headers.get('content-encoding', ''):
gen = stream_decompress(gen, mode='deflate')
if decode_unicode is None:
decode_unicode = self.config.get('decode_unicode')
@@ -578,50 +629,25 @@ class Response(object):
return gen
def iter_lines(self, newlines=None, decode_unicode=None):
def iter_lines(self, chunk_size=10 * 1024, decode_unicode=None):
"""Iterates over the response data, one line at a time. This
avoids reading the content at once into memory for large
responses.
:param newlines: a collection of bytes to seperate lines with.
"""
if newlines is None:
newlines = ('\r', '\n', '\r\n')
pending = None
for chunk in self.iter_content(chunk_size, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
lines = chunk.splitlines(True)
for line in lines[:-1]:
yield line.rstrip()
# Save the last part of the chunk for next iteration, to keep full line together
pending = lines[-1]
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed'
)
def generate():
chunk = []
while 1:
c = self.raw.read(1)
if not c:
break
if c in newlines:
yield ''.join(chunk)
chunk = []
else:
chunk.append(c)
self._content_consumed = True
gen = generate()
if 'gzip' in self.headers.get('content-encoding', ''):
gen = stream_decode_gzip(gen)
if decode_unicode is None:
decode_unicode = self.config.get('decode_unicode')
if decode_unicode:
gen = stream_decode_response_unicode(gen, self)
return gen
# Yield the last line
if pending is not None:
yield pending.rstrip()
@property
@@ -643,13 +669,6 @@ class Response(object):
content = self._content
# Decode GZip'd content.
if 'gzip' in self.headers.get('content-encoding', ''):
try:
content = decode_gzip(self._content)
except zlib.error:
pass
# Decode unicode content.
if self.config.get('decode_unicode'):

View File

@@ -13,6 +13,7 @@ from Queue import Queue, Empty, Full
from select import select
from socket import error as SocketError, timeout as SocketTimeout
from .packages.ssl_match_hostname import match_hostname, CertificateError
try:
import ssl
@@ -70,7 +71,8 @@ class VerifiedHTTPSConnection(HTTPSConnection):
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs)
if self.ca_certs:
match_hostname(self.sock.getpeercert(), self.host)
## Pool objects
@@ -364,6 +366,10 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
# SSL certificate error
raise SSLError(e)
except (CertificateError), e:
# Name mismatch
raise SSLError(e)
except (HTTPException, SocketError), e:
# Connection broken, discard. It will be replaced next _get_conn().
conn = None

View File

@@ -0,0 +1,4 @@
from __future__ import absolute_import
from . import ssl_match_hostname

View File

@@ -0,0 +1,61 @@
"""The match_hostname() function from Python 3.2, essential when using SSL."""
import re
__version__ = '3.2.2'
class CertificateError(ValueError):
pass
def _dnsname_to_pat(dn):
pats = []
for frag in dn.split(r'.'):
if frag == '*':
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.
pats.append('[^.]+')
else:
# Otherwise, '*' matches any dotless fragment.
frag = re.escape(frag)
pats.append(frag.replace(r'\*', '[^.]*'))
return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
def match_hostname(cert, hostname):
"""Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
are mostly followed, but IP addresses are not accepted for *hostname*.
CertificateError is raised on failure. On success, the function
returns nothing.
"""
if not cert:
raise ValueError("empty or no certificate")
dnsnames = []
san = cert.get('subjectAltName', ())
for key, value in san:
if key == 'DNS':
if _dnsname_to_pat(value).match(hostname):
return
dnsnames.append(value)
if not dnsnames:
# The subject is only checked when there is no dNSName entry
# in subjectAltName
for sub in cert.get('subject', ()):
for key, value in sub:
# XXX according to RFC 2818, the most specific Common Name
# must be used.
if key == 'commonName':
if _dnsname_to_pat(value).match(hostname):
return
dnsnames.append(value)
if len(dnsnames) > 1:
raise CertificateError("hostname %r "
"doesn't match either of %s"
% (hostname, ', '.join(map(repr, dnsnames))))
elif len(dnsnames) == 1:
raise CertificateError("hostname %r "
"doesn't match %r"
% (hostname, dnsnames[0]))
else:
raise CertificateError("no appropriate commonName or "
"subjectAltName fields were found")

View File

@@ -63,7 +63,8 @@ class Session(object):
proxies=None,
hooks=None,
params=None,
config=None):
config=None,
verify=True):
self.headers = headers or {}
self.cookies = cookies or {}
@@ -73,6 +74,7 @@ class Session(object):
self.hooks = hooks or {}
self.params = params or {}
self.config = config or {}
self.verify = verify
for (k, v) in defaults.items():
self.config.setdefault(k, v)
@@ -111,7 +113,8 @@ class Session(object):
hooks=None,
return_response=True,
config=None,
prefetch=False):
prefetch=False,
verify=None):
"""Constructs and sends a :class:`Request <Request>`.
Returns :class:`Response <Response>` object.
@@ -130,6 +133,7 @@ class Session(object):
:param return_response: (optional) If False, an un-sent Request object will returned.
:param config: (optional) A configuration dictionary.
:param prefetch: (optional) if ``True``, the response content will be immediately downloaded.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
"""
method = str(method).upper()
@@ -141,6 +145,10 @@ class Session(object):
headers = {} if headers is None else headers
params = {} if params is None else params
hooks = {} if hooks is None else hooks
if verify is None:
verify = self.verify
# use session's hooks as defaults
for key, cb in self.hooks.iteritems():
hooks.setdefault(key, cb)
@@ -164,6 +172,7 @@ class Session(object):
allow_redirects=allow_redirects,
proxies=proxies,
config=config,
verify=verify,
_poolmanager=self.poolmanager
)

View File

@@ -354,20 +354,37 @@ def decode_gzip(content):
return zlib.decompress(content, 16 + zlib.MAX_WBITS)
def stream_decode_gzip(iterator):
"""Stream decodes a gzip-encoded iterator"""
def stream_decompress(iterator, mode='gzip'):
"""
Stream decodes an iterator over compressed data
:param iterator: An iterator over compressed data
:param mode: 'gzip' or 'deflate'
:return: An iterator over decompressed data
"""
if mode not in ['gzip', 'deflate']:
raise ValueError('stream_decompress mode must be gzip or deflate')
zlib_mode = 16 + zlib.MAX_WBITS if mode == 'gzip' else -zlib.MAX_WBITS
dec = zlib.decompressobj(zlib_mode)
try:
dec = zlib.decompressobj(16 + zlib.MAX_WBITS)
for chunk in iterator:
rv = dec.decompress(chunk)
if rv:
yield rv
except zlib.error:
# If there was an error decompressing, just return the raw chunk
yield chunk
# Continue to return the rest of the raw data
for chunk in iterator:
yield chunk
else:
# Make sure everything has been returned from the decompression object
buf = dec.decompress('')
rv = buf + dec.flush()
if rv:
yield rv
except zlib.error:
pass
def requote_path(path):

View File

@@ -20,7 +20,9 @@ if sys.argv[-1] == 'test':
os.system('python test_requests.py')
sys.exit()
required = []
required = [
'certifi>=0.0.4'
]
if sys.version_info[:2] < (2,6):
required.append('simplejson')
@@ -38,6 +40,8 @@ setup(
'requests',
'requests.packages',
'requests.packages.urllib3',
'requests.packages.urllib3.packages',
'requests.packages.urllib3.packages.ssl_match_hostname',
'requests.packages.oreos'
],
package_data={'': ['LICENSE', 'NOTICE']},

View File

@@ -3,6 +3,7 @@
from __future__ import with_statement
import StringIO
import time
import os
import unittest
@@ -278,6 +279,16 @@ class RequestsTestSuite(unittest.TestCase):
r.raise_for_status()
def test_default_status_raising(self):
config = {'danger_mode': True}
args = [httpbin('status', '404')]
kwargs = dict(config=config)
self.assertRaises(HTTPError, requests.get, *args, **kwargs)
r = requests.get(httpbin('status', '200'))
self.assertEqual(r.status_code, 200)
def test_decompress_gzip(self):
r = requests.get(httpbin('gzip'))
@@ -603,5 +614,45 @@ class RequestsTestSuite(unittest.TestCase):
self.assertEqual(i, len_lines)
# Test 'dangling' fragment in responses that do not terminate in
# a newline.
quote = (
'''Why will he not upon our fair request\n'''
'''Untent his person and share the air with us?'''
)
# Make a request and monkey-patch its contents
r = requests.get(httpbin('get'))
r.raw = StringIO.StringIO(quote)
# Make sure iter_lines doesn't chop the trailing bit
lines = '\n'.join(r.iter_lines())
self.assertEqual(lines, quote)
def test_safe_mode(self):
safe = requests.session(config=dict(safe_mode=True))
# Safe mode creates empty responses for failed requests.
# Iterating on these responses should produce empty sequences
r = safe.get('http://_/')
self.assertEquals(list(r.iter_lines()), [])
self.assertIsInstance(r.error, requests.exceptions.ConnectionError)
r = safe.get('http://_/')
self.assertEquals(list(r.iter_content()), [])
self.assertIsInstance(r.error, requests.exceptions.ConnectionError)
# When not in safe mode, should raise Timeout exception
with self.assertRaises(requests.exceptions.Timeout):
r = requests.get(httpbin('stream', '1000'), timeout=0.0001)
# In safe mode, should return a blank response
r = requests.get(httpbin('stream', '1000'), timeout=0.0001,
config=dict(safe_mode=True))
self.assertIsNone(r.content)
self.assertIsInstance(r.error, requests.exceptions.Timeout)
if __name__ == '__main__':
unittest.main()

45
test_requests_ext.py Normal file
View File

@@ -0,0 +1,45 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import unittest
import requests
try:
import omnijson as json
except ImportError:
import json
class RequestsTestSuite(unittest.TestCase):
"""Requests test cases."""
# It goes to eleven.
_multiprocess_can_split_ = True
def test_addition(self):
assert (1 + 1) == 2
def test_ssl_hostname_ok(self):
requests.get('https://github.com', verify=True)
def test_ssl_hostname_not_ok(self):
requests.get('https://kennethreitz.com', verify=False)
self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')
def test_ssl_hostname_session_not_ok(self):
s = requests.session()
s.get('https://kennethreitz.com', verify=False)
self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')
if __name__ == '__main__':
unittest.main()