API improvements

This commit is contained in:
2017-05-26 21:07:37 -04:00
parent 14d6fa1472
commit ce64cce14e
2 changed files with 32 additions and 16 deletions
+8
View File
@@ -577,6 +577,10 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
for event in hooks:
self.register_hook(event, hooks[event])
def send(self, session):
"""Sends the given PreparedRequest to the given session."""
return session.send(self)
class Response(object):
"""The :class:`Response <Response>` object, which contains a
@@ -593,6 +597,7 @@ class Response(object):
self._content = False
self._content_consumed = False
self._next = None
#: Integer Code of responded HTTP Status, e.g. 404 or 200.
self.status_code = None
@@ -709,6 +714,9 @@ class Response(object):
"""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))
def next(self):
if self.is_redirect:
return self._next
@property
def apparent_encoding(self):
"""The apparent encoding, provided by the chardet library"""
+24 -16
View File
@@ -114,8 +114,8 @@ class SessionRedirectMixin(object):
return None
def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None, **adapter_kwargs):
"""Receives a Response. Returns a generator of Responses."""
verify=True, cert=None, proxies=None, yield_responses=True, **adapter_kwargs):
"""Receives a Response. Returns a generator of Responses or Requests."""
hist = [] # keep track of history
@@ -203,22 +203,26 @@ class SessionRedirectMixin(object):
# Override the original request.
req = prepared_request
resp = self.send(
req,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
allow_redirects=False,
**adapter_kwargs
)
if not yield_responses:
yield req
else:
extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
resp = self.send(
req,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
allow_redirects=False,
**adapter_kwargs
)
# extract redirect url, if any, for the next loop
url = self.get_redirect_target(resp)
yield resp
extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
# extract redirect url, if any, for the next loop
url = self.get_redirect_target(resp)
yield resp
def rebuild_auth(self, prepared_request, response):
"""When being redirected we may want to strip authentication from the
@@ -668,6 +672,10 @@ class Session(SessionRedirectMixin):
r = history.pop()
r.history = history
# If redirects aren't being followed, store the response on the Request for Response.next().
if not allow_redirects:
r._next = self.resolve_redirects(r, request, yield_responses=False, **kwargs).next()
if not stream:
r.content