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
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.wrap
(self, value)
return self
A string of HTML that will be created on the fly and wrapped around each target: >>> d = PyQuery('<span>youhou</span>') >>> d.wrap('<div></div>') [<div>] >>> print(d) <div><span>youhou</span></div>
A string of HTML that will be created on the fly and wrapped around each target:
1,308
1,341
def wrap(self, value): """A string of HTML that will be created on the fly and wrapped around each target: >>> d = PyQuery('<span>youhou</span>') >>> d.wrap('<div></div>') [<div>] >>> print(d) <div><span>youhou</span></div> """ assert isinstance(value, basestring) value = fromstring(value)[0] nodes = [] for tag in self: wrapper = deepcopy(value) # FIXME: using iterchildren is probably not optimal if not wrapper.getchildren(): wrapper.append(deepcopy(tag)) else: childs = [c for c in wrapper.iterchildren()] child = childs[-1] child.append(deepcopy(tag)) nodes.append(wrapper) parent = tag.getparent() if parent is not None: for t in parent.iterchildren(): if t is tag: t.addnext(wrapper) parent.remove(t) break self[:] = nodes return self
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1308-L1341
32
[ 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 ]
100
[]
0
true
74.758454
34
8
100
8
def wrap(self, value): assert isinstance(value, basestring) value = fromstring(value)[0] nodes = [] for tag in self: wrapper = deepcopy(value) # FIXME: using iterchildren is probably not optimal if not wrapper.getchildren(): wrapper.append(deepcopy(tag)) else: childs = [c for c in wrapper.iterchildren()] child = childs[-1] child.append(deepcopy(tag)) nodes.append(wrapper) parent = tag.getparent() if parent is not None: for t in parent.iterchildren(): if t is tag: t.addnext(wrapper) parent.remove(t) break self[:] = nodes return self
21,761
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.wrap_all
(self, value)
return self
Wrap all the elements in the matched set into a single wrapper element:: >>> d = PyQuery('<div><span>Hey</span><span>you !</span></div>') >>> print(d('span').wrap_all('<div id="wrapper"></div>')) <div id="wrapper"><span>Hey</span><span>you !</span></div> >>> d = PyQuery('<div><span>Hey</span><span>you !</span></div>') >>> print(d('span').wrapAll('<div id="wrapper"></div>')) <div id="wrapper"><span>Hey</span><span>you !</span></div> ..
Wrap all the elements in the matched set into a single wrapper element::
1,344
1,390
def wrap_all(self, value): """Wrap all the elements in the matched set into a single wrapper element:: >>> d = PyQuery('<div><span>Hey</span><span>you !</span></div>') >>> print(d('span').wrap_all('<div id="wrapper"></div>')) <div id="wrapper"><span>Hey</span><span>you !</span></div> >>> d = PyQuery('<div><span>Hey</span><span>you !</span></div>') >>> print(d('span').wrapAll('<div id="wrapper"></div>')) <div id="wrapper"><span>Hey</span><span>you !</span></div> .. """ if not self: return self assert isinstance(value, basestring) value = fromstring(value)[0] wrapper = deepcopy(value) if not wrapper.getchildren(): child = wrapper else: childs = [c for c in wrapper.iterchildren()] child = childs[-1] replace_childs = True parent = self[0].getparent() if parent is None: parent = no_default # add nodes to wrapper and check parent for tag in self: child.append(deepcopy(tag)) if tag.getparent() is not parent: replace_childs = False # replace nodes i parent if possible if parent is not no_default and replace_childs: childs = [c for c in parent.iterchildren()] if len(childs) == len(self): for tag in self: parent.remove(tag) parent.append(wrapper) self[:] = [wrapper] return self
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1344-L1390
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 25, 26, 27, 28, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46 ]
85.106383
[ 15, 23, 24, 29, 35 ]
10.638298
false
74.758454
47
13
89.361702
12
def wrap_all(self, value): if not self: return self assert isinstance(value, basestring) value = fromstring(value)[0] wrapper = deepcopy(value) if not wrapper.getchildren(): child = wrapper else: childs = [c for c in wrapper.iterchildren()] child = childs[-1] replace_childs = True parent = self[0].getparent() if parent is None: parent = no_default # add nodes to wrapper and check parent for tag in self: child.append(deepcopy(tag)) if tag.getparent() is not parent: replace_childs = False # replace nodes i parent if possible if parent is not no_default and replace_childs: childs = [c for c in parent.iterchildren()] if len(childs) == len(self): for tag in self: parent.remove(tag) parent.append(wrapper) self[:] = [wrapper] return self
21,762
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.replace_with
(self, value)
return self
replace nodes by value: >>> doc = PyQuery("<html><div /></html>") >>> node = PyQuery("<span />") >>> child = doc.find('div') >>> child.replace_with(node) [<div>] >>> print(doc) <html><span/></html>
replace nodes by value:
1,393
1,418
def replace_with(self, value): """replace nodes by value: >>> doc = PyQuery("<html><div /></html>") >>> node = PyQuery("<span />") >>> child = doc.find('div') >>> child.replace_with(node) [<div>] >>> print(doc) <html><span/></html> """ if isinstance(value, PyQuery): value = str(value) if hasattr(value, '__call__'): for i, element in enumerate(self): self._copy(element).before( value(i, element) + (element.tail or '')) parent = element.getparent() parent.remove(element) else: for tag in self: self._copy(tag).before(value + (tag.tail or '')) parent = tag.getparent() parent.remove(tag) return self
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1393-L1418
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 25 ]
84.615385
[ 13, 22, 23, 24 ]
15.384615
false
74.758454
26
7
84.615385
9
def replace_with(self, value): if isinstance(value, PyQuery): value = str(value) if hasattr(value, '__call__'): for i, element in enumerate(self): self._copy(element).before( value(i, element) + (element.tail or '')) parent = element.getparent() parent.remove(element) else: for tag in self: self._copy(tag).before(value + (tag.tail or '')) parent = tag.getparent() parent.remove(tag) return self
21,763
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.replace_all
(self, expr)
return self
replace nodes by expr
replace nodes by expr
1,421
1,428
def replace_all(self, expr): """replace nodes by expr """ if self._parent is no_default: raise ValueError( 'replaceAll can only be used with an object with parent') self._parent(expr).replace_with(self) return self
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1421-L1428
32
[ 0, 1, 2 ]
37.5
[ 3, 4, 6, 7 ]
50
false
74.758454
8
2
50
1
def replace_all(self, expr): if self._parent is no_default: raise ValueError( 'replaceAll can only be used with an object with parent') self._parent(expr).replace_with(self) return self
21,764
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.clone
(self)
return PyQuery([deepcopy(tag) for tag in self])
return a copy of nodes
return a copy of nodes
1,430
1,433
def clone(self): """return a copy of nodes """ return PyQuery([deepcopy(tag) for tag in self])
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1430-L1433
32
[ 0, 1, 2 ]
75
[ 3 ]
25
false
74.758454
4
2
75
1
def clone(self): return PyQuery([deepcopy(tag) for tag in self])
21,765
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.empty
(self)
return self
remove nodes content
remove nodes content
1,435
1,441
def empty(self): """remove nodes content """ for tag in self: tag.text = None tag[:] = [] return self
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1435-L1441
32
[ 0, 1, 2 ]
42.857143
[ 3, 4, 5, 6 ]
57.142857
false
74.758454
7
2
42.857143
1
def empty(self): for tag in self: tag.text = None tag[:] = [] return self
21,766
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.remove
(self, expr=no_default)
return self
Remove nodes: >>> h = ( ... '<div>Maybe <em>she</em> does <strong>NOT</strong> know</div>' ... ) >>> d = PyQuery(h) >>> d('strong').remove() [<strong>] >>> print(d) <div>Maybe <em>she</em> does know</div>
Remove nodes:
1,443
1,473
def remove(self, expr=no_default): """Remove nodes: >>> h = ( ... '<div>Maybe <em>she</em> does <strong>NOT</strong> know</div>' ... ) >>> d = PyQuery(h) >>> d('strong').remove() [<strong>] >>> print(d) <div>Maybe <em>she</em> does know</div> """ if expr is no_default: for tag in self: parent = tag.getparent() if parent is not None: if tag.tail: prev = tag.getprevious() if prev is None: if not parent.text: parent.text = '' parent.text += tag.tail else: if not prev.tail: prev.tail = '' prev.tail += tag.tail parent.remove(tag) else: results = self._copy(expr, self) results.remove() return self
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1443-L1473
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 26, 27, 30 ]
83.870968
[ 23, 24, 25, 28, 29 ]
16.129032
false
74.758454
31
8
83.870968
10
def remove(self, expr=no_default): if expr is no_default: for tag in self: parent = tag.getparent() if parent is not None: if tag.tail: prev = tag.getprevious() if prev is None: if not parent.text: parent.text = '' parent.text += tag.tail else: if not prev.tail: prev.tail = '' prev.tail += tag.tail parent.remove(tag) else: results = self._copy(expr, self) results.remove() return self
21,767
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.serialize_array
(self)
return list(map( lambda p: {'name': p[0], 'value': p[1]}, self.serialize_pairs() ))
Serialize form elements as an array of dictionaries, whose structure mirrors that produced by the jQuery API. Notably, it does not handle the deprecated `keygen` form element. >>> d = PyQuery('<form><input name="order" value="spam"></form>') >>> d.serialize_array() == [{'name': 'order', 'value': 'spam'}] True >>> d.serializeArray() == [{'name': 'order', 'value': 'spam'}] True
Serialize form elements as an array of dictionaries, whose structure mirrors that produced by the jQuery API. Notably, it does not handle the deprecated `keygen` form element.
1,501
1,515
def serialize_array(self): """Serialize form elements as an array of dictionaries, whose structure mirrors that produced by the jQuery API. Notably, it does not handle the deprecated `keygen` form element. >>> d = PyQuery('<form><input name="order" value="spam"></form>') >>> d.serialize_array() == [{'name': 'order', 'value': 'spam'}] True >>> d.serializeArray() == [{'name': 'order', 'value': 'spam'}] True """ return list(map( lambda p: {'name': p[0], 'value': p[1]}, self.serialize_pairs() ))
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1501-L1515
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
74.758454
15
1
100
9
def serialize_array(self): return list(map( lambda p: {'name': p[0], 'value': p[1]}, self.serialize_pairs() ))
21,768
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.serialize
(self)
return urlencode(self.serialize_pairs()).replace('+', '%20')
Serialize form elements as a URL-encoded string. >>> h = ( ... '<form><input name="order" value="spam">' ... '<input name="order2" value="baked beans"></form>' ... ) >>> d = PyQuery(h) >>> d.serialize() 'order=spam&order2=baked%20beans'
Serialize form elements as a URL-encoded string.
1,517
1,528
def serialize(self): """Serialize form elements as a URL-encoded string. >>> h = ( ... '<form><input name="order" value="spam">' ... '<input name="order2" value="baked beans"></form>' ... ) >>> d = PyQuery(h) >>> d.serialize() 'order=spam&order2=baked%20beans' """ return urlencode(self.serialize_pairs()).replace('+', '%20')
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1517-L1528
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
74.758454
12
1
100
9
def serialize(self): return urlencode(self.serialize_pairs()).replace('+', '%20')
21,769
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.serialize_pairs
(self)
return ret
Serialize form elements as an array of 2-tuples conventional for typical URL-parsing operations in Python. >>> d = PyQuery('<form><input name="order" value="spam"></form>') >>> d.serialize_pairs() [('order', 'spam')] >>> d.serializePairs() [('order', 'spam')]
Serialize form elements as an array of 2-tuples conventional for typical URL-parsing operations in Python.
1,535
1,599
def serialize_pairs(self): """Serialize form elements as an array of 2-tuples conventional for typical URL-parsing operations in Python. >>> d = PyQuery('<form><input name="order" value="spam"></form>') >>> d.serialize_pairs() [('order', 'spam')] >>> d.serializePairs() [('order', 'spam')] """ # https://github.com/jquery/jquery/blob # /2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/src/serialize.js#L14 _submitter_types = ['submit', 'button', 'image', 'reset', 'file'] controls = self._copy([]) # Expand list of form controls for el in self.items(): if el[0].tag == 'form': form_id = el.attr('id') if form_id: # Include inputs outside of their form owner root = self._copy(el.root.getroot()) controls.extend(root( '#%s :not([form]):input, [form="%s"]:input' % (form_id, form_id))) else: controls.extend(el(':not([form]):input')) elif el[0].tag == 'fieldset': controls.extend(el(':input')) else: controls.extend(el) # Filter controls selector = '[name]:enabled:not(button)' # Not serializing image button selector += ''.join(map( lambda s: ':not([type="%s"])' % s, _submitter_types)) controls = controls.filter(selector) def _filter_out_unchecked(_, el): el = controls._copy(el) return not el.is_(':checkbox:not(:checked)') and \ not el.is_(':radio:not(:checked)') controls = controls.filter(_filter_out_unchecked) # jQuery serializes inputs with the datalist element as an ancestor # contrary to WHATWG spec as of August 2018 # # xpath = 'self::*[not(ancestor::datalist)]' # results = [] # for tag in controls: # results.extend(tag.xpath(xpath, namespaces=controls.namespaces)) # controls = controls._copy(results) # Serialize values ret = [] for field in controls: val = self._copy(field).val() or '' if isinstance(val, list): ret.extend(map( lambda v: (field.attrib['name'], v.replace('\n', '\r\n')), val )) else: ret.append((field.attrib['name'], val.replace('\n', '\r\n'))) return ret
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1535-L1599
32
[ 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 ]
100
[]
0
true
74.758454
65
10
100
8
def serialize_pairs(self): # https://github.com/jquery/jquery/blob # /2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/src/serialize.js#L14 _submitter_types = ['submit', 'button', 'image', 'reset', 'file'] controls = self._copy([]) # Expand list of form controls for el in self.items(): if el[0].tag == 'form': form_id = el.attr('id') if form_id: # Include inputs outside of their form owner root = self._copy(el.root.getroot()) controls.extend(root( '#%s :not([form]):input, [form="%s"]:input' % (form_id, form_id))) else: controls.extend(el(':not([form]):input')) elif el[0].tag == 'fieldset': controls.extend(el(':input')) else: controls.extend(el) # Filter controls selector = '[name]:enabled:not(button)' # Not serializing image button selector += ''.join(map( lambda s: ':not([type="%s"])' % s, _submitter_types)) controls = controls.filter(selector) def _filter_out_unchecked(_, el): el = controls._copy(el) return not el.is_(':checkbox:not(:checked)') and \ not el.is_(':radio:not(:checked)') controls = controls.filter(_filter_out_unchecked) # jQuery serializes inputs with the datalist element as an ancestor # contrary to WHATWG spec as of August 2018 # # xpath = 'self::*[not(ancestor::datalist)]' # results = [] # for tag in controls: # results.extend(tag.xpath(xpath, namespaces=controls.namespaces)) # controls = controls._copy(results) # Serialize values ret = [] for field in controls: val = self._copy(field).val() or '' if isinstance(val, list): ret.extend(map( lambda v: (field.attrib['name'], v.replace('\n', '\r\n')), val )) else: ret.append((field.attrib['name'], val.replace('\n', '\r\n'))) return ret
21,770
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.serialize_dict
(self)
return ret
Serialize form elements as an ordered dictionary. Multiple values corresponding to the same input name are concatenated into one list. >>> d = PyQuery('''<form> ... <input name="order" value="spam"> ... <input name="order" value="eggs"> ... <input name="order2" value="ham"> ... </form>''') >>> d.serialize_dict() OrderedDict([('order', ['spam', 'eggs']), ('order2', 'ham')]) >>> d.serializeDict() OrderedDict([('order', ['spam', 'eggs']), ('order2', 'ham')])
Serialize form elements as an ordered dictionary. Multiple values corresponding to the same input name are concatenated into one list.
1,602
1,624
def serialize_dict(self): """Serialize form elements as an ordered dictionary. Multiple values corresponding to the same input name are concatenated into one list. >>> d = PyQuery('''<form> ... <input name="order" value="spam"> ... <input name="order" value="eggs"> ... <input name="order2" value="ham"> ... </form>''') >>> d.serialize_dict() OrderedDict([('order', ['spam', 'eggs']), ('order2', 'ham')]) >>> d.serializeDict() OrderedDict([('order', ['spam', 'eggs']), ('order2', 'ham')]) """ ret = OrderedDict() for name, val in self.serialize_pairs(): if name not in ret: ret[name] = val elif not isinstance(ret[name], list): ret[name] = [ret[name], val] else: ret[name].append(val) return ret
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1602-L1624
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22 ]
95.652174
[ 21 ]
4.347826
false
74.758454
23
4
95.652174
12
def serialize_dict(self): ret = OrderedDict() for name, val in self.serialize_pairs(): if name not in ret: ret[name] = val elif not isinstance(ret[name], list): ret[name] = [ret[name], val] else: ret[name].append(val) return ret
21,771
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.base_url
(self)
Return the url of current html document or None if not available.
Return the url of current html document or None if not available.
1,627
1,633
def base_url(self): """Return the url of current html document or None if not available. """ if self._base_url is not None: return self._base_url if self._parent is not no_default: return self._parent.base_url
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1627-L1633
32
[ 0, 1, 2 ]
42.857143
[ 3, 4, 5, 6 ]
57.142857
false
74.758454
7
3
42.857143
1
def base_url(self): if self._base_url is not None: return self._base_url if self._parent is not no_default: return self._parent.base_url
21,772
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/pyquery.py
PyQuery.make_links_absolute
(self, base_url=None)
return self
Make all links absolute.
Make all links absolute.
1,635
1,668
def make_links_absolute(self, base_url=None): """Make all links absolute. """ if base_url is None: base_url = self.base_url if base_url is None: raise ValueError(( 'You need a base URL to make your links' 'absolute. It can be provided by the base_url parameter.')) def repl(attr): def rep(i, e): attr_value = self(e).attr(attr) # when label hasn't such attr, pass if attr_value is None: return None # skip specific "protocol" schemas if any(attr_value.startswith(schema) for schema in ('tel:', 'callto:', 'sms:')): return None return self(e).attr(attr, urljoin(base_url, attr_value.strip())) return rep self('a').each(repl('href')) self('link').each(repl('href')) self('script').each(repl('src')) self('img').each(repl('src')) self('iframe').each(repl('src')) self('form').each(repl('action')) return self
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/pyquery.py#L1635-L1668
32
[ 0, 1, 2, 3, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
82.352941
[ 4, 5, 6, 20 ]
11.764706
false
74.758454
34
7
88.235294
1
def make_links_absolute(self, base_url=None): if base_url is None: base_url = self.base_url if base_url is None: raise ValueError(( 'You need a base URL to make your links' 'absolute. It can be provided by the base_url parameter.')) def repl(attr): def rep(i, e): attr_value = self(e).attr(attr) # when label hasn't such attr, pass if attr_value is None: return None # skip specific "protocol" schemas if any(attr_value.startswith(schema) for schema in ('tel:', 'callto:', 'sms:')): return None return self(e).attr(attr, urljoin(base_url, attr_value.strip())) return rep self('a').each(repl('href')) self('link').each(repl('href')) self('script').each(repl('src')) self('img').each(repl('src')) self('iframe').each(repl('src')) self('form').each(repl('action')) return self
21,773
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/exceptions.py
RequestException.__init__
(self, *args, **kwargs)
Initialize RequestException with `request` and `response` objects.
Initialize RequestException with `request` and `response` objects.
17
24
def __init__(self, *args, **kwargs): """Initialize RequestException with `request` and `response` objects.""" response = kwargs.pop("response", None) self.response = response self.request = kwargs.pop("request", None) if response is not None and not self.request and hasattr(response, "request"): self.request = self.response.request super().__init__(*args, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/exceptions.py#L17-L24
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
100
8
4
100
1
def __init__(self, *args, **kwargs): response = kwargs.pop("response", None) self.response = response self.request = kwargs.pop("request", None) if response is not None and not self.request and hasattr(response, "request"): self.request = self.response.request super().__init__(*args, **kwargs)
21,998
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/exceptions.py
JSONDecodeError.__init__
(self, *args, **kwargs)
Construct the JSONDecodeError instance first with all args. Then use it's args to construct the IOError so that the json specific args aren't used as IOError specific args and the error message from JSONDecodeError is preserved.
Construct the JSONDecodeError instance first with all args. Then use it's args to construct the IOError so that the json specific args aren't used as IOError specific args and the error message from JSONDecodeError is preserved.
34
42
def __init__(self, *args, **kwargs): """ Construct the JSONDecodeError instance first with all args. Then use it's args to construct the IOError so that the json specific args aren't used as IOError specific args and the error message from JSONDecodeError is preserved. """ CompatJSONDecodeError.__init__(self, *args) InvalidJSONError.__init__(self, *self.args, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/exceptions.py#L34-L42
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
100
9
1
100
4
def __init__(self, *args, **kwargs): CompatJSONDecodeError.__init__(self, *args) InvalidJSONError.__init__(self, *self.args, **kwargs)
21,999
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
RequestEncodingMixin.path_url
(self)
return "".join(url)
Build the path URL to use.
Build the path URL to use.
86
104
def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = "/" url.append(path) query = p.query if query: url.append("?") url.append(query) return "".join(url)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L86-L104
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
94.736842
[ 9 ]
5.263158
false
92.763158
19
3
94.736842
1
def path_url(self): url = [] p = urlsplit(self.url) path = p.path if not path: path = "/" url.append(path) query = p.query if query: url.append("?") url.append(query) return "".join(url)
22,000
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
RequestEncodingMixin._encode_params
(data)
Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict.
Encode parameters in a piece of data.
107
134
def _encode_params(data): """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data, (str, bytes)): return data elif hasattr(data, "read"): return data elif hasattr(data, "__iter__"): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): vs = [vs] for v in vs: if v is not None: result.append( ( k.encode("utf-8") if isinstance(k, str) else k, v.encode("utf-8") if isinstance(v, str) else v, ) ) return urlencode(result, doseq=True) else: return data
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L107-L134
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
92.763158
28
9
100
5
def _encode_params(data): if isinstance(data, (str, bytes)): return data elif hasattr(data, "read"): return data elif hasattr(data, "__iter__"): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): vs = [vs] for v in vs: if v is not None: result.append( ( k.encode("utf-8") if isinstance(k, str) else k, v.encode("utf-8") if isinstance(v, str) else v, ) ) return urlencode(result, doseq=True) else: return data
22,001
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
RequestEncodingMixin._encode_files
(files, data)
return body, content_type
Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
Build the body for a multipart/form-data request.
137
203
def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). """ if not files: raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, "__iter__"): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( ( field.decode("utf-8") if isinstance(field, bytes) else field, v.encode("utf-8") if isinstance(v, str) else v, ) ) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp elif hasattr(fp, "read"): fdata = fp.read() elif fp is None: continue else: fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L137-L203
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 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, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66 ]
97.014925
[ 10, 46 ]
2.985075
false
92.763158
67
19
97.014925
7
def _encode_files(files, data): if not files: raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, "__iter__"): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( ( field.decode("utf-8") if isinstance(field, bytes) else field, v.encode("utf-8") if isinstance(v, str) else v, ) ) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp elif hasattr(fp, "read"): fdata = fp.read() elif fp is None: continue else: fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type
22,002
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
RequestHooksMixin.register_hook
(self, event, hook)
Properly register a hook.
Properly register a hook.
207
216
def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError(f'Unsupported event specified, with event name "{event}"') if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, "__iter__"): self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L207-L216
33
[ 0, 1, 2, 3, 5, 6, 7, 8, 9 ]
90
[ 4 ]
10
false
92.763158
10
4
90
1
def register_hook(self, event, hook): if event not in self.hooks: raise ValueError(f'Unsupported event specified, with event name "{event}"') if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, "__iter__"): self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
22,003
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
RequestHooksMixin.deregister_hook
(self, event, hook)
Deregister a previously registered hook. Returns True if the hook existed, False if not.
Deregister a previously registered hook. Returns True if the hook existed, False if not.
218
227
def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L218-L227
33
[ 0, 1, 2, 3, 4 ]
50
[ 5, 6, 7, 8, 9 ]
50
false
92.763158
10
2
50
2
def deregister_hook(self, event, hook): try: self.hooks[event].remove(hook) return True except ValueError: return False
22,004
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Request.__init__
( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, )
258
291
def __init__( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, ): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L258-L291
33
[ 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
61.764706
[]
0
false
92.763158
34
2
100
0
def __init__( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, ): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies
22,005
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Request.__repr__
(self)
return f"<Request [{self.method}]>"
293
294
def __repr__(self): return f"<Request [{self.method}]>"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L293-L294
33
[ 0 ]
50
[ 1 ]
50
false
92.763158
2
1
50
0
def __repr__(self): return f"<Request [{self.method}]>"
22,006
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Request.prepare
(self)
return p
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
296
311
def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L296-L311
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
92.763158
16
1
100
1
def prepare(self): p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p
22,007
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.__init__
(self)
335
350
def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() #: integer denoting starting position of a readable file-like body. self._body_position = None
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L335-L350
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
92.763158
16
1
100
0
def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() #: integer denoting starting position of a readable file-like body. self._body_position = None
22,008
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare
( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, )
Prepares the entire request with the given parameters.
Prepares the entire request with the given parameters.
352
378
def prepare( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, ): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L352-L378
33
[ 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]
51.851852
[]
0
false
92.763158
27
1
100
1
def prepare( self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None, ): self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks)
22,009
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.__repr__
(self)
return f"<PreparedRequest [{self.method}]>"
380
381
def __repr__(self): return f"<PreparedRequest [{self.method}]>"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L380-L381
33
[ 0 ]
50
[ 1 ]
50
false
92.763158
2
1
50
0
def __repr__(self): return f"<PreparedRequest [{self.method}]>"
22,010
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.copy
(self)
return p
383
392
def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks p._body_position = self._body_position return p
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L383-L392
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
92.763158
10
1
100
0
def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks p._body_position = self._body_position return p
22,011
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_method
(self, method)
Prepares the given HTTP method.
Prepares the given HTTP method.
394
398
def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = to_native_string(self.method.upper())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L394-L398
33
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
92.763158
5
2
100
1
def prepare_method(self, method): self.method = method if self.method is not None: self.method = to_native_string(self.method.upper())
22,012
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest._get_idna_encoded_host
(host)
return host
401
408
def _get_idna_encoded_host(host): import idna try: host = idna.encode(host, uts46=True).decode("utf-8") except idna.IDNAError: raise UnicodeError return host
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L401-L408
33
[ 0 ]
12.5
[ 1, 3, 4, 5, 6, 7 ]
75
false
92.763158
8
2
25
0
def _get_idna_encoded_host(host): import idna try: host = idna.encode(host, uts46=True).decode("utf-8") except idna.IDNAError: raise UnicodeError return host
22,013
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_url
(self, url, params)
Prepares the given HTTP URL.
Prepares the given HTTP URL.
410
482
def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/psf/requests/pull/2238 if isinstance(url, bytes): url = url.decode("utf8") else: url = str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ":" in url and not url.lower().startswith("http"): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: raise MissingSchema( f"Invalid URL {url!r}: No scheme supplied. " f"Perhaps you meant https://{url}?" ) if not host: raise InvalidURL(f"Invalid URL {url!r}: No host supplied") # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL("URL has an invalid label.") elif host.startswith(("*", ".")): raise InvalidURL("URL has an invalid label.") # Carefully reconstruct the network location netloc = auth or "" if netloc: netloc += "@" netloc += host if port: netloc += f":{port}" # Bare domains aren't valid URLs. if not path: path = "/" if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = f"{query}&{enc_params}" else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L410-L482
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, 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 ]
94.520548
[ 42, 43, 44, 45 ]
5.479452
false
92.763158
73
17
94.520548
1
def prepare_url(self, url, params): #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/psf/requests/pull/2238 if isinstance(url, bytes): url = url.decode("utf8") else: url = str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ":" in url and not url.lower().startswith("http"): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: raise MissingSchema( f"Invalid URL {url!r}: No scheme supplied. " f"Perhaps you meant https://{url}?" ) if not host: raise InvalidURL(f"Invalid URL {url!r}: No host supplied") # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL("URL has an invalid label.") elif host.startswith(("*", ".")): raise InvalidURL("URL has an invalid label.") # Carefully reconstruct the network location netloc = auth or "" if netloc: netloc += "@" netloc += host if port: netloc += f":{port}" # Bare domains aren't valid URLs. if not path: path = "/" if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = f"{query}&{enc_params}" else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url
22,014
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_headers
(self, headers)
Prepares the given HTTP headers.
Prepares the given HTTP headers.
484
493
def prepare_headers(self, headers): """Prepares the given HTTP headers.""" self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): # Raise exception on invalid header value. check_header_validity(header) name, value = header self.headers[to_native_string(name)] = value
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L484-L493
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
92.763158
10
3
100
1
def prepare_headers(self, headers): self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): # Raise exception on invalid header value. check_header_validity(header) name, value = header self.headers[to_native_string(name)] = value
22,015
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_body
(self, data, files, json=None)
Prepares the given HTTP body data.
Prepares the given HTTP body data.
495
571
def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = "application/json" try: body = complexjson.dumps(json, allow_nan=False) except ValueError as ve: raise InvalidJSONError(ve, request=self) if not isinstance(body, bytes): body = body.encode("utf-8") is_stream = all( [ hasattr(data, "__iter__"), not isinstance(data, (basestring, list, tuple, Mapping)), ] ) if is_stream: try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None body = data if getattr(body, "tell", None) is not None: # Record the current file position before reading. # This will allow us to rewind a file in the event # of a redirect. try: self._body_position = body.tell() except OSError: # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body self._body_position = object() if files: raise NotImplementedError( "Streamed bodies and files are mutually exclusive." ) if length: self.headers["Content-Length"] = builtin_str(length) else: self.headers["Transfer-Encoding"] = "chunked" else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, "read"): content_type = None else: content_type = "application/x-www-form-urlencoded" self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ("content-type" not in self.headers): self.headers["Content-Type"] = content_type self.body = body
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L495-L571
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, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76 ]
93.506494
[ 33, 34, 50 ]
3.896104
false
92.763158
77
17
96.103896
1
def prepare_body(self, data, files, json=None): # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = "application/json" try: body = complexjson.dumps(json, allow_nan=False) except ValueError as ve: raise InvalidJSONError(ve, request=self) if not isinstance(body, bytes): body = body.encode("utf-8") is_stream = all( [ hasattr(data, "__iter__"), not isinstance(data, (basestring, list, tuple, Mapping)), ] ) if is_stream: try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None body = data if getattr(body, "tell", None) is not None: # Record the current file position before reading. # This will allow us to rewind a file in the event # of a redirect. try: self._body_position = body.tell() except OSError: # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body self._body_position = object() if files: raise NotImplementedError( "Streamed bodies and files are mutually exclusive." ) if length: self.headers["Content-Length"] = builtin_str(length) else: self.headers["Transfer-Encoding"] = "chunked" else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, "read"): content_type = None else: content_type = "application/x-www-form-urlencoded" self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ("content-type" not in self.headers): self.headers["Content-Type"] = content_type self.body = body
22,016
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_content_length
(self, body)
Prepare Content-Length header based on request method and body
Prepare Content-Length header based on request method and body
573
587
def prepare_content_length(self, body): """Prepare Content-Length header based on request method and body""" if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked. self.headers["Content-Length"] = builtin_str(length) elif ( self.method not in ("GET", "HEAD") and self.headers.get("Content-Length") is None ): # Set Content-Length to 0 for methods that can have a body # but don't provide one. (i.e. not GET or HEAD) self.headers["Content-Length"] = "0"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L573-L587
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
92.763158
15
5
100
1
def prepare_content_length(self, body): if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked. self.headers["Content-Length"] = builtin_str(length) elif ( self.method not in ("GET", "HEAD") and self.headers.get("Content-Length") is None ): # Set Content-Length to 0 for methods that can have a body # but don't provide one. (i.e. not GET or HEAD) self.headers["Content-Length"] = "0"
22,017
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_auth
(self, auth, url="")
Prepares the given HTTP auth data.
Prepares the given HTTP auth data.
589
609
def prepare_auth(self, auth, url=""): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L589-L609
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
92.763158
21
5
100
1
def prepare_auth(self, auth, url=""): # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body)
22,018
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_cookies
(self, cookies)
Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand.
Prepares the given HTTP cookie data.
611
629
def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand. """ if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers["Cookie"] = cookie_header
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L611-L629
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
92.763158
19
3
100
9
def prepare_cookies(self, cookies): if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers["Cookie"] = cookie_header
22,019
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
PreparedRequest.prepare_hooks
(self, hooks)
Prepares the given hooks.
Prepares the given hooks.
631
638
def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: self.register_hook(event, hooks[event])
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L631-L638
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
92.763158
8
3
100
1
def prepare_hooks(self, hooks): # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: self.register_hook(event, hooks[event])
22,020
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__init__
(self)
659
704
def __init__(self): self._content = False self._content_consumed = False self._next = None #: Integer Code of responded HTTP Status, e.g. 404 or 200. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. #: This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta). #: This property specifically measures the time taken between sending #: the first byte of the request and finishing parsing the headers. It #: is therefore unaffected by consuming the response content or the #: value of the ``stream`` keyword argument. self.elapsed = datetime.timedelta(0) #: The :class:`PreparedRequest <PreparedRequest>` object to which this #: is a response. self.request = None
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L659-L704
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
92.763158
46
1
100
0
def __init__(self): self._content = False self._content_consumed = False self._next = None #: Integer Code of responded HTTP Status, e.g. 404 or 200. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. #: This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta). #: This property specifically measures the time taken between sending #: the first byte of the request and finishing parsing the headers. It #: is therefore unaffected by consuming the response content or the #: value of the ``stream`` keyword argument. self.elapsed = datetime.timedelta(0) #: The :class:`PreparedRequest <PreparedRequest>` object to which this #: is a response. self.request = None
22,021
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__enter__
(self)
return self
706
707
def __enter__(self): return self
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L706-L707
33
[ 0, 1 ]
100
[]
0
true
92.763158
2
1
100
0
def __enter__(self): return self
22,022
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__exit__
(self, *args)
709
710
def __exit__(self, *args): self.close()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L709-L710
33
[ 0, 1 ]
100
[]
0
true
92.763158
2
1
100
0
def __exit__(self, *args): self.close()
22,023
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__getstate__
(self)
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
712
718
def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return {attr: getattr(self, attr, None) for attr in self.__attrs__}
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L712-L718
33
[ 0, 1, 2, 3, 5, 6 ]
85.714286
[ 4 ]
14.285714
false
92.763158
7
2
85.714286
0
def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return {attr: getattr(self, attr, None) for attr in self.__attrs__}
22,024
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__setstate__
(self, state)
720
726
def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, "_content_consumed", True) setattr(self, "raw", None)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L720-L726
33
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
92.763158
7
2
100
0
def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, "_content_consumed", True) setattr(self, "raw", None)
22,025
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__repr__
(self)
return f"<Response [{self.status_code}]>"
728
729
def __repr__(self): return f"<Response [{self.status_code}]>"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L728-L729
33
[ 0, 1 ]
100
[]
0
true
92.763158
2
1
100
0
def __repr__(self): return f"<Response [{self.status_code}]>"
22,026
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__bool__
(self)
return self.ok
Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``.
Returns True if :attr:`status_code` is less than 400.
731
739
def __bool__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L731-L739
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
88.888889
[ 8 ]
11.111111
false
92.763158
9
1
88.888889
6
def __bool__(self): return self.ok
22,027
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__nonzero__
(self)
return self.ok
Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``.
Returns True if :attr:`status_code` is less than 400.
741
749
def __nonzero__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L741-L749
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
88.888889
[ 8 ]
11.111111
false
92.763158
9
1
88.888889
6
def __nonzero__(self): return self.ok
22,028
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.__iter__
(self)
return self.iter_content(128)
Allows you to use a response as an iterator.
Allows you to use a response as an iterator.
751
753
def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L751-L753
33
[ 0, 1, 2 ]
100
[]
0
true
92.763158
3
1
100
1
def __iter__(self): return self.iter_content(128)
22,029
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.ok
(self)
return True
Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``.
Returns True if :attr:`status_code` is less than 400, False if not.
756
768
def ok(self): """Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ try: self.raise_for_status() except HTTPError: return False return True
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L756-L768
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
92.763158
13
2
100
6
def ok(self): try: self.raise_for_status() except HTTPError: return False return True
22,030
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.is_redirect
(self)
return "location" in self.headers and self.status_code in REDIRECT_STATI
True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`).
True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`).
771
775
def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """ return "location" in self.headers and self.status_code in REDIRECT_STATI
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L771-L775
33
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
92.763158
5
2
100
2
def is_redirect(self): return "location" in self.headers and self.status_code in REDIRECT_STATI
22,031
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.is_permanent_redirect
(self)
return "location" in self.headers and self.status_code in ( codes.moved_permanently, codes.permanent_redirect, )
True if this Response one of the permanent versions of redirect.
True if this Response one of the permanent versions of redirect.
778
783
def is_permanent_redirect(self): """True if this Response one of the permanent versions of redirect.""" return "location" in self.headers and self.status_code in ( codes.moved_permanently, codes.permanent_redirect, )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L778-L783
33
[ 0, 1 ]
33.333333
[ 2 ]
16.666667
false
92.763158
6
2
83.333333
1
def is_permanent_redirect(self): return "location" in self.headers and self.status_code in ( codes.moved_permanently, codes.permanent_redirect, )
22,032
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.next
(self)
return self._next
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
786
788
def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L786-L788
33
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
92.763158
3
1
66.666667
1
def next(self): return self._next
22,033
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.apparent_encoding
(self)
return chardet.detect(self.content)["encoding"]
The apparent encoding, provided by the charset_normalizer or chardet libraries.
The apparent encoding, provided by the charset_normalizer or chardet libraries.
791
793
def apparent_encoding(self): """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" return chardet.detect(self.content)["encoding"]
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L791-L793
33
[ 0, 1, 2 ]
100
[]
0
true
92.763158
3
1
100
1
def apparent_encoding(self): return chardet.detect(self.content)["encoding"]
22,034
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.iter_content
(self, chunk_size=1, decode_unicode=False)
return chunks
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response.
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
795
851
def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): # Special case for urllib3. if hasattr(self.raw, "stream"): try: yield from self.raw.stream(chunk_size, decode_content=True) except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) except SSLError as e: raise RequestsSSLError(e) else: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance(chunk_size, int): raise TypeError( f"chunk_size must be an int, it is instead a {type(chunk_size)}." ) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L795-L851
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, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56 ]
98.245614
[ 41 ]
1.754386
false
92.763158
57
14
98.245614
14
def iter_content(self, chunk_size=1, decode_unicode=False): def generate(): # Special case for urllib3. if hasattr(self.raw, "stream"): try: yield from self.raw.stream(chunk_size, decode_content=True) except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) except SSLError as e: raise RequestsSSLError(e) else: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance(chunk_size, int): raise TypeError( f"chunk_size must be an int, it is instead a {type(chunk_size)}." ) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks
22,035
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.iter_lines
( self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None )
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe.
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.
853
885
def iter_lines( self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None ): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. """ pending = None for chunk in self.iter_content( chunk_size=chunk_size, decode_unicode=decode_unicode ): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None yield from lines if pending is not None: yield pending
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L853-L885
33
[ 0, 9, 10, 11, 12, 15, 16, 17, 18, 19, 22, 23, 24, 25, 27, 28, 29, 30, 31 ]
57.575758
[ 20, 32 ]
6.060606
false
92.763158
33
9
93.939394
5
def iter_lines( self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None ): pending = None for chunk in self.iter_content( chunk_size=chunk_size, decode_unicode=decode_unicode ): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None yield from lines if pending is not None: yield pending
22,036
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.content
(self)
return self._content
Content of the response, in bytes.
Content of the response, in bytes.
888
904
def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. if self._content_consumed: raise RuntimeError("The content for this response was already consumed") if self.status_code == 0 or self.raw is None: self._content = None else: self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L888-L904
33
[ 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
94.117647
[ 6 ]
5.882353
false
92.763158
17
6
94.117647
1
def content(self): if self._content is False: # Read the contents. if self._content_consumed: raise RuntimeError("The content for this response was already consumed") if self.status_code == 0 or self.raw is None: self._content = None else: self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content
22,037
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.text
(self)
return content
Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``charset_normalizer`` or ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property.
Content of the response, in unicode.
907
942
def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``charset_normalizer`` or ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return "" # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors="replace") except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors="replace") return content
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L907-L942
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 ]
100
[]
0
true
92.763158
36
4
100
9
def text(self): # Try charset from content-type content = None encoding = self.encoding if not self.content: return "" # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors="replace") except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors="replace") return content
22,038
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.json
(self, **kwargs)
r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises requests.exceptions.JSONDecodeError: If the response body does not contain valid json.
r"""Returns the json-encoded content of a response, if any.
944
975
def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises requests.exceptions.JSONDecodeError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using charset_normalizer to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass except JSONDecodeError as e: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) try: return complexjson.loads(self.text, **kwargs) except JSONDecodeError as e: # Catch JSON-related errors and raise as requests.JSONDecodeError # This aliases json.JSONDecodeError and simplejson.JSONDecodeError raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L944-L975
33
[ 0, 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 ]
81.25
[]
0
false
92.763158
32
8
100
5
def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises requests.exceptions.JSONDecodeError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using charset_normalizer to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass except JSONDecodeError as e: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) try: return complexjson.loads(self.text, **kwargs) except JSONDecodeError as e: # Catch JSON-related errors and raise as requests.JSONDecodeError # This aliases json.JSONDecodeError and simplejson.JSONDecodeError raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
22,039
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.links
(self)
return resolved_links
Returns the parsed header links of the response, if any.
Returns the parsed header links of the response, if any.
978
992
def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get("link") resolved_links = {} if header: links = parse_header_links(header) for link in links: key = link.get("rel") or link.get("url") resolved_links[key] = link return resolved_links
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L978-L992
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
92.763158
15
4
100
1
def links(self): header = self.headers.get("link") resolved_links = {} if header: links = parse_header_links(header) for link in links: key = link.get("rel") or link.get("url") resolved_links[key] = link return resolved_links
22,040
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.raise_for_status
(self)
Raises :class:`HTTPError`, if one occurred.
Raises :class:`HTTPError`, if one occurred.
994
1,021
def raise_for_status(self): """Raises :class:`HTTPError`, if one occurred.""" http_error_msg = "" if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. (See PR #3538) try: reason = self.reason.decode("utf-8") except UnicodeDecodeError: reason = self.reason.decode("iso-8859-1") else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = ( f"{self.status_code} Client Error: {reason} for url: {self.url}" ) elif 500 <= self.status_code < 600: http_error_msg = ( f"{self.status_code} Server Error: {reason} for url: {self.url}" ) if http_error_msg: raise HTTPError(http_error_msg, response=self)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L994-L1021
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
92.763158
28
6
100
1
def raise_for_status(self): http_error_msg = "" if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. (See PR #3538) try: reason = self.reason.decode("utf-8") except UnicodeDecodeError: reason = self.reason.decode("iso-8859-1") else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = ( f"{self.status_code} Client Error: {reason} for url: {self.url}" ) elif 500 <= self.status_code < 600: http_error_msg = ( f"{self.status_code} Server Error: {reason} for url: {self.url}" ) if http_error_msg: raise HTTPError(http_error_msg, response=self)
22,041
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/models.py
Response.close
(self)
Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.*
Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again.
1,023
1,034
def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, "release_conn", None) if release_conn is not None: release_conn()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/models.py#L1023-L1034
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
92.763158
12
3
100
4
def close(self): if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, "release_conn", None) if release_conn is not None: release_conn()
22,042
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
dict_to_sequence
(d)
return d
Returns an internal sequence dictionary update.
Returns an internal sequence dictionary update.
119
125
def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" if hasattr(d, "items"): d = d.items() return d
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L119-L125
33
[ 0, 1, 2 ]
42.857143
[ 3, 4, 6 ]
42.857143
false
81.742739
7
2
57.142857
1
def dict_to_sequence(d): if hasattr(d, "items"): d = d.items() return d
22,043
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
super_len
(o)
return max(0, total_length - current_position)
128
191
def super_len(o): total_length = None current_position = 0 if hasattr(o, "__len__"): total_length = len(o) elif hasattr(o, "len"): total_length = o.len elif hasattr(o, "fileno"): try: fileno = o.fileno() except (io.UnsupportedOperation, AttributeError): # AttributeError is a surprising exception, seeing as how we've just checked # that `hasattr(o, 'fileno')`. It happens for objects obtained via # `Tarfile.extractfile()`, per issue 5229. pass else: total_length = os.fstat(fileno).st_size # Having used fstat to determine the file length, we need to # confirm that this file was opened up in binary mode. if "b" not in o.mode: warnings.warn( ( "Requests has determined the content-length for this " "request using the binary size of the file: however, the " "file has been opened in text mode (i.e. without the 'b' " "flag in the mode). This may lead to an incorrect " "content-length. In Requests 3.0, support will be removed " "for files in text mode." ), FileModeWarning, ) if hasattr(o, "tell"): try: current_position = o.tell() except OSError: # This can happen in some weird situations, such as when the file # is actually a special file descriptor like stdin. In this # instance, we don't know what the length is, so set it to zero and # let requests chunk it instead. if total_length is not None: current_position = total_length else: if hasattr(o, "seek") and total_length is None: # StringIO and BytesIO have seek but no usable fileno try: # seek to end of file o.seek(0, 2) total_length = o.tell() # seek back to current position to support # partially read file-like objects o.seek(current_position or 0) except OSError: total_length = 0 if total_length is None: total_length = 0 return max(0, total_length - current_position)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L128-L191
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 ]
81.25
[]
0
false
81.742739
64
14
100
0
def super_len(o): total_length = None current_position = 0 if hasattr(o, "__len__"): total_length = len(o) elif hasattr(o, "len"): total_length = o.len elif hasattr(o, "fileno"): try: fileno = o.fileno() except (io.UnsupportedOperation, AttributeError): # AttributeError is a surprising exception, seeing as how we've just checked # that `hasattr(o, 'fileno')`. It happens for objects obtained via # `Tarfile.extractfile()`, per issue 5229. pass else: total_length = os.fstat(fileno).st_size # Having used fstat to determine the file length, we need to # confirm that this file was opened up in binary mode. if "b" not in o.mode: warnings.warn( ( "Requests has determined the content-length for this " "request using the binary size of the file: however, the " "file has been opened in text mode (i.e. without the 'b' " "flag in the mode). This may lead to an incorrect " "content-length. In Requests 3.0, support will be removed " "for files in text mode." ), FileModeWarning, ) if hasattr(o, "tell"): try: current_position = o.tell() except OSError: # This can happen in some weird situations, such as when the file # is actually a special file descriptor like stdin. In this # instance, we don't know what the length is, so set it to zero and # let requests chunk it instead. if total_length is not None: current_position = total_length else: if hasattr(o, "seek") and total_length is None: # StringIO and BytesIO have seek but no usable fileno try: # seek to end of file o.seek(0, 2) total_length = o.tell() # seek back to current position to support # partially read file-like objects o.seek(current_position or 0) except OSError: total_length = 0 if total_length is None: total_length = 0 return max(0, total_length - current_position)
22,044
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
get_netrc_auth
(url, raise_errors=False)
Returns the Requests tuple auth for a given url from netrc.
Returns the Requests tuple auth for a given url from netrc.
194
248
def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" netrc_file = os.environ.get("NETRC") if netrc_file is not None: netrc_locations = (netrc_file,) else: netrc_locations = (f"~/{f}" for f in NETRC_FILES) try: from netrc import NetrcParseError, netrc netrc_path = None for f in netrc_locations: try: loc = os.path.expanduser(f) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & # https://github.com/psf/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b":" if isinstance(url, str): splitstr = splitstr.decode("ascii") host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = 0 if _netrc[0] else 1 return (_netrc[login_i], _netrc[2]) except (NetrcParseError, OSError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # App Engine hackiness. except (ImportError, AttributeError): pass
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L194-L248
33
[ 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 23, 27, 28, 29, 30 ]
40
[ 5, 17, 21, 24, 25, 31, 35, 36, 37, 38, 40, 41, 42, 44, 45, 46, 49, 50, 53, 54 ]
36.363636
false
81.742739
55
11
63.636364
1
def get_netrc_auth(url, raise_errors=False): netrc_file = os.environ.get("NETRC") if netrc_file is not None: netrc_locations = (netrc_file,) else: netrc_locations = (f"~/{f}" for f in NETRC_FILES) try: from netrc import NetrcParseError, netrc netrc_path = None for f in netrc_locations: try: loc = os.path.expanduser(f) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & # https://github.com/psf/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b":" if isinstance(url, str): splitstr = splitstr.decode("ascii") host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = 0 if _netrc[0] else 1 return (_netrc[login_i], _netrc[2]) except (NetrcParseError, OSError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # App Engine hackiness. except (ImportError, AttributeError): pass
22,045
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
guess_filename
(obj)
Tries to guess the filename of the given object.
Tries to guess the filename of the given object.
251
255
def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, "name", None) if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": return os.path.basename(name)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L251-L255
33
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
81.742739
5
5
100
1
def guess_filename(obj): name = getattr(obj, "name", None) if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": return os.path.basename(name)
22,046
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
extract_zipped_paths
(path)
return extracted_path
Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.
Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.
258
292
def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) if not prefix: # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users break member = "/".join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, member.split("/")[-1]) if not os.path.exists(extracted_path): # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition with atomic_open(extracted_path) as file_handler: file_handler.write(zip_file.read(member)) return extracted_path
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L258-L292
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, 27, 28, 29, 30, 31, 32, 33, 34 ]
91.428571
[ 17, 25 ]
5.714286
false
81.742739
35
9
94.285714
3
def extract_zipped_paths(path): if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) if not prefix: # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users break member = "/".join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, member.split("/")[-1]) if not os.path.exists(extracted_path): # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition with atomic_open(extracted_path) as file_handler: file_handler.write(zip_file.read(member)) return extracted_path
22,047
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
atomic_open
(filename)
Write a file to the disk in an atomic fashion
Write a file to the disk in an atomic fashion
296
305
def atomic_open(filename): """Write a file to the disk in an atomic fashion""" tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) try: with os.fdopen(tmp_descriptor, "wb") as tmp_handler: yield tmp_handler os.replace(tmp_name, filename) except BaseException: os.remove(tmp_name) raise
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L296-L305
33
[ 0, 1, 2, 3, 4, 5, 6 ]
70
[ 7, 8, 9 ]
30
false
81.742739
10
3
70
1
def atomic_open(filename): tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) try: with os.fdopen(tmp_descriptor, "wb") as tmp_handler: yield tmp_handler os.replace(tmp_name, filename) except BaseException: os.remove(tmp_name) raise
22,048
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
from_key_val_list
(value)
return OrderedDict(value)
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g.,
308
332
def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError("cannot encode objects that are not 2-tuples") return OrderedDict(value)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L308-L332
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
72
[ 18, 19, 21, 22, 24 ]
20
false
81.742739
25
3
80
16
def from_key_val_list(value): if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError("cannot encode objects that are not 2-tuples") return OrderedDict(value)
22,049
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
to_key_val_list
(value)
return list(value)
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g.,
335
361
def to_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError("cannot encode objects that are not 2-tuples") if isinstance(value, Mapping): value = value.items() return list(value)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L335-L361
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
81.742739
27
4
100
15
def to_key_val_list(value): if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError("cannot encode objects that are not 2-tuples") if isinstance(value, Mapping): value = value.items() return list(value)
22,050
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
parse_list_header
(value)
return result
Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list
Parse lists as described by RFC 2068 Section 2.
365
393
def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L365-L393
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
79.310345
[ 23, 24, 25, 26, 27, 28 ]
20.689655
false
81.742739
29
3
79.310345
21
def parse_list_header(value): result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result
22,051
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
parse_dict_header
(value)
return result
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict:
397
428
def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict """ result = {} for item in _parse_list_header(value): if "=" not in item: result[item] = None continue name, value = item.split("=", 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L397-L428
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 ]
100
[]
0
true
81.742739
32
4
100
20
def parse_dict_header(value): result = {} for item in _parse_list_header(value): if "=" not in item: result[item] = None continue name, value = item.split("=", 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result
22,052
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
unquote_header_value
(value, is_filename=False)
return value
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting.
432
454
def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != "\\\\": return value.replace("\\\\", "\\").replace('\\"', '"') return value
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L432-L454
33
[ 0, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
73.913043
[]
0
false
81.742739
23
5
100
6
def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != "\\\\": return value.replace("\\\\", "\\").replace('\\"', '"') return value
22,053
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
dict_from_cookiejar
(cj)
return cookie_dict
Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict
Returns a key/value dictionary from a CookieJar.
457
469
def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L457-L469
33
[ 0, 1, 2, 3, 4, 5, 6 ]
53.846154
[ 7, 9, 10, 12 ]
30.769231
false
81.742739
13
2
69.230769
4
def dict_from_cookiejar(cj): cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
22,054
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
add_dict_to_cookiejar
(cj, cookie_dict)
return cookiejar_from_dict(cookie_dict, cj)
Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar
Returns a CookieJar from a key/value dictionary.
472
480
def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar """ return cookiejar_from_dict(cookie_dict, cj)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L472-L480
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
81.742739
9
1
100
5
def add_dict_to_cookiejar(cj, cookie_dict): return cookiejar_from_dict(cookie_dict, cj)
22,055
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
get_encodings_from_content
(content)
return ( charset_re.findall(content) + pragma_re.findall(content) + xml_re.findall(content) )
Returns encodings from given content string. :param content: bytestring to extract encodings from.
Returns encodings from given content string.
483
505
def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ warnings.warn( ( "In requests 3.0, get_encodings_from_content will be removed. For " "more information, please see the discussion on issue #2266. (This" " warning should only appear once.)" ), DeprecationWarning, ) charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I) xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') return ( charset_re.findall(content) + pragma_re.findall(content) + xml_re.findall(content) )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L483-L505
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
81.742739
23
1
100
3
def get_encodings_from_content(content): warnings.warn( ( "In requests 3.0, get_encodings_from_content will be removed. For " "more information, please see the discussion on issue #2266. (This" " warning should only appear once.)" ), DeprecationWarning, ) charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I) xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') return ( charset_re.findall(content) + pragma_re.findall(content) + xml_re.findall(content) )
22,056
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
_parse_content_type_header
(header)
return content_type, params_dict
Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters
Returns content type and parameters from given header
508
530
def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(";") content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1 :].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L508-L530
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
81.742739
23
4
100
5
def _parse_content_type_header(header): tokens = header.split(";") content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1 :].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict
22,057
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
get_encoding_from_headers
(headers)
Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str
Returns encodings from given HTTP Header Dict.
533
555
def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = headers.get("content-type") if not content_type: return None content_type, params = _parse_content_type_header(content_type) if "charset" in params: return params["charset"].strip("'\"") if "text" in content_type: return "ISO-8859-1" if "application/json" in content_type: # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset return "utf-8"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L533-L555
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
81.742739
23
5
100
4
def get_encoding_from_headers(headers): content_type = headers.get("content-type") if not content_type: return None content_type, params = _parse_content_type_header(content_type) if "charset" in params: return params["charset"].strip("'\"") if "text" in content_type: return "ISO-8859-1" if "application/json" in content_type: # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset return "utf-8"
22,058
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
stream_decode_response_unicode
(iterator, r)
Stream decodes an iterator.
Stream decodes an iterator.
558
572
def stream_decode_response_unicode(iterator, r): """Stream decodes an iterator.""" if r.encoding is None: yield from iterator return decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode(b"", final=True) if rv: yield rv
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L558-L572
33
[ 0, 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13 ]
80
[ 4, 5, 14 ]
20
false
81.742739
15
5
80
1
def stream_decode_response_unicode(iterator, r): if r.encoding is None: yield from iterator return decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode(b"", final=True) if rv: yield rv
22,059
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
iter_slices
(string, slice_length)
Iterate over slices of a string.
Iterate over slices of a string.
575
582
def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos : pos + slice_length] pos += slice_length
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L575-L582
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
81.742739
8
4
100
1
def iter_slices(string, slice_length): pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos : pos + slice_length] pos += slice_length
22,060
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
get_unicode_from_response
(r)
Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str
Returns the requested content back in unicode.
585
621
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn( ( "In requests 3.0, get_unicode_from_response will be removed. For " "more information, please see the discussion on issue #2266. (This" " warning should only appear once.)" ), DeprecationWarning, ) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors="replace") except TypeError: return r.content
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L585-L621
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
32.432432
[ 12, 21, 24, 26, 27, 28, 29, 30, 33, 34, 35, 36 ]
32.432432
false
81.742739
37
4
67.567568
10
def get_unicode_from_response(r): warnings.warn( ( "In requests 3.0, get_unicode_from_response will be removed. For " "more information, please see the discussion on issue #2266. (This" " warning should only appear once.)" ), DeprecationWarning, ) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors="replace") except TypeError: return r.content
22,061
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
unquote_unreserved
(uri)
return "".join(parts)
Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str
Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
630
651
def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str """ parts = uri.split("%") for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 and h.isalnum(): try: c = chr(int(h, 16)) except ValueError: raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = f"%{parts[i]}" else: parts[i] = f"%{parts[i]}" return "".join(parts)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L630-L651
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
81.742739
22
6
100
4
def unquote_unreserved(uri): parts = uri.split("%") for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 and h.isalnum(): try: c = chr(int(h, 16)) except ValueError: raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = f"%{parts[i]}" else: parts[i] = f"%{parts[i]}" return "".join(parts)
22,062
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
requote_uri
(uri)
Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str
Re-quote the given URI.
654
673
def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L654-L673
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
81.742739
20
2
100
6
def requote_uri(uri): safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent)
22,063
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
address_in_network
(ip, net)
return (ipaddr & netmask) == (network & netmask)
This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool
This function allows you to check if an IP belongs to a network subnet
676
688
def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] netaddr, bits = net.split("/") netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L676-L688
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
81.742739
13
1
100
6
def address_in_network(ip, net): ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] netaddr, bits = net.split("/") netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask)
22,064
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
dotted_netmask
(mask)
return socket.inet_ntoa(struct.pack(">I", bits))
Converts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str
Converts mask from /xx format to xxx.xxx.xxx.xxx
691
699
def dotted_netmask(mask): """Converts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str """ bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 return socket.inet_ntoa(struct.pack(">I", bits))
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L691-L699
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
81.742739
9
1
100
5
def dotted_netmask(mask): bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 return socket.inet_ntoa(struct.pack(">I", bits))
22,065
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
is_ipv4_address
(string_ip)
return True
:rtype: bool
:rtype: bool
702
710
def is_ipv4_address(string_ip): """ :rtype: bool """ try: socket.inet_aton(string_ip) except OSError: return False return True
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L702-L710
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
81.742739
9
2
100
1
def is_ipv4_address(string_ip): try: socket.inet_aton(string_ip) except OSError: return False return True
22,066
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
is_valid_cidr
(string_network)
return True
Very simple check of the cidr format in no_proxy variable. :rtype: bool
Very simple check of the cidr format in no_proxy variable.
713
734
def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count("/") == 1: try: mask = int(string_network.split("/")[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split("/")[0]) except OSError: return False else: return False return True
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L713-L734
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
81.742739
22
6
100
3
def is_valid_cidr(string_network): if string_network.count("/") == 1: try: mask = int(string_network.split("/")[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split("/")[0]) except OSError: return False else: return False return True
22,067
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
set_environ
(env_name, value)
Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing
Set the environment variable 'env_name' to 'value'
738
756
def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L738-L756
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18 ]
89.473684
[]
0
false
81.742739
19
4
100
6
def set_environ(env_name, value): value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value
22,068
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
should_bypass_proxies
(url, no_proxy)
return False
Returns whether we should bypass proxies or not. :rtype: bool
Returns whether we should bypass proxies or not.
759
816
def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). def get_proxy(key): return os.environ.get(key) or os.environ.get(key.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy("no_proxy") parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += f":{parsed.port}" for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ("no_proxy", no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L759-L816
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, 53, 54, 55, 56, 57 ]
96.551724
[ 51, 52 ]
3.448276
false
81.742739
58
18
96.551724
3
def should_bypass_proxies(url, no_proxy): # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). def get_proxy(key): return os.environ.get(key) or os.environ.get(key.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy("no_proxy") parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += f":{parsed.port}" for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ("no_proxy", no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
22,069
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
get_environ_proxies
(url, no_proxy=None)
Return a dict of environment proxies. :rtype: dict
Return a dict of environment proxies.
819
828
def get_environ_proxies(url, no_proxy=None): """ Return a dict of environment proxies. :rtype: dict """ if should_bypass_proxies(url, no_proxy=no_proxy): return {} else: return getproxies()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L819-L828
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
81.742739
10
2
100
3
def get_environ_proxies(url, no_proxy=None): if should_bypass_proxies(url, no_proxy=no_proxy): return {} else: return getproxies()
22,070
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
select_proxy
(url, proxies)
return proxy
Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
Select a proxy for the url, if applicable.
831
854
def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get("all")) proxy_keys = [ urlparts.scheme + "://" + urlparts.hostname, urlparts.scheme, "all://" + urlparts.hostname, "all", ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L831-L854
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 ]
100
[]
0
true
81.742739
24
5
100
4
def select_proxy(url, proxies): proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get("all")) proxy_keys = [ urlparts.scheme + "://" + urlparts.hostname, urlparts.scheme, "all://" + urlparts.hostname, "all", ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy
22,071
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
resolve_proxies
(request, proxies, trust_env=True)
return new_proxies
This method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such a NO_PROXY to strip proxy configurations. :param request: Request or PreparedRequest :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs :param trust_env: Boolean declaring whether to trust environment configs :rtype: dict
This method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such a NO_PROXY to strip proxy configurations.
857
881
def resolve_proxies(request, proxies, trust_env=True): """This method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such a NO_PROXY to strip proxy configurations. :param request: Request or PreparedRequest :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs :param trust_env: Boolean declaring whether to trust environment configs :rtype: dict """ proxies = proxies if proxies is not None else {} url = request.url scheme = urlparse(url).scheme no_proxy = proxies.get("no_proxy") new_proxies = proxies.copy() if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get("all")) if proxy: new_proxies.setdefault(scheme, proxy) return new_proxies
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L857-L881
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 ]
100
[]
0
true
81.742739
25
4
100
9
def resolve_proxies(request, proxies, trust_env=True): proxies = proxies if proxies is not None else {} url = request.url scheme = urlparse(url).scheme no_proxy = proxies.get("no_proxy") new_proxies = proxies.copy() if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get("all")) if proxy: new_proxies.setdefault(scheme, proxy) return new_proxies
22,072
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
default_user_agent
(name="python-requests")
return f"{name}/{__version__}"
Return a string representing the default user agent. :rtype: str
Return a string representing the default user agent.
884
890
def default_user_agent(name="python-requests"): """ Return a string representing the default user agent. :rtype: str """ return f"{name}/{__version__}"
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L884-L890
33
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
81.742739
7
1
100
3
def default_user_agent(name="python-requests"): return f"{name}/{__version__}"
22,073
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
default_headers
()
return CaseInsensitiveDict( { "User-Agent": default_user_agent(), "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, "Accept": "*/*", "Connection": "keep-alive", } )
:rtype: requests.structures.CaseInsensitiveDict
:rtype: requests.structures.CaseInsensitiveDict
893
904
def default_headers(): """ :rtype: requests.structures.CaseInsensitiveDict """ return CaseInsensitiveDict( { "User-Agent": default_user_agent(), "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, "Accept": "*/*", "Connection": "keep-alive", } )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L893-L904
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
81.742739
12
1
100
1
def default_headers(): return CaseInsensitiveDict( { "User-Agent": default_user_agent(), "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, "Accept": "*/*", "Connection": "keep-alive", } )
22,074
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
parse_header_links
(value)
return links
Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list
Return a list of parsed link headers proxies.
907
941
def parse_header_links(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = " '\"" value = value.strip(replace_chars) if not value: return links for val in re.split(", *<", value): try: url, params = val.split(";", 1) except ValueError: url, params = val, "" link = {"url": url.strip("<> '\"")} for param in params.split(";"): try: key, value = param.split("=") except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L907-L941
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 ]
100
[]
0
true
81.742739
35
6
100
5
def parse_header_links(value): links = [] replace_chars = " '\"" value = value.strip(replace_chars) if not value: return links for val in re.split(", *<", value): try: url, params = val.split(";", 1) except ValueError: url, params = val, "" link = {"url": url.strip("<> '\"")} for param in params.split(";"): try: key, value = param.split("=") except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links
22,075
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
guess_json_utf
(data)
return None
:rtype: str
:rtype: str
950
979
def guess_json_utf(data): """ :rtype: str """ # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. sample = data[:4] if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): return "utf-32" # BOM included if sample[:3] == codecs.BOM_UTF8: return "utf-8-sig" # BOM included, MS style (discouraged) if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): return "utf-16" # BOM included nullcount = sample.count(_null) if nullcount == 0: return "utf-8" if nullcount == 2: if sample[::2] == _null2: # 1st and 3rd are null return "utf-16-be" if sample[1::2] == _null2: # 2nd and 4th are null return "utf-16-le" # Did not detect 2 valid UTF-16 ascii-range characters if nullcount == 3: if sample[:3] == _null3: return "utf-32-be" if sample[1:] == _null3: return "utf-32-le" # Did not detect a valid UTF-32 ascii-range character return None
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L950-L979
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
81.742739
30
11
100
1
def guess_json_utf(data): # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. sample = data[:4] if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): return "utf-32" # BOM included if sample[:3] == codecs.BOM_UTF8: return "utf-8-sig" # BOM included, MS style (discouraged) if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): return "utf-16" # BOM included nullcount = sample.count(_null) if nullcount == 0: return "utf-8" if nullcount == 2: if sample[::2] == _null2: # 1st and 3rd are null return "utf-16-be" if sample[1::2] == _null2: # 2nd and 4th are null return "utf-16-le" # Did not detect 2 valid UTF-16 ascii-range characters if nullcount == 3: if sample[:3] == _null3: return "utf-32-be" if sample[1:] == _null3: return "utf-32-le" # Did not detect a valid UTF-32 ascii-range character return None
22,076
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
prepend_scheme_if_needed
(url, new_scheme)
return urlunparse((scheme, netloc, path, "", query, fragment))
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument.
982
1,008
def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ parsed = parse_url(url) scheme, auth, host, port, path, query, fragment = parsed # A defect in urlparse determines that there isn't a netloc present in some # urls. We previously assumed parsing was overly cautious, and swapped the # netloc and path. Due to a lack of tests on the original defect, this is # maintained with parse_url for backwards compatibility. netloc = parsed.netloc if not netloc: netloc, path = path, netloc if auth: # parse_url doesn't provide the netloc with auth # so we'll add it ourselves. netloc = "@".join([auth, netloc]) if scheme is None: scheme = new_scheme if path is None: path = "" return urlunparse((scheme, netloc, path, "", query, fragment))
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L982-L1008
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
81.742739
27
5
100
4
def prepend_scheme_if_needed(url, new_scheme): parsed = parse_url(url) scheme, auth, host, port, path, query, fragment = parsed # A defect in urlparse determines that there isn't a netloc present in some # urls. We previously assumed parsing was overly cautious, and swapped the # netloc and path. Due to a lack of tests on the original defect, this is # maintained with parse_url for backwards compatibility. netloc = parsed.netloc if not netloc: netloc, path = path, netloc if auth: # parse_url doesn't provide the netloc with auth # so we'll add it ourselves. netloc = "@".join([auth, netloc]) if scheme is None: scheme = new_scheme if path is None: path = "" return urlunparse((scheme, netloc, path, "", query, fragment))
22,077
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
get_auth_from_url
(url)
return auth
Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str)
Given a url with authentication components, extract them into a tuple of username,password.
1,011
1,024
def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ("", "") return auth
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L1011-L1024
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
81.742739
14
2
100
4
def get_auth_from_url(url): parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ("", "") return auth
22,078
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
check_header_validity
(header)
Verifies that header parts don't contain leading whitespace reserved characters, or return characters. :param header: tuple, in the format (name, value).
Verifies that header parts don't contain leading whitespace reserved characters, or return characters.
1,027
1,043
def check_header_validity(header): """Verifies that header parts don't contain leading whitespace reserved characters, or return characters. :param header: tuple, in the format (name, value). """ name, value = header for part in header: if type(part) not in HEADER_VALIDATORS: raise InvalidHeader( f"Header part ({part!r}) from {{{name!r}: {value!r}}} must be " f"of type str or bytes, not {type(part)}" ) _validate_header_part(name, "name", HEADER_VALIDATORS[type(name)][0]) _validate_header_part(value, "value", HEADER_VALIDATORS[type(value)][1])
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L1027-L1043
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
81.742739
17
3
100
4
def check_header_validity(header): name, value = header for part in header: if type(part) not in HEADER_VALIDATORS: raise InvalidHeader( f"Header part ({part!r}) from {{{name!r}: {value!r}}} must be " f"of type str or bytes, not {type(part)}" ) _validate_header_part(name, "name", HEADER_VALIDATORS[type(name)][0]) _validate_header_part(value, "value", HEADER_VALIDATORS[type(value)][1])
22,079
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
_validate_header_part
(header_part, header_kind, validator)
1,046
1,051
def _validate_header_part(header_part, header_kind, validator): if not validator.match(header_part): raise InvalidHeader( f"Invalid leading whitespace, reserved character(s), or return" f"character(s) in header {header_kind}: {header_part!r}" )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L1046-L1051
33
[ 0, 1, 2 ]
50
[]
0
false
81.742739
6
2
100
0
def _validate_header_part(header_part, header_kind, validator): if not validator.match(header_part): raise InvalidHeader( f"Invalid leading whitespace, reserved character(s), or return" f"character(s) in header {header_kind}: {header_part!r}" )
22,080
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
urldefragauth
(url)
return urlunparse((scheme, netloc, path, params, query, ""))
Given a url remove the fragment and the authentication part. :rtype: str
Given a url remove the fragment and the authentication part.
1,054
1,068
def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit("@", 1)[-1] return urlunparse((scheme, netloc, path, params, query, ""))
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L1054-L1068
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
81.742739
15
2
100
3
def urldefragauth(url): scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit("@", 1)[-1] return urlunparse((scheme, netloc, path, params, query, ""))
22,081
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/utils.py
rewind_body
(prepared_request)
Move file pointer back to its recorded starting position so it can be read again on redirect.
Move file pointer back to its recorded starting position so it can be read again on redirect.
1,071
1,086
def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, "seek", None) if body_seek is not None and isinstance( prepared_request._body_position, integer_types ): try: body_seek(prepared_request._body_position) except OSError: raise UnrewindableBodyError( "An error occurred when rewinding request body for redirect." ) else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/utils.py#L1071-L1086
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
81.742739
16
4
100
2
def rewind_body(prepared_request): body_seek = getattr(prepared_request.body, "seek", None) if body_seek is not None and isinstance( prepared_request._body_position, integer_types ): try: body_seek(prepared_request._body_position) except OSError: raise UnrewindableBodyError( "An error occurred when rewinding request body for redirect." ) else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
22,082
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__init__
(self, data=None, **kwargs)
40
44
def __init__(self, data=None, **kwargs): self._store = OrderedDict() if data is None: data = {} self.update(data, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L40-L44
33
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
100
5
2
100
0
def __init__(self, data=None, **kwargs): self._store = OrderedDict() if data is None: data = {} self.update(data, **kwargs)
22,083
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/structures.py
CaseInsensitiveDict.__setitem__
(self, key, value)
46
49
def __setitem__(self, key, value): # Use the lowercased key for lookups, but store the actual # key alongside the value. self._store[key.lower()] = (key, value)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/structures.py#L46-L49
33
[ 0, 1, 2, 3 ]
100
[]
0
true
100
4
1
100
0
def __setitem__(self, key, value): # Use the lowercased key for lookups, but store the actual # key alongside the value. self._store[key.lower()] = (key, value)
22,084