nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__getitem__
(self, key)
return self._store[key.lower()][1]
51
52
def __getitem__(self, key): return self._store[key.lower()][1]
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L51-L52
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __getitem__(self, key): return self._store[key.lower()][1]
22,085
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__delitem__
(self, key)
54
55
def __delitem__(self, key): del self._store[key.lower()]
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L54-L55
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __delitem__(self, key): del self._store[key.lower()]
22,086
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__iter__
(self)
return (casedkey for casedkey, mappedvalue in self._store.values())
57
58
def __iter__(self): return (casedkey for casedkey, mappedvalue in self._store.values())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L57-L58
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __iter__(self): return (casedkey for casedkey, mappedvalue in self._store.values())
22,087
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__len__
(self)
return len(self._store)
60
61
def __len__(self): return len(self._store)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L60-L61
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __len__(self): return len(self._store)
22,088
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.lower_items
(self)
return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
Like iteritems(), but with all lowercase keys.
Like iteritems(), but with all lowercase keys.
63
65
def lower_items(self): """Like iteritems(), but with all lowercase keys.""" return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L63-L65
33
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
1
def lower_items(self): return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
22,089
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__eq__
(self, other)
return dict(self.lower_items()) == dict(other.lower_items())
67
73
def __eq__(self, other): if isinstance(other, Mapping): other = CaseInsensitiveDict(other) else: return NotImplemented # Compare insensitively return dict(self.lower_items()) == dict(other.lower_items())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L67-L73
33
[ 0, 1, 2, 4, 5, 6 ]
85.714286
[]
0
false
100
7
2
100
0
def __eq__(self, other): if isinstance(other, Mapping): other = CaseInsensitiveDict(other) else: return NotImplemented # Compare insensitively return dict(self.lower_items()) == dict(other.lower_items())
22,090
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.copy
(self)
return CaseInsensitiveDict(self._store.values())
76
77
def copy(self): return CaseInsensitiveDict(self._store.values())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L76-L77
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def copy(self): return CaseInsensitiveDict(self._store.values())
22,091
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__repr__
(self)
return str(dict(self.items()))
79
80
def __repr__(self): return str(dict(self.items()))
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L79-L80
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __repr__(self): return str(dict(self.items()))
22,092
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
LookupDict.__init__
(self, name=None)
86
88
def __init__(self, name=None): self.name = name super().__init__()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L86-L88
33
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
0
def __init__(self, name=None): self.name = name super().__init__()
22,093
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
LookupDict.__repr__
(self)
return f"<lookup '{self.name}'>"
90
91
def __repr__(self): return f"<lookup '{self.name}'>"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L90-L91
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __repr__(self): return f"<lookup '{self.name}'>"
22,094
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
LookupDict.__getitem__
(self, key)
return self.__dict__.get(key, None)
93
96
def __getitem__(self, key): # We allow fall-through here, so values default to None return self.__dict__.get(key, None)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L93-L96
33
[ 0, 1, 2, 3 ]
100
[]
0
true
100
4
1
100
0
def __getitem__(self, key): # We allow fall-through here, so values default to None return self.__dict__.get(key, None)
22,095
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
LookupDict.get
(self, key, default=None)
return self.__dict__.get(key, default)
98
99
def get(self, key, default=None): return self.__dict__.get(key, default)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L98-L99
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def get(self, key, default=None): return self.__dict__.get(key, default)
22,096
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/status_codes.py
_init
()
109
125
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 )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/status_codes.py#L109-L125
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12 ]
70.588235
[]
0
false
100
17
5
100
0
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 )
22,097
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
merge_setting
(request_setting, session_setting, dict_class=OrderedDict)
return merged_setting
Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class`
Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class`
61
88
def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. none_keys = [k for (k, v) in merged_setting.items() if v is None] for key in none_keys: del merged_setting[key] return merged_setting
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L61-L88
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
95.522388
28
7
100
3
def merge_setting(request_setting, session_setting, dict_class=OrderedDict): if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. none_keys = [k for (k, v) in merged_setting.items() if v is None] for key in none_keys: del merged_setting[key] return merged_setting
22,098
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
merge_hooks
(request_hooks, session_hooks, dict_class=OrderedDict)
return merge_setting(request_hooks, session_hooks, dict_class)
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely.
Properly merges both requests and session hooks.
91
103
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get("response") == []: return request_hooks if request_hooks is None or request_hooks.get("response") == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L91-L103
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
95.522388
13
5
100
4
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): if session_hooks is None or session_hooks.get("response") == []: return request_hooks if request_hooks is None or request_hooks.get("response") == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
22,099
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
session
()
return 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
Returns a :class:`Session` for context-management.
819
831
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()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L819-L831
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
95.522388
13
1
100
9
def session(): return Session()
22,100
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
SessionRedirectMixin.get_redirect_target
(self, resp)
return None
Receives a Response. Returns a redirect URI or ``None``
Receives a Response. Returns a redirect URI or ``None``
107
125
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"] # 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. location = location.encode("latin1") return to_native_string(location, "utf8") return None
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L107-L125
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
95.522388
19
2
100
1
def get_redirect_target(self, resp): # 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"] # 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. location = location.encode("latin1") return to_native_string(location, "utf8") return None
22,101
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
SessionRedirectMixin.should_strip_auth
(self, old_url, new_url)
return changed_port or changed_scheme
Decide whether Authorization header should be removed when redirecting
Decide whether Authorization header should be removed when redirecting
127
157
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
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L127-L157
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]
100
[]
0
true
95.522388
31
10
100
1
def should_strip_auth(self, old_url, new_url): 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
22,102
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
SessionRedirectMixin.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.
Receives a Response. Returns a generator of Responses or Requests.
159
281
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() # Update history and keep track of redirects. # resp.history must ignore the original request in this loop hist.append(resp) resp.history = hist[1:] try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if len(resp.history) >= self.max_redirects: 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("//"): parsed_rurl = urlparse(resp.url) url = ":".join([to_native_string(parsed_rurl.scheme), url]) # 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. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # 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 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 # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # 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 ) # Attempt to rewind consumed file-like object. if rewindable: rewind_body(prepared_request) # Override the original request. req = prepared_request if yield_requests: yield req else: resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs, ) 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
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L159-L281
33
[ 0, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 63, 64, 65, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 98, 99, 100, 101, 102, 103, 104, 106, 107, 117, 118, 119, 120, 121, 122 ]
73.98374
[]
0
false
95.522388
123
15
100
1
def resolve_redirects( self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs, ): hist = [] # keep track of history url = self.get_redirect_target(resp) previous_fragment = urlparse(req.url).fragment while url: prepared_request = req.copy() # Update history and keep track of redirects. # resp.history must ignore the original request in this loop hist.append(resp) resp.history = hist[1:] try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if len(resp.history) >= self.max_redirects: 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("//"): parsed_rurl = urlparse(resp.url) url = ":".join([to_native_string(parsed_rurl.scheme), url]) # 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. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # 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 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 # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # 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 ) # Attempt to rewind consumed file-like object. if rewindable: rewind_body(prepared_request) # Override the original request. req = prepared_request if yield_requests: yield req else: resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs, ) 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
22,103
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
SessionRedirectMixin.rebuild_auth
(self, prepared_request, response)
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
283
301
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url 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. 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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L283-L301
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
94.736842
[ 18 ]
5.263158
false
95.522388
19
4
94.736842
3
def rebuild_auth(self, prepared_request, response): headers = prepared_request.headers url = prepared_request.url 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. 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)
22,104
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
SessionRedirectMixin.rebuild_proxies
(self, prepared_request, proxies)
return new_proxies
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).
303
330
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 NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ headers = prepared_request.headers scheme = urlparse(prepared_request.url).scheme new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) 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) return new_proxies
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L303-L330
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 26, 27 ]
92.857143
[ 17, 25 ]
7.142857
false
95.522388
28
5
92.857143
10
def rebuild_proxies(self, prepared_request, proxies): headers = prepared_request.headers scheme = urlparse(prepared_request.url).scheme new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) 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) return new_proxies
22,105
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
SessionRedirectMixin.rebuild_method
(self, prepared_request, response)
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
332
352
def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # 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" # 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" prepared_request.method = method
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L332-L352
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
100
[]
0
true
95.522388
21
7
100
2
def rebuild_method(self, prepared_request, response): method = prepared_request.method # 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" # 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" prepared_request.method = method
22,106
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.__init__
(self)
389
449
def __init__(self): #: A case-insensitive dictionary of headers to be sent on each #: :class:`Request <Request>` sent from this #: :class:`Session <Session>`. self.headers = default_headers() #: Default Authentication tuple or object to attach to #: :class:`Request <Request>`. self.auth = None #: Dictionary mapping protocol or protocol and host to the URL of the proxy #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to #: be used on each :class:`Request <Request>`. self.proxies = {} #: Event-handling hooks. self.hooks = default_hooks() #: Dictionary of querystring data to attach to each #: :class:`Request <Request>`. The dictionary values may be lists for #: representing multivalued query parameters. self.params = {} #: Stream response content default. 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 #: cert file (.pem). If Tuple, ('cert', 'key') pair. self.cert = None #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default #: authentication and similar. self.trust_env = True #: A CookieJar containing all currently outstanding cookies set on this #: session. By default it is a #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but #: may be any other ``cookielib.CookieJar`` compatible object. self.cookies = cookiejar_from_dict({}) # Default connection adapters. self.adapters = OrderedDict() self.mount("https://", HTTPAdapter()) self.mount("http://", HTTPAdapter())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L389-L449
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ]
100
[]
0
true
95.522388
61
1
100
0
def __init__(self): #: A case-insensitive dictionary of headers to be sent on each #: :class:`Request <Request>` sent from this #: :class:`Session <Session>`. self.headers = default_headers() #: Default Authentication tuple or object to attach to #: :class:`Request <Request>`. self.auth = None #: Dictionary mapping protocol or protocol and host to the URL of the proxy #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to #: be used on each :class:`Request <Request>`. self.proxies = {} #: Event-handling hooks. self.hooks = default_hooks() #: Dictionary of querystring data to attach to each #: :class:`Request <Request>`. The dictionary values may be lists for #: representing multivalued query parameters. self.params = {} #: Stream response content default. 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 #: cert file (.pem). If Tuple, ('cert', 'key') pair. self.cert = None #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default #: authentication and similar. self.trust_env = True #: A CookieJar containing all currently outstanding cookies set on this #: session. By default it is a #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but #: may be any other ``cookielib.CookieJar`` compatible object. self.cookies = cookiejar_from_dict({}) # Default connection adapters. self.adapters = OrderedDict() self.mount("https://", HTTPAdapter()) self.mount("http://", HTTPAdapter())
22,107
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.__enter__
(self)
return self
451
452
def __enter__(self): return self
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L451-L452
33
[ 0, 1 ]
100
[]
0
true
95.522388
2
1
100
0
def __enter__(self): return self
22,108
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.__exit__
(self, *args)
454
455
def __exit__(self, *args): self.close()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L454-L455
33
[ 0, 1 ]
100
[]
0
true
95.522388
2
1
100
0
def __exit__(self, *args): self.close()
22,109
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.prepare_request
(self, request)
return p
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`.
457
498
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies ) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, 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, hooks=merge_hooks(request.hooks, self.hooks), ) return p
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L457-L498
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
100
[]
0
true
95.522388
42
6
100
8
def prepare_request(self, request): cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies ) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, 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, hooks=merge_hooks(request.hooks, self.hooks), ) return p
22,110
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.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, )
return resp
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :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, 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 :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :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``. 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
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object.
500
589
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. :param method: method for the new :class:`Request` object. :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, 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 :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :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``. 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 """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { "timeout": timeout, "allow_redirects": allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L500-L589
33
[ 0, 60, 61, 73, 74, 75, 76, 77, 81, 82, 86, 87, 88, 89 ]
15.555556
[]
0
false
95.522388
90
4
100
40
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, ): # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { "timeout": timeout, "allow_redirects": allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
22,111
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.get
(self, url, **kwargs)
return self.request("GET", url, **kwargs)
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a GET request. Returns :class:`Response` object.
591
600
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return self.request("GET", url, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L591-L600
33
[ 0, 7, 8, 9 ]
40
[]
0
false
95.522388
10
1
100
5
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return self.request("GET", url, **kwargs)
22,112
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.options
(self, url, **kwargs)
return self.request("OPTIONS", url, **kwargs)
r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a OPTIONS request. Returns :class:`Response` object.
602
611
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return self.request("OPTIONS", url, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L602-L611
33
[ 0 ]
10
[ 8, 9 ]
20
false
95.522388
10
1
80
5
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return self.request("OPTIONS", url, **kwargs)
22,113
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.head
(self, url, **kwargs)
return self.request("HEAD", url, **kwargs)
r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a HEAD request. Returns :class:`Response` object.
613
622
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", False) return self.request("HEAD", url, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L613-L622
33
[ 0 ]
10
[ 8, 9 ]
20
false
95.522388
10
1
80
5
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", False) return self.request("HEAD", url, **kwargs)
22,114
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.post
(self, url, data=None, json=None, **kwargs)
return self.request("POST", url, data=data, json=json, **kwargs)
r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :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
r"""Sends a POST request. Returns :class:`Response` object.
624
635
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, 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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L624-L635
33
[ 0 ]
8.333333
[ 11 ]
8.333333
false
95.522388
12
1
91.666667
8
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, 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)
22,115
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.put
(self, url, data=None, **kwargs)
return self.request("PUT", url, data=data, **kwargs)
r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :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
r"""Sends a PUT request. Returns :class:`Response` object.
637
647
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, 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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L637-L647
33
[ 0 ]
9.090909
[ 10 ]
9.090909
false
95.522388
11
1
90.909091
7
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, 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)
22,116
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.patch
(self, url, data=None, **kwargs)
return self.request("PATCH", url, data=data, **kwargs)
r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :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
r"""Sends a PATCH request. Returns :class:`Response` object.
649
659
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, 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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L649-L659
33
[ 0 ]
9.090909
[ 10 ]
9.090909
false
95.522388
11
1
90.909091
7
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, 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)
22,117
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.delete
(self, url, **kwargs)
return self.request("DELETE", url, **kwargs)
r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a DELETE request. Returns :class:`Response` object.
661
669
def delete(self, url, **kwargs): r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request("DELETE", url, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L661-L669
33
[ 0 ]
11.111111
[ 8 ]
11.111111
false
95.522388
9
1
88.888889
5
def delete(self, url, **kwargs): r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request("DELETE", url, **kwargs)
22,118
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.send
(self, request, **kwargs)
return r
Send a given PreparedRequest. :rtype: requests.Response
Send a given PreparedRequest.
671
747
def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # 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) 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.") # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop("allow_redirects", True) stream = kwargs.get("stream") hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks 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) # Resolve redirects if allowed. 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: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made 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: try: r._next = next( self.resolve_redirects(r, request, yield_requests=True, **kwargs) ) except StopIteration: pass if not stream: r.content return r
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L671-L747
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76 ]
100
[]
0
true
95.522388
77
11
100
3
def send(self, request, **kwargs): # 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) 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.") # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop("allow_redirects", True) stream = kwargs.get("stream") hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks 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) # Resolve redirects if allowed. 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: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made 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: try: r._next = next( self.resolve_redirects(r, request, yield_requests=True, **kwargs) ) except StopIteration: pass if not stream: r.content return r
22,119
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.merge_environment_settings
(self, url, proxies, stream, verify, cert)
return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
Check the environment and merge it with some settings. :rtype: dict
Check the environment and merge it with some settings.
749
778
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # 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 env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # 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") or verify ) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L749-L778
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 ]
100
[]
0
true
95.522388
30
7
100
3
def merge_environment_settings(self, url, proxies, stream, verify, cert): # 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 env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # 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") or verify ) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
22,120
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.get_adapter
(self, url)
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
Returns the appropriate connection adapter for the given URL.
780
792
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema(f"No connection adapters were found for {url!r}")
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L780-L792
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
95.522388
13
3
100
3
def get_adapter(self, url): for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema(f"No connection adapters were found for {url!r}")
22,121
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.close
(self)
Closes all adapters and as such the session
Closes all adapters and as such the session
794
797
def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L794-L797
33
[ 0, 1, 2, 3 ]
100
[]
0
true
95.522388
4
2
100
1
def close(self): for v in self.adapters.values(): v.close()
22,122
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.mount
(self, prefix, adapter)
Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length.
Registers a connection adapter to a prefix.
799
808
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. 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)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L799-L808
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
95.522388
10
3
100
3
def mount(self, prefix, adapter): self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
22,123
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.__getstate__
(self)
return state
810
812
def __getstate__(self): state = {attr: getattr(self, attr, None) for attr in self.__attrs__} return state
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L810-L812
33
[ 0, 1, 2 ]
100
[]
0
true
95.522388
3
1
100
0
def __getstate__(self): state = {attr: getattr(self, attr, None) for attr in self.__attrs__} return state
22,124
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/sessions.py
Session.__setstate__
(self, state)
814
816
def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/sessions.py#L814-L816
33
[ 0, 1, 2 ]
100
[]
0
true
95.522388
3
2
100
0
def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value)
22,125
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/hooks.py
default_hooks
()
return {event: [] for event in HOOKS}
15
16
def default_hooks(): return {event: [] for event in HOOKS}
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/hooks.py#L15-L16
33
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def default_hooks(): return {event: [] for event in HOOKS}
22,126
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/hooks.py
dispatch_hook
(key, hooks, hook_data, **kwargs)
return hook_data
Dispatches a hook dictionary on a given piece of data.
Dispatches a hook dictionary on a given piece of data.
22
33
def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, "__call__"): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/hooks.py#L22-L33
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
100
12
6
100
1
def dispatch_hook(key, hooks, hook_data, **kwargs): hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, "__call__"): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
22,127
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
request
(method, url, **kwargs)
Constructs and sends a :class:`Request <Request>`. :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, 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 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. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :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``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') >>> req <Response [200]>
Constructs and sends a :class:`Request <Request>`.
14
59
def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :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, 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 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. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :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``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') >>> req <Response [200]> """ # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L14-L59
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 ]
100
[]
0
true
84.210526
46
2
100
38
def request(method, url, **kwargs): # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs)
22,128
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
get
(url, params=None, **kwargs)
return request("get", url, params=params, **kwargs)
r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :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
r"""Sends a GET request.
62
73
def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :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 """ return request("get", url, params=params, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L62-L73
33
[ 0, 10, 11 ]
25
[]
0
false
84.210526
12
1
100
8
def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :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 """ return request("get", url, params=params, **kwargs)
22,129
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
options
(url, **kwargs)
return request("options", url, **kwargs)
r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends an OPTIONS request.
76
85
def options(url, **kwargs): r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("options", url, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L76-L85
33
[ 0 ]
10
[ 9 ]
10
false
84.210526
10
1
90
6
def options(url, **kwargs): r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("options", url, **kwargs)
22,130
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
head
(url, **kwargs)
return request("head", url, **kwargs)
r"""Sends a HEAD request. :param url: URL for the new :class:`Request` object. :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
r"""Sends a HEAD request.
88
100
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. 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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L88-L100
33
[ 0, 10, 11, 12 ]
30.769231
[]
0
false
84.210526
13
1
100
8
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. 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)
22,131
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
post
(url, data=None, json=None, **kwargs)
return request("post", url, data=data, json=json, **kwargs)
r"""Sends a POST request. :param url: URL for the new :class:`Request` object. :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 data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends a POST request.
103
115
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, list of tuples, 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 \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("post", url, data=data, json=json, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L103-L115
33
[ 0, 11, 12 ]
23.076923
[]
0
false
84.210526
13
1
100
9
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, list of tuples, 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 \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("post", url, data=data, json=json, **kwargs)
22,132
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
put
(url, data=None, **kwargs)
return request("put", url, data=data, **kwargs)
r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :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 data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends a PUT request.
118
130
def put(url, data=None, **kwargs): r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :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 data 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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L118-L130
33
[ 0, 11, 12 ]
23.076923
[]
0
false
84.210526
13
1
100
9
def put(url, data=None, **kwargs): r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :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 data 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)
22,133
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
patch
(url, data=None, **kwargs)
return request("patch", url, data=data, **kwargs)
r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :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 data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends a PATCH request.
133
145
def patch(url, data=None, **kwargs): r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :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 data 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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L133-L145
33
[ 0 ]
7.692308
[ 12 ]
7.692308
false
84.210526
13
1
92.307692
9
def patch(url, data=None, **kwargs): r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :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 data 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)
22,134
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/api.py
delete
(url, **kwargs)
return request("delete", url, **kwargs)
r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends a DELETE request.
148
157
def delete(url, **kwargs): r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("delete", url, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/api.py#L148-L157
33
[ 0 ]
10
[ 9 ]
10
false
84.210526
10
1
90
6
def delete(url, **kwargs): r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("delete", url, **kwargs)
22,135
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/__init__.py
check_compatibility
(urllib3_version, chardet_version, charset_normalizer_version)
58
86
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, <= 1.26 assert major == 1 assert minor >= 21 assert minor <= 26 # 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: raise Exception("You need either charset_normalizer or chardet installed")
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/__init__.py#L58-L86
33
[ 0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26 ]
72.413793
[ 6, 18, 19, 21, 28 ]
17.241379
false
64.705882
29
10
82.758621
0
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, <= 1.26 assert major == 1 assert minor >= 21 assert minor <= 26 # 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: raise Exception("You need either charset_normalizer or chardet installed")
22,136
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/__init__.py
_check_cryptography
(cryptography_version)
89
100
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)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/__init__.py#L89-L100
33
[ 0, 1 ]
16.666667
[ 2, 3, 4, 5, 7, 8, 11 ]
58.333333
false
64.705882
12
3
41.666667
0
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)
22,137
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/_internal_utils.py
to_native_string
(string, encoding="ascii")
return out
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.
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.
23
33
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. """ if isinstance(string, builtin_str): out = string else: out = string.decode(encoding) return out
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/_internal_utils.py#L23-L33
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
100
11
2
100
3
def to_native_string(string, encoding="ascii"): if isinstance(string, builtin_str): out = string else: out = string.decode(encoding) return out
22,138
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/_internal_utils.py
unicode_is_ascii
(u_string)
Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool
Determine if unicode string only contains ASCII characters.
36
48
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode("ascii") return True except UnicodeEncodeError: return False
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/_internal_utils.py#L36-L48
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
100
13
3
100
5
def unicode_is_ascii(u_string): assert isinstance(u_string, str) try: u_string.encode("ascii") return True except UnicodeEncodeError: return False
22,139
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
_basic_auth_str
(username, password)
return authstr
Returns a Basic Auth string.
Returns a Basic Auth string.
25
66
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backwards compatibility # for things like ints. This will be removed in 3.0.0. 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 ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(username), category=DeprecationWarning, ) username = str(username) 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 ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(type(password)), category=DeprecationWarning, ) password = str(password) # -- End Removal -- if isinstance(username, str): username = username.encode("latin1") if isinstance(password, str): password = password.encode("latin1") authstr = "Basic " + to_native_string( b64encode(b":".join((username, password))).strip() ) return authstr
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L25-L66
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
100
[]
0
true
87.861272
42
5
100
1
def _basic_auth_str(username, password): # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backwards compatibility # for things like ints. This will be removed in 3.0.0. 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 ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(username), category=DeprecationWarning, ) username = str(username) 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 ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(type(password)), category=DeprecationWarning, ) password = str(password) # -- End Removal -- if isinstance(username, str): username = username.encode("latin1") if isinstance(password, str): password = password.encode("latin1") authstr = "Basic " + to_native_string( b64encode(b":".join((username, password))).strip() ) return authstr
22,140
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPBasicAuth.__init__
(self, username, password)
79
81
def __init__(self, username, password): self.username = username self.password = password
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L79-L81
33
[ 0, 1, 2 ]
100
[]
0
true
87.861272
3
1
100
0
def __init__(self, username, password): self.username = username self.password = password
22,141
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPBasicAuth.__eq__
(self, other)
return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] )
83
89
def __eq__(self, other): return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L83-L89
33
[ 0 ]
14.285714
[ 1 ]
14.285714
false
87.861272
7
1
85.714286
0
def __eq__(self, other): return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] )
22,142
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPBasicAuth.__ne__
(self, other)
return not self == other
91
92
def __ne__(self, other): return not self == other
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L91-L92
33
[ 0 ]
50
[ 1 ]
50
false
87.861272
2
1
50
0
def __ne__(self, other): return not self == other
22,143
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPBasicAuth.__call__
(self, r)
return r
94
96
def __call__(self, r): r.headers["Authorization"] = _basic_auth_str(self.username, self.password) return r
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L94-L96
33
[ 0, 1, 2 ]
100
[]
0
true
87.861272
3
1
100
0
def __call__(self, r): r.headers["Authorization"] = _basic_auth_str(self.username, self.password) return r
22,144
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPProxyAuth.__call__
(self, r)
return r
102
104
def __call__(self, r): r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) return r
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L102-L104
33
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
87.861272
3
1
33.333333
0
def __call__(self, r): r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) return r
22,145
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.__init__
(self, username, password)
110
114
def __init__(self, username, password): self.username = username self.password = password # Keep state in per-thread local storage self._thread_local = threading.local()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L110-L114
33
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
87.861272
5
1
100
0
def __init__(self, username, password): self.username = username self.password = password # Keep state in per-thread local storage self._thread_local = threading.local()
22,146
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.init_per_thread_state
(self)
116
124
def init_per_thread_state(self): # Ensure state is initialized just once per-thread if not hasattr(self._thread_local, "init"): self._thread_local.init = True self._thread_local.last_nonce = "" self._thread_local.nonce_count = 0 self._thread_local.chal = {} self._thread_local.pos = None self._thread_local.num_401_calls = None
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L116-L124
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
87.861272
9
2
100
0
def init_per_thread_state(self): # Ensure state is initialized just once per-thread if not hasattr(self._thread_local, "init"): self._thread_local.init = True self._thread_local.last_nonce = "" self._thread_local.nonce_count = 0 self._thread_local.chal = {} self._thread_local.pos = None self._thread_local.num_401_calls = None
22,147
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.build_digest_header
(self, method, url)
return f"Digest {base}"
:rtype: str
:rtype: str
126
234
def build_digest_header(self, method, url): """ :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") hash_utf8 = None if algorithm is None: _algorithm = "MD5" else: _algorithm = algorithm.upper() # lambdas assume digest modules are imported at the top level if _algorithm == "MD5" or _algorithm == "MD5-SESS": def md5_utf8(x): if isinstance(x, str): x = x.encode("utf-8") return hashlib.md5(x).hexdigest() hash_utf8 = md5_utf8 elif _algorithm == "SHA": def sha_utf8(x): if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha1(x).hexdigest() 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 # XXX not implemented yet entdig = None p_parsed = urlparse(url) #: path is request-uri defined in RFC 2616 which should not be empty path = p_parsed.path or "/" if p_parsed.query: path += f"?{p_parsed.query}" A1 = f"{self.username}:{realm}:{self.password}" A2 = f"{method}:{path}" HA1 = hash_utf8(A1) HA2 = hash_utf8(A2) if nonce == self._thread_local.last_nonce: self._thread_local.nonce_count += 1 else: self._thread_local.nonce_count = 1 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(f"{HA1}:{nonce}:{cnonce}") if not qop: 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. return None self._thread_local.last_nonce = nonce # XXX should the partial digests be encoded too? base = ( f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' f'uri="{path}", response="{respdig}"' ) if opaque: base += f', opaque="{opaque}"' if algorithm: base += f', algorithm="{algorithm}"' if entdig: base += f', digest="{entdig}"' if qop: base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' return f"Digest {base}"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L126-L234
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 105, 106, 107, 108 ]
88.073394
[ 27, 28, 29, 30, 32, 53, 61, 81, 84, 90, 104 ]
10.091743
false
87.861272
109
27
89.908257
1
def build_digest_header(self, method, url): 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" else: _algorithm = algorithm.upper() # lambdas assume digest modules are imported at the top level if _algorithm == "MD5" or _algorithm == "MD5-SESS": def md5_utf8(x): if isinstance(x, str): x = x.encode("utf-8") return hashlib.md5(x).hexdigest() hash_utf8 = md5_utf8 elif _algorithm == "SHA": def sha_utf8(x): if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha1(x).hexdigest() 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 # XXX not implemented yet entdig = None p_parsed = urlparse(url) #: path is request-uri defined in RFC 2616 which should not be empty path = p_parsed.path or "/" if p_parsed.query: path += f"?{p_parsed.query}" A1 = f"{self.username}:{realm}:{self.password}" A2 = f"{method}:{path}" HA1 = hash_utf8(A1) HA2 = hash_utf8(A2) if nonce == self._thread_local.last_nonce: self._thread_local.nonce_count += 1 else: self._thread_local.nonce_count = 1 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(f"{HA1}:{nonce}:{cnonce}") if not qop: 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. return None self._thread_local.last_nonce = nonce # XXX should the partial digests be encoded too? base = ( f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' f'uri="{path}", response="{respdig}"' ) if opaque: base += f', opaque="{opaque}"' if algorithm: base += f', algorithm="{algorithm}"' if entdig: base += f', digest="{entdig}"' if qop: base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' return f"Digest {base}"
22,148
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.handle_redirect
(self, r, **kwargs)
Reset num_401_calls counter on redirects.
Reset num_401_calls counter on redirects.
236
239
def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self._thread_local.num_401_calls = 1
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L236-L239
33
[ 0, 1, 2, 3 ]
100
[]
0
true
87.861272
4
2
100
1
def handle_redirect(self, r, **kwargs): if r.is_redirect: self._thread_local.num_401_calls = 1
22,149
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.handle_401
(self, r, **kwargs)
return r
Takes the given response and tries digest-auth, if needed. :rtype: requests.Response
Takes the given response and tries digest-auth, if needed.
241
284
def handle_401(self, r, **kwargs): """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 if not 400 <= r.status_code < 500: self._thread_local.num_401_calls = 1 return r if self._thread_local.pos is not None: # 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: 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)) # Consume content and release the original connection # to allow our new request to reuse the same one. r.content r.close() prep = r.request.copy() 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 ) _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r self._thread_local.num_401_calls = 1 return r
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L241-L284
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
93.181818
[ 16, 42, 43 ]
6.818182
false
87.861272
44
5
93.181818
3
def handle_401(self, r, **kwargs): # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 if not 400 <= r.status_code < 500: self._thread_local.num_401_calls = 1 return r if self._thread_local.pos is not None: # 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: 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)) # Consume content and release the original connection # to allow our new request to reuse the same one. r.content r.close() prep = r.request.copy() 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 ) _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r self._thread_local.num_401_calls = 1 return r
22,150
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.__call__
(self, r)
return r
286
304
def __call__(self, r): # Initialize per-thread state, if needed 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) try: self._thread_local.pos = r.body.tell() except AttributeError: # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # 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) self._thread_local.num_401_calls = 1 return r
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L286-L304
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
87.861272
19
3
100
0
def __call__(self, r): # Initialize per-thread state, if needed 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) try: self._thread_local.pos = r.body.tell() except AttributeError: # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # 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) self._thread_local.num_401_calls = 1 return r
22,151
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.__eq__
(self, other)
return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] )
306
312
def __eq__(self, other): return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L306-L312
33
[ 0 ]
14.285714
[ 1 ]
14.285714
false
87.861272
7
1
85.714286
0
def __eq__(self, other): return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] )
22,152
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/auth.py
HTTPDigestAuth.__ne__
(self, other)
return not self == other
314
315
def __ne__(self, other): return not self == other
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/auth.py#L314-L315
33
[ 0 ]
50
[ 1 ]
50
false
87.861272
2
1
50
0
def __ne__(self, other): return not self == other
22,153
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/help.py
_implementation
()
return {"name": implementation, "version": implementation_version}
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.
Return a dict with the Python implementation and version.
34
66
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}
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/help.py#L34-L66
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 31, 32 ]
51.515152
[ 15, 16, 21, 22, 25, 26, 27, 28, 30 ]
27.272727
false
69.354839
33
6
72.727273
9
def _implementation(): 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}
22,154
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/help.py
info
()
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, }, }
Generate information for a bug report.
Generate information for a bug report.
69
125
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, }, }
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/help.py#L69-L125
33
[ 0, 1, 2, 3, 4, 5, 6, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56 ]
84.210526
[ 7, 8, 20, 27 ]
7.017544
false
69.354839
57
5
92.982456
1
def info(): 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, }, }
22,155
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/help.py
main
()
Pretty-print the bug information as JSON.
Pretty-print the bug information as JSON.
128
130
def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2))
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/help.py#L128-L130
33
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
69.354839
3
1
66.666667
1
def main(): print(json.dumps(info(), sort_keys=True, indent=2))
22,156
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
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 request: our own requests.Request object :param response: urllib3.HTTPResponse object
Extract the cookies from the response into a CookieJar.
124
137
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 request: our own requests.Request object :param response: urllib3.HTTPResponse object """ if not (hasattr(response, "_original_response") and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L124-L137
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
77.824268
14
3
100
5
def extract_cookies_to_jar(jar, request, 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) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req)
22,157
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
get_cookie_header
(jar, request)
return r.get_new_headers().get("Cookie")
Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str
Produce an appropriate Cookie header string to be sent with `request`, or None.
140
148
def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get("Cookie")
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L140-L148
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
77.824268
9
1
100
3
def get_cookie_header(jar, request): r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get("Cookie")
22,158
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
remove_cookie_by_name
(cookiejar, name, domain=None, path=None)
Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n).
Unsets a cookie by name, by default over all domains and paths.
151
167
def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L151-L167
33
[ 0, 1, 2, 3, 4 ]
29.411765
[ 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16 ]
64.705882
false
77.824268
17
8
35.294118
3
def remove_cookie_by_name(cookiejar, name, domain=None, path=None): clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name)
22,159
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
_copy_cookie_jar
(jar)
return new_jar
440
452
def _copy_cookie_jar(jar): if jar is None: return None if hasattr(jar, "copy"): # We're dealing with an instance of RequestsCookieJar return jar.copy() # We're dealing with a generic CookieJar instance new_jar = copy.copy(jar) new_jar.clear() for cookie in jar: new_jar.set_cookie(copy.copy(cookie)) return new_jar
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L440-L452
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
77.824268
13
4
100
0
def _copy_cookie_jar(jar): if jar is None: return None if hasattr(jar, "copy"): # We're dealing with an instance of RequestsCookieJar return jar.copy() # We're dealing with a generic CookieJar instance new_jar = copy.copy(jar) new_jar.clear() for cookie in jar: new_jar.set_cookie(copy.copy(cookie)) return new_jar
22,160
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
create_cookie
(name, value, **kwargs)
return cookielib.Cookie(**result)
Make a cookie from underspecified parameters. 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").
Make a cookie from underspecified parameters.
455
489
def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. 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 = { "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: 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"]) return cookielib.Cookie(**result)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L455-L489
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 27, 28, 29, 30, 31, 32, 33, 34 ]
91.428571
[ 24 ]
2.857143
false
77.824268
35
2
97.142857
4
def create_cookie(name, value, **kwargs): 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: 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"]) return cookielib.Cookie(**result)
22,161
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
morsel_to_cookie
(morsel)
return create_cookie( comment=morsel["comment"], comment_url=bool(morsel["comment"]), discard=False, domain=morsel["domain"], expires=expires, name=morsel.key, path=morsel["path"], port=None, rest={"HttpOnly": morsel["httponly"]}, rfc2109=False, secure=bool(morsel["secure"]), value=morsel.value, version=morsel["version"] or 0, )
Convert a Morsel object into a Cookie containing the one k/v pair.
Convert a Morsel object into a Cookie containing the one k/v pair.
492
518
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel["max-age"]: try: expires = int(time.time() + int(morsel["max-age"])) except ValueError: 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"]), discard=False, domain=morsel["domain"], expires=expires, name=morsel.key, path=morsel["path"], port=None, rest={"HttpOnly": morsel["httponly"]}, rfc2109=False, secure=bool(morsel["secure"]), value=morsel.value, version=morsel["version"] or 0, )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L492-L518
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]
100
[]
0
true
77.824268
27
5
100
1
def morsel_to_cookie(morsel): expires = None if morsel["max-age"]: try: expires = int(time.time() + int(morsel["max-age"])) except ValueError: 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"]), discard=False, domain=morsel["domain"], expires=expires, name=morsel.key, path=morsel["path"], port=None, rest={"HttpOnly": morsel["httponly"]}, rfc2109=False, secure=bool(morsel["secure"]), value=morsel.value, version=morsel["version"] or 0, )
22,162
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
cookiejar_from_dict
(cookie_dict, cookiejar=None, overwrite=True)
return cookiejar
Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :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
Returns a CookieJar from a key/value dictionary.
521
539
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :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() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L521-L539
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
77.824268
19
7
100
7
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar
22,163
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
merge_cookies
(cookiejar, cookies)
return cookiejar
Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar
Add cookies to cookiejar and returns a merged CookieJar.
542
561
def merge_cookies(cookiejar, cookies): """Add cookies to cookiejar and returns a merged CookieJar. :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") if isinstance(cookies, dict): cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L542-L561
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
95
[ 8 ]
5
false
77.824268
20
6
95
5
def merge_cookies(cookiejar, cookies): if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError("You can only merge into CookieJar") if isinstance(cookies, dict): cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
22,164
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.__init__
(self, request)
35
38
def __init__(self, request): self._r = request self._new_headers = {} self.type = urlparse(self._r.url).scheme
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L35-L38
33
[ 0, 1, 2, 3 ]
100
[]
0
true
77.824268
4
1
100
0
def __init__(self, request): self._r = request self._new_headers = {} self.type = urlparse(self._r.url).scheme
22,165
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.get_type
(self)
return self.type
40
41
def get_type(self): return self.type
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L40-L41
33
[ 0 ]
50
[ 1 ]
50
false
77.824268
2
1
50
0
def get_type(self): return self.type
22,166
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.get_host
(self)
return urlparse(self._r.url).netloc
43
44
def get_host(self): return urlparse(self._r.url).netloc
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L43-L44
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def get_host(self): return urlparse(self._r.url).netloc
22,167
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.get_origin_req_host
(self)
return self.get_host()
46
47
def get_origin_req_host(self): return self.get_host()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L46-L47
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def get_origin_req_host(self): return self.get_host()
22,168
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.get_full_url
(self)
return urlunparse( [ parsed.scheme, host, parsed.path, parsed.params, parsed.query, parsed.fragment, ] )
49
67
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"): 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") 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, ] )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L49-L67
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
52.631579
[]
0
false
77.824268
19
2
100
0
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"): 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") 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, ] )
22,169
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.is_unverifiable
(self)
return True
69
70
def is_unverifiable(self): return True
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L69-L70
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def is_unverifiable(self): return True
22,170
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.has_header
(self, name)
return name in self._r.headers or name in self._new_headers
72
73
def has_header(self, name): return name in self._r.headers or name in self._new_headers
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L72-L73
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
2
100
0
def has_header(self, name): return name in self._r.headers or name in self._new_headers
22,171
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.get_header
(self, name, default=None)
return self._r.headers.get(name, self._new_headers.get(name, default))
75
76
def get_header(self, name, default=None): return self._r.headers.get(name, self._new_headers.get(name, default))
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L75-L76
33
[ 0 ]
50
[ 1 ]
50
false
77.824268
2
1
50
0
def get_header(self, name, default=None): return self._r.headers.get(name, self._new_headers.get(name, default))
22,172
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.add_header
(self, key, val)
cookielib has no legitimate use for this method; add it back if you find one.
cookielib has no legitimate use for this method; add it back if you find one.
78
82
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()" )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L78-L82
33
[ 0, 1 ]
40
[ 2 ]
20
false
77.824268
5
1
80
1
def add_header(self, key, val): raise NotImplementedError( "Cookie headers should be added with add_unredirected_header()" )
22,173
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.add_unredirected_header
(self, name, value)
84
85
def add_unredirected_header(self, name, value): self._new_headers[name] = value
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L84-L85
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def add_unredirected_header(self, name, value): self._new_headers[name] = value
22,174
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.get_new_headers
(self)
return self._new_headers
87
88
def get_new_headers(self): return self._new_headers
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L87-L88
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def get_new_headers(self): return self._new_headers
22,175
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.unverifiable
(self)
return self.is_unverifiable()
91
92
def unverifiable(self): return self.is_unverifiable()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L91-L92
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def unverifiable(self): return self.is_unverifiable()
22,176
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.origin_req_host
(self)
return self.get_origin_req_host()
95
96
def origin_req_host(self): return self.get_origin_req_host()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L95-L96
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def origin_req_host(self): return self.get_origin_req_host()
22,177
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockRequest.host
(self)
return self.get_host()
99
100
def host(self): return self.get_host()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L99-L100
33
[ 0 ]
50
[ 1 ]
50
false
77.824268
2
1
50
0
def host(self): return self.get_host()
22,178
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockResponse.__init__
(self, headers)
Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers
Make a MockResponse for `cookielib` to read.
110
115
def __init__(self, headers): """Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers """ self._headers = headers
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L110-L115
33
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
77.824268
6
1
100
3
def __init__(self, headers): self._headers = headers
22,179
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockResponse.info
(self)
return self._headers
117
118
def info(self): return self._headers
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L117-L118
33
[ 0, 1 ]
100
[]
0
true
77.824268
2
1
100
0
def info(self): return self._headers
22,180
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
MockResponse.getheaders
(self, name)
120
121
def getheaders(self, name): self._headers.getheaders(name)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L120-L121
33
[ 0 ]
50
[ 1 ]
50
false
77.824268
2
1
50
0
def getheaders(self, name): self._headers.getheaders(name)
22,181
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.get
(self, name, default=None, domain=None, path=None)
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1).
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.
194
204
def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). """ try: return self._find_no_duplicates(name, domain, path) except KeyError: return default
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L194-L204
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
90.909091
[ 10 ]
9.090909
false
77.824268
11
2
90.909091
5
def get(self, name, default=None, domain=None, path=None): try: return self._find_no_duplicates(name, domain, path) except KeyError: return default
22,182
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.set
(self, name, value, **kwargs)
return c
Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.
Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.
206
223
def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. """ # 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") ) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L206-L223
33
[ 0, 1, 2, 3, 4, 5, 6, 11, 12, 14, 15, 16, 17 ]
72.222222
[ 7, 10, 13 ]
16.666667
false
77.824268
18
3
83.333333
3
def set(self, name, value, **kwargs): # 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") ) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c
22,183
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.iterkeys
(self)
Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems().
Dict-like iterkeys() that returns an iterator of names of cookies from the jar.
225
232
def iterkeys(self): """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems(). """ for cookie in iter(self): yield cookie.name
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L225-L232
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
77.824268
8
2
100
4
def iterkeys(self): for cookie in iter(self): yield cookie.name
22,184