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
sequence | executed_lines_pc
float64 0
153
| missing_lines
sequence | 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | normalize_pairs | (
inp: Sequence[tuple[str, Any]] | Mapping[str, Any]
) | return list(inp.items()) if isinstance(inp, typing.Mapping) else inp | 51 | 55 | def normalize_pairs(
inp: Sequence[tuple[str, Any]] | Mapping[str, Any]
) -> Sequence[tuple[str, Any]]:
# pylint: disable=deprecated-typing-alias
return list(inp.items()) if isinstance(inp, typing.Mapping) else inp | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L51-L55 | 1 | [
0,
3,
4
] | 60 | [] | 0 | false | 86.167147 | 5 | 1 | 100 | 0 | def normalize_pairs(
inp: Sequence[tuple[str, Any]] | Mapping[str, Any]
) -> Sequence[tuple[str, Any]]:
# pylint: disable=deprecated-typing-alias
return list(inp.items()) if isinstance(inp, typing.Mapping) else inp | 0 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.__init__ | (
self,
body: bytes,
*,
document_type: None | str = "html",
head: None | bytes = None,
headers: None | email.message.Message = None,
encoding: None | str = None,
code: None | int = None,
url: None | str = None,
cookies: None | Sequence[Cookie] = None,
) | 88 | 125 | def __init__(
self,
body: bytes,
*,
document_type: None | str = "html",
head: None | bytes = None,
headers: None | email.message.Message = None,
encoding: None | str = None,
code: None | int = None,
url: None | str = None,
cookies: None | Sequence[Cookie] = None,
) -> None:
# Cache attributes
self._unicode_body: None | str = None
self._lxml_tree: None | _Element = None
self._strict_lxml_tree: None | _Element = None
self._pyquery = None
self._lxml_form: None | FormElement = None
self._file_fields: MutableMapping[str, Any] = {}
# Main attributes
self.document_type = document_type
if not isinstance(body, bytes):
raise ValueError("Argument 'body' must be bytes")
self._bytes_body = body
self.code = code
self.head = head
self.headers: email.message.Message = headers or email.message.Message()
self.url = url
# Encoding must be processed AFTER body and headers are set
self.encoding = self.process_encoding(encoding)
# other
self.cookies = cookies or []
self.download_size = 0
self.upload_size = 0
self.download_speed = 0
self.error_code = None
self.error_msg = None
self.from_cache = False | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L88-L125 | 1 | [
0,
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
] | 71.052632 | [] | 0 | false | 86.167147 | 38 | 4 | 100 | 0 | def __init__(
self,
body: bytes,
*,
document_type: None | str = "html",
head: None | bytes = None,
headers: None | email.message.Message = None,
encoding: None | str = None,
code: None | int = None,
url: None | str = None,
cookies: None | Sequence[Cookie] = None,
) -> None:
# Cache attributes
self._unicode_body: None | str = None
self._lxml_tree: None | _Element = None
self._strict_lxml_tree: None | _Element = None
self._pyquery = None
self._lxml_form: None | FormElement = None
self._file_fields: MutableMapping[str, Any] = {}
# Main attributes
self.document_type = document_type
if not isinstance(body, bytes):
raise ValueError("Argument 'body' must be bytes")
self._bytes_body = body
self.code = code
self.head = head
self.headers: email.message.Message = headers or email.message.Message()
self.url = url
# Encoding must be processed AFTER body and headers are set
self.encoding = self.process_encoding(encoding)
# other
self.cookies = cookies or []
self.download_size = 0
self.upload_size = 0
self.download_speed = 0
self.error_code = None
self.error_msg = None
self.from_cache = False | 1 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.__call__ | (self, query: str) | return self.select(query) | 128 | 129 | def __call__(self, query: str) -> SelectorList[_Element]:
return self.select(query) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L128-L129 | 1 | [
0
] | 50 | [
1
] | 50 | false | 86.167147 | 2 | 1 | 50 | 0 | def __call__(self, query: str) -> SelectorList[_Element]:
return self.select(query) | 2 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.select | (self, *args: Any, **kwargs: Any) | return XpathSelector(self.tree).select(*args, **kwargs) | 131 | 132 | def select(self, *args: Any, **kwargs: Any) -> SelectorList[_Element]:
return XpathSelector(self.tree).select(*args, **kwargs) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L131-L132 | 1 | [
0,
1
] | 100 | [] | 0 | true | 86.167147 | 2 | 1 | 100 | 0 | def select(self, *args: Any, **kwargs: Any) -> SelectorList[_Element]:
return XpathSelector(self.tree).select(*args, **kwargs) | 3 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.process_encoding | (self, encoding: None | str = None) | return unicodec.detect_content_encoding(
self.get_body_chunk() or b"",
content_type_header=(
self.headers.get("Content-Type", None) if self.headers else None
),
markup="xml" if self.document_type == "xml" else "html",
) | Process explicitly defined encoding or auto-detect it.
If encoding is explicitly defined, ensure it is a valid encoding the python
can deal with. If encoding is not specified, auto-detect it.
Raises unicodec.InvalidEncodingName if explicitly set encoding is invalid. | Process explicitly defined encoding or auto-detect it. | 134 | 150 | def process_encoding(self, encoding: None | str = None) -> str:
"""Process explicitly defined encoding or auto-detect it.
If encoding is explicitly defined, ensure it is a valid encoding the python
can deal with. If encoding is not specified, auto-detect it.
Raises unicodec.InvalidEncodingName if explicitly set encoding is invalid.
"""
if encoding:
return unicodec.normalize_encoding_name(encoding)
return unicodec.detect_content_encoding(
self.get_body_chunk() or b"",
content_type_header=(
self.headers.get("Content-Type", None) if self.headers else None
),
markup="xml" if self.document_type == "xml" else "html",
) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L134-L150 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16
] | 100 | [] | 0 | true | 86.167147 | 17 | 3 | 100 | 6 | def process_encoding(self, encoding: None | str = None) -> str:
if encoding:
return unicodec.normalize_encoding_name(encoding)
return unicodec.detect_content_encoding(
self.get_body_chunk() or b"",
content_type_header=(
self.headers.get("Content-Type", None) if self.headers else None
),
markup="xml" if self.document_type == "xml" else "html",
) | 4 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.copy | (self) | return self.__class__(
code=self.code,
head=self.head,
body=self.body,
url=self.url,
headers=deepcopy(self.headers),
encoding=self.encoding,
document_type=self.document_type,
cookies=copy(self.cookies),
) | 152 | 162 | def copy(self) -> Document:
return self.__class__(
code=self.code,
head=self.head,
body=self.body,
url=self.url,
headers=deepcopy(self.headers),
encoding=self.encoding,
document_type=self.document_type,
cookies=copy(self.cookies),
) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L152-L162 | 1 | [
0,
1
] | 18.181818 | [] | 0 | false | 86.167147 | 11 | 1 | 100 | 0 | def copy(self) -> Document:
return self.__class__(
code=self.code,
head=self.head,
body=self.body,
url=self.url,
headers=deepcopy(self.headers),
encoding=self.encoding,
document_type=self.document_type,
cookies=copy(self.cookies),
) | 5 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.save | (self, path: str) | Save response body to file. | Save response body to file. | 164 | 172 | def save(self, path: str) -> None:
"""Save response body to file."""
path_dir = os.path.split(path)[0]
if not os.path.exists(path_dir):
with suppress(OSError):
os.makedirs(path_dir)
with open(path, "wb") as out:
out.write(self.body) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L164-L172 | 1 | [
0,
1,
2,
3,
6,
7,
8
] | 77.777778 | [
4,
5
] | 22.222222 | false | 86.167147 | 9 | 4 | 77.777778 | 1 | def save(self, path: str) -> None:
path_dir = os.path.split(path)[0]
if not os.path.exists(path_dir):
with suppress(OSError):
os.makedirs(path_dir)
with open(path, "wb") as out:
out.write(self.body) | 6 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.status | (self) | return self.code | 175 | 176 | def status(self) -> None | int:
return self.code | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L175-L176 | 1 | [
0
] | 50 | [
1
] | 50 | false | 86.167147 | 2 | 1 | 50 | 0 | def status(self) -> None | int:
return self.code | 7 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.status | (self, val: int) | 179 | 180 | def status(self, val: int) -> None:
self.code = val | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L179-L180 | 1 | [
0
] | 50 | [
1
] | 50 | false | 86.167147 | 2 | 1 | 50 | 0 | def status(self, val: int) -> None:
self.code = val | 8 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.json | (self) | return json.loads(self.body.decode(self.encoding)) | Return response body deserialized into JSON object. | Return response body deserialized into JSON object. | 183 | 186 | def json(self) -> Any:
"""Return response body deserialized into JSON object."""
assert self.body is not None
return json.loads(self.body.decode(self.encoding)) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L183-L186 | 1 | [
0,
1,
2,
3
] | 100 | [] | 0 | true | 86.167147 | 4 | 2 | 100 | 1 | def json(self) -> Any:
assert self.body is not None
return json.loads(self.body.decode(self.encoding)) | 9 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.url_details | (self) | return urlsplit(cast(str, self.url)) | Return result of urlsplit function applied to response url. | Return result of urlsplit function applied to response url. | 188 | 190 | def url_details(self) -> SplitResult:
"""Return result of urlsplit function applied to response url."""
return urlsplit(cast(str, self.url)) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L188-L190 | 1 | [
0,
1
] | 66.666667 | [
2
] | 33.333333 | false | 86.167147 | 3 | 1 | 66.666667 | 1 | def url_details(self) -> SplitResult:
return urlsplit(cast(str, self.url)) | 10 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.query_param | (self, key: str) | return parse_qs(self.url_details().query)[key][0] | Return value of parameter in query string. | Return value of parameter in query string. | 192 | 194 | def query_param(self, key: str) -> str:
"""Return value of parameter in query string."""
return parse_qs(self.url_details().query)[key][0] | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L192-L194 | 1 | [
0,
1
] | 66.666667 | [
2
] | 33.333333 | false | 86.167147 | 3 | 1 | 66.666667 | 1 | def query_param(self, key: str) -> str:
return parse_qs(self.url_details().query)[key][0] | 11 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.browse | (self) | Save response in temporary file and open it in GUI browser. | Save response in temporary file and open it in GUI browser. | 196 | 200 | def browse(self) -> None:
"""Save response in temporary file and open it in GUI browser."""
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open("file://" + path) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L196-L200 | 1 | [
0,
1
] | 40 | [
2,
3,
4
] | 60 | false | 86.167147 | 5 | 1 | 40 | 1 | def browse(self) -> None:
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open("file://" + path) | 12 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.__getstate__ | (self) | return state | Reset cached lxml objects which could not be pickled. | Reset cached lxml objects which could not be pickled. | 202 | 213 | def __getstate__(self) -> Mapping[str, Any]:
"""Reset cached lxml objects which could not be pickled."""
state: dict[str, Any] = {}
for cls in type(self).mro():
cls_slots = getattr(cls, "__slots__", ())
for slot_name in cls_slots:
if hasattr(self, slot_name):
state[slot_name] = getattr(self, slot_name)
state["_lxml_tree"] = None
state["_strict_lxml_tree"] = None
state["_lxml_form"] = None
return state | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L202-L213 | 1 | [
0,
1
] | 16.666667 | [
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 83.333333 | false | 86.167147 | 12 | 4 | 16.666667 | 1 | def __getstate__(self) -> Mapping[str, Any]:
state: dict[str, Any] = {}
for cls in type(self).mro():
cls_slots = getattr(cls, "__slots__", ())
for slot_name in cls_slots:
if hasattr(self, slot_name):
state[slot_name] = getattr(self, slot_name)
state["_lxml_tree"] = None
state["_strict_lxml_tree"] = None
state["_lxml_form"] = None
return state | 13 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.__setstate__ | (self, state: Mapping[str, Any]) | 215 | 218 | def __setstate__(self, state: Mapping[str, Any]) -> None:
# TODO: check assigned key is in slots
for slot_name, value in state.items():
setattr(self, slot_name, value) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L215-L218 | 1 | [
0,
1
] | 50 | [
2,
3
] | 50 | false | 86.167147 | 4 | 2 | 50 | 0 | def __setstate__(self, state: Mapping[str, Any]) -> None:
# TODO: check assigned key is in slots
for slot_name, value in state.items():
setattr(self, slot_name, value) | 14 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.text_search | (self, anchor: str | bytes) | return anchor in self.body | Search the substring in response body.
:param anchor: string to search
:param byte: if False then `anchor` should be the
unicode string, and search will be performed in
`response.unicode_body()` else `anchor` should be the byte-string
and search will be performed in `response.body`
If substring is found return True else False. | Search the substring in response body. | 222 | 236 | def text_search(self, anchor: str | bytes) -> bool:
"""Search the substring in response body.
:param anchor: string to search
:param byte: if False then `anchor` should be the
unicode string, and search will be performed in
`response.unicode_body()` else `anchor` should be the byte-string
and search will be performed in `response.body`
If substring is found return True else False.
"""
assert self.body is not None
if isinstance(anchor, str):
return anchor in self.unicode_body()
return anchor in self.body | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L222-L236 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
] | 100 | [] | 0 | true | 86.167147 | 15 | 3 | 100 | 9 | def text_search(self, anchor: str | bytes) -> bool:
assert self.body is not None
if isinstance(anchor, str):
return anchor in self.unicode_body()
return anchor in self.body | 15 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.text_assert | (self, anchor: str | bytes) | If `anchor` is not found then raise `DataNotFound` exception. | If `anchor` is not found then raise `DataNotFound` exception. | 238 | 241 | def text_assert(self, anchor: str | bytes) -> None:
"""If `anchor` is not found then raise `DataNotFound` exception."""
if not self.text_search(anchor):
raise DataNotFound("Substring not found: {}".format(str(anchor))) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L238-L241 | 1 | [
0,
1,
2,
3
] | 100 | [] | 0 | true | 86.167147 | 4 | 2 | 100 | 1 | def text_assert(self, anchor: str | bytes) -> None:
if not self.text_search(anchor):
raise DataNotFound("Substring not found: {}".format(str(anchor))) | 16 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.text_assert_any | (self, anchors: Sequence[str | bytes]) | If no `anchors` were found then raise `DataNotFound` exception. | If no `anchors` were found then raise `DataNotFound` exception. | 243 | 248 | def text_assert_any(self, anchors: Sequence[str | bytes]) -> None:
"""If no `anchors` were found then raise `DataNotFound` exception."""
if not any(self.text_search(x) for x in anchors):
raise DataNotFound(
"Substrings not found: %s" % ", ".join(map(str, anchors))
) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L243-L248 | 1 | [
0,
1,
2,
3,
4,
5
] | 100 | [] | 0 | true | 86.167147 | 6 | 2 | 100 | 1 | def text_assert_any(self, anchors: Sequence[str | bytes]) -> None:
if not any(self.text_search(x) for x in anchors):
raise DataNotFound(
"Substrings not found: %s" % ", ".join(map(str, anchors))
) | 17 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.rex_text | (
self,
regexp: str | bytes | Pattern[str] | Pattern[bytes],
flags: int = 0,
default: Any = UNDEFINED,
) | Return content of first matching group of regexp found in response body. | Return content of first matching group of regexp found in response body. | 252 | 266 | def rex_text(
self,
regexp: str | bytes | Pattern[str] | Pattern[bytes],
flags: int = 0,
default: Any = UNDEFINED,
) -> Any:
"""Return content of first matching group of regexp found in response body."""
try:
match = self.rex_search(regexp, flags=flags)
except DataNotFound as ex:
if default is UNDEFINED:
raise DataNotFound("Regexp not found") from ex
return default
else:
return match.group(1) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L252-L266 | 1 | [
0,
6,
7,
8,
13,
14
] | 40 | [
9,
10,
11,
12
] | 26.666667 | false | 86.167147 | 15 | 3 | 73.333333 | 1 | def rex_text(
self,
regexp: str | bytes | Pattern[str] | Pattern[bytes],
flags: int = 0,
default: Any = UNDEFINED,
) -> Any:
try:
match = self.rex_search(regexp, flags=flags)
except DataNotFound as ex:
if default is UNDEFINED:
raise DataNotFound("Regexp not found") from ex
return default
else:
return match.group(1) | 18 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.rex_search | (
self,
regexp: str | bytes | Pattern[str] | Pattern[bytes],
flags: int = 0,
default: Any = UNDEFINED,
) | return default | Search the regular expression in response body.
Return found match object or None | Search the regular expression in response body. | 268 | 291 | def rex_search(
self,
regexp: str | bytes | Pattern[str] | Pattern[bytes],
flags: int = 0,
default: Any = UNDEFINED,
) -> Any:
"""Search the regular expression in response body.
Return found match object or None
"""
match: None | Match[bytes] | Match[str] = None
assert self.body is not None
if isinstance(regexp, (bytes, str)):
regexp = re.compile(regexp, flags=flags)
match = (
regexp.search(self.body)
if isinstance(regexp.pattern, bytes)
else regexp.search(self.unicode_body())
)
if match:
return match
if default is UNDEFINED:
raise DataNotFound("Could not find regexp: %s" % regexp)
return default | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L268-L291 | 1 | [
0,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22
] | 62.5 | [
23
] | 4.166667 | false | 86.167147 | 24 | 5 | 95.833333 | 3 | def rex_search(
self,
regexp: str | bytes | Pattern[str] | Pattern[bytes],
flags: int = 0,
default: Any = UNDEFINED,
) -> Any:
match: None | Match[bytes] | Match[str] = None
assert self.body is not None
if isinstance(regexp, (bytes, str)):
regexp = re.compile(regexp, flags=flags)
match = (
regexp.search(self.body)
if isinstance(regexp.pattern, bytes)
else regexp.search(self.unicode_body())
)
if match:
return match
if default is UNDEFINED:
raise DataNotFound("Could not find regexp: %s" % regexp)
return default | 19 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.rex_assert | (
self,
rex: str | bytes | Pattern[str] | Pattern[bytes],
) | Raise `DataNotFound` exception if `rex` expression is not found. | Raise `DataNotFound` exception if `rex` expression is not found. | 293 | 300 | def rex_assert(
self,
rex: str | bytes | Pattern[str] | Pattern[bytes],
) -> None:
"""Raise `DataNotFound` exception if `rex` expression is not found."""
# if given regexp not found, rex_search() will raise DataNotFound
# because default argument is not set
self.rex_search(rex) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L293-L300 | 1 | [
0,
6,
7
] | 37.5 | [] | 0 | false | 86.167147 | 8 | 1 | 100 | 1 | def rex_assert(
self,
rex: str | bytes | Pattern[str] | Pattern[bytes],
) -> None:
# if given regexp not found, rex_search() will raise DataNotFound
# because default argument is not set
self.rex_search(rex) | 20 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.pyquery | (self) | return self._pyquery | Return pyquery handler. | Return pyquery handler. | 305 | 314 | def pyquery(self) -> Any:
"""Return pyquery handler."""
if not self._pyquery:
# pytype: disable=import-error
from pyquery import PyQuery # pylint: disable=import-outside-toplevel
# pytype: enable=import-error
self._pyquery = PyQuery(self.tree)
return self._pyquery | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L305-L314 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 | [] | 0 | true | 86.167147 | 10 | 2 | 100 | 1 | def pyquery(self) -> Any:
if not self._pyquery:
# pytype: disable=import-error
from pyquery import PyQuery # pylint: disable=import-outside-toplevel
# pytype: enable=import-error
self._pyquery = PyQuery(self.tree)
return self._pyquery | 21 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.get_body_chunk | (self) | return self.body[:4096] | 318 | 319 | def get_body_chunk(self) -> bytes:
return self.body[:4096] | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L318-L319 | 1 | [
0,
1
] | 100 | [] | 0 | true | 86.167147 | 2 | 1 | 100 | 0 | def get_body_chunk(self) -> bytes:
return self.body[:4096] | 22 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.unicode_body | (
self,
) | return self._unicode_body | Return response body as unicode string. | Return response body as unicode string. | 321 | 330 | def unicode_body(
self,
) -> str:
"""Return response body as unicode string."""
if not self._unicode_body:
# FIXME: ignore_errors option
self._unicode_body = unicodec.decode_content(
self.body, encoding=self.encoding
)
return self._unicode_body | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L321-L330 | 1 | [
0,
3,
4,
5,
6,
7,
8,
9
] | 80 | [] | 0 | false | 86.167147 | 10 | 2 | 100 | 1 | def unicode_body(
self,
) -> str:
if not self._unicode_body:
# FIXME: ignore_errors option
self._unicode_body = unicodec.decode_content(
self.body, encoding=self.encoding
)
return self._unicode_body | 23 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.body | (self) | return self._bytes_body | 333 | 334 | def body(self) -> bytes:
return self._bytes_body | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L333-L334 | 1 | [
0,
1
] | 100 | [] | 0 | true | 86.167147 | 2 | 1 | 100 | 0 | def body(self) -> bytes:
return self._bytes_body | 24 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.tree | (self) | return self.build_html_tree() | Return DOM tree of the document built with HTML DOM builder. | Return DOM tree of the document built with HTML DOM builder. | 343 | 347 | def tree(self) -> _Element:
"""Return DOM tree of the document built with HTML DOM builder."""
if self.document_type == "xml":
return self.build_xml_tree()
return self.build_html_tree() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L343-L347 | 1 | [
0,
1,
2,
3,
4
] | 100 | [] | 0 | true | 86.167147 | 5 | 2 | 100 | 1 | def tree(self) -> _Element:
if self.document_type == "xml":
return self.build_xml_tree()
return self.build_html_tree() | 25 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.wrap_io | (cls, inp: bytes | str) | return BytesIO(inp) if isinstance(inp, bytes) else StringIO(inp) | 350 | 351 | def wrap_io(cls, inp: bytes | str) -> StringIO | BytesIO:
return BytesIO(inp) if isinstance(inp, bytes) else StringIO(inp) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L350-L351 | 1 | [
0,
1
] | 100 | [] | 0 | true | 86.167147 | 2 | 1 | 100 | 0 | def wrap_io(cls, inp: bytes | str) -> StringIO | BytesIO:
return BytesIO(inp) if isinstance(inp, bytes) else StringIO(inp) | 26 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document._build_dom | (cls, content: bytes | str, mode: str, encoding: str) | return dom.getroot() | 354 | 370 | def _build_dom(cls, content: bytes | str, mode: str, encoding: str) -> _Element:
assert mode in {"html", "xml"}
if mode == "html":
if not hasattr(THREAD_STORAGE, "html_parsers"):
THREAD_STORAGE.html_parsers = {}
parser = THREAD_STORAGE.html_parsers.setdefault(
encoding, HTMLParser(encoding=encoding)
)
dom = etree.parse(cls.wrap_io(content), parser=parser)
return dom.getroot()
if not hasattr(THREAD_STORAGE, "xml_parser"):
THREAD_STORAGE.xml_parsers = {}
parser = THREAD_STORAGE.xml_parsers.setdefault(
encoding, etree.XMLParser(resolve_entities=False)
)
dom = etree.parse(cls.wrap_io(content), parser=parser)
return dom.getroot() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L354-L370 | 1 | [
0,
1,
2,
3,
4,
5,
8,
9,
10,
11,
12,
15,
16
] | 76.470588 | [] | 0 | false | 86.167147 | 17 | 5 | 100 | 0 | def _build_dom(cls, content: bytes | str, mode: str, encoding: str) -> _Element:
assert mode in {"html", "xml"}
if mode == "html":
if not hasattr(THREAD_STORAGE, "html_parsers"):
THREAD_STORAGE.html_parsers = {}
parser = THREAD_STORAGE.html_parsers.setdefault(
encoding, HTMLParser(encoding=encoding)
)
dom = etree.parse(cls.wrap_io(content), parser=parser)
return dom.getroot()
if not hasattr(THREAD_STORAGE, "xml_parser"):
THREAD_STORAGE.xml_parsers = {}
parser = THREAD_STORAGE.xml_parsers.setdefault(
encoding, etree.XMLParser(resolve_entities=False)
)
dom = etree.parse(cls.wrap_io(content), parser=parser)
return dom.getroot() | 27 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.build_html_tree | (self) | return self._lxml_tree | 372 | 403 | def build_html_tree(self) -> _Element:
if self._lxml_tree is None:
assert self.body is not None
ubody = self.unicode_body()
body: None | bytes = (
ubody.encode(self.encoding) if ubody is not None else None
)
if not body:
# Generate minimal empty content
# which will not break lxml parser
body = b"<html></html>"
try:
self._lxml_tree = self._build_dom(body, "html", self.encoding)
except Exception as ex:
# FIXME: write test for this case
if b"<html" not in body and (
# Fix for "just a string" body
(
isinstance(ex, etree.ParserError)
and "Document is empty" in str(ex)
)
# Fix for smth like "<frameset></frameset>"
or (
isinstance(ex, TypeError)
and "object of type 'NoneType' has no len" in str(ex)
)
):
body = b"<html>%s</html>" % body
self._lxml_tree = self._build_dom(body, "html", self.encoding)
else:
raise
return self._lxml_tree | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L372-L403 | 1 | [
0,
1,
2,
3,
4,
7,
8,
9,
10,
11,
12,
31
] | 37.5 | [
13,
15,
27,
28,
30
] | 15.625 | false | 86.167147 | 32 | 10 | 84.375 | 0 | def build_html_tree(self) -> _Element:
if self._lxml_tree is None:
assert self.body is not None
ubody = self.unicode_body()
body: None | bytes = (
ubody.encode(self.encoding) if ubody is not None else None
)
if not body:
# Generate minimal empty content
# which will not break lxml parser
body = b"<html></html>"
try:
self._lxml_tree = self._build_dom(body, "html", self.encoding)
except Exception as ex:
# FIXME: write test for this case
if b"<html" not in body and (
# Fix for "just a string" body
(
isinstance(ex, etree.ParserError)
and "Document is empty" in str(ex)
)
# Fix for smth like "<frameset></frameset>"
or (
isinstance(ex, TypeError)
and "object of type 'NoneType' has no len" in str(ex)
)
):
body = b"<html>%s</html>" % body
self._lxml_tree = self._build_dom(body, "html", self.encoding)
else:
raise
return self._lxml_tree | 28 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.build_xml_tree | (self) | return self._strict_lxml_tree | 405 | 411 | def build_xml_tree(self) -> _Element:
if self._strict_lxml_tree is None:
ubody = self.unicode_body()
assert ubody is not None
body = ubody.encode(self.encoding)
self._strict_lxml_tree = self._build_dom(body, "xml", self.encoding)
return self._strict_lxml_tree | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L405-L411 | 1 | [
0,
1,
2,
3,
4,
5,
6
] | 100 | [] | 0 | true | 86.167147 | 7 | 3 | 100 | 0 | def build_xml_tree(self) -> _Element:
if self._strict_lxml_tree is None:
ubody = self.unicode_body()
assert ubody is not None
body = ubody.encode(self.encoding)
self._strict_lxml_tree = self._build_dom(body, "xml", self.encoding)
return self._strict_lxml_tree | 29 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.choose_form | (
self,
number: None | int = None,
xpath: None | str = None,
name: None | str = None,
**kwargs: Any,
) | Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`DataNotFound` if form not found
:raises: :class:`GrabMisuseError`
if method is called without parameters
Selected form will be available via `form` attribute of `Grab`
instance. All form methods will work with default form.
Examples::
# Select second form
g.choose_form(1)
# Select by id
g.choose_form(id="register")
# Select by name
g.choose_form(name="signup")
# Select by xpath
g.choose_form(xpath='//form[contains(@action, "/submit")]') | Set the default form. | 415 | 467 | def choose_form(
self,
number: None | int = None,
xpath: None | str = None,
name: None | str = None,
**kwargs: Any,
) -> None:
"""Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`DataNotFound` if form not found
:raises: :class:`GrabMisuseError`
if method is called without parameters
Selected form will be available via `form` attribute of `Grab`
instance. All form methods will work with default form.
Examples::
# Select second form
g.choose_form(1)
# Select by id
g.choose_form(id="register")
# Select by name
g.choose_form(name="signup")
# Select by xpath
g.choose_form(xpath='//form[contains(@action, "/submit")]')
"""
idx = 0
if kwargs.get("id") is not None:
query = '//form[@id="{}"]'.format(kwargs["id"])
elif name is not None:
query = '//form[@name="{}"]'.format(name)
elif number is not None:
query = "//form"
idx = number
elif xpath is not None:
query = xpath
else:
raise GrabMisuseError(
"choose_form methods requires one of "
"[number, id, name, xpath] arguments"
)
try:
self._lxml_form = cast(HtmlElement, self.select(query)[idx].node())
except IndexError as ex:
raise DataNotFound("Could not find form with xpath: %s" % xpath) from ex | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L415-L467 | 1 | [
0,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52
] | 39.622642 | [] | 0 | false | 86.167147 | 53 | 6 | 100 | 26 | def choose_form(
self,
number: None | int = None,
xpath: None | str = None,
name: None | str = None,
**kwargs: Any,
) -> None:
idx = 0
if kwargs.get("id") is not None:
query = '//form[@id="{}"]'.format(kwargs["id"])
elif name is not None:
query = '//form[@name="{}"]'.format(name)
elif number is not None:
query = "//form"
idx = number
elif xpath is not None:
query = xpath
else:
raise GrabMisuseError(
"choose_form methods requires one of "
"[number, id, name, xpath] arguments"
)
try:
self._lxml_form = cast(HtmlElement, self.select(query)[idx].node())
except IndexError as ex:
raise DataNotFound("Could not find form with xpath: %s" % xpath) from ex | 30 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.form | (self) | return self._lxml_form | Return default document's form.
If form was not selected manually then select the form
which has the biggest number of input elements.
The form value is just an `lxml.html` form element.
Example::
g.request('some URL')
# Choose form automatically
print g.form
# And now choose form manually
g.choose_form(1)
print g.form | Return default document's form. | 470 | 498 | def form(self) -> FormElement:
"""Return default document's form.
If form was not selected manually then select the form
which has the biggest number of input elements.
The form value is just an `lxml.html` form element.
Example::
g.request('some URL')
# Choose form automatically
print g.form
# And now choose form manually
g.choose_form(1)
print g.form
"""
if self._lxml_form is None:
forms = [
(idx, len(list(x.fields)))
for idx, x in enumerate(cast(HtmlElement, self.tree).forms)
]
if forms:
idx = sorted(forms, key=lambda x: x[1], reverse=True)[0][0]
self.choose_form(idx)
else:
raise DataNotFound("Response does not contains any form")
return self._lxml_form | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L470-L498 | 1 | [
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
] | 100 | [] | 0 | true | 86.167147 | 29 | 4 | 100 | 16 | def form(self) -> FormElement:
if self._lxml_form is None:
forms = [
(idx, len(list(x.fields)))
for idx, x in enumerate(cast(HtmlElement, self.tree).forms)
]
if forms:
idx = sorted(forms, key=lambda x: x[1], reverse=True)[0][0]
self.choose_form(idx)
else:
raise DataNotFound("Response does not contains any form")
return self._lxml_form | 31 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.get_cached_form | (self) | return self._lxml_form | Get form which has been already selected.
Returns None if form has not been selected yet.
It is for testing mainly. To not trigger pylint warnings about
accessing protected element. | Get form which has been already selected. | 500 | 511 | def get_cached_form(self) -> FormElement:
"""Get form which has been already selected.
Returns None if form has not been selected yet.
It is for testing mainly. To not trigger pylint warnings about
accessing protected element.
"""
if self._lxml_form is None:
raise ValueError("Requested form does not exist")
assert isinstance(self._lxml_form, FormElement)
return self._lxml_form | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L500-L511 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 | [] | 0 | true | 86.167147 | 12 | 3 | 100 | 6 | def get_cached_form(self) -> FormElement:
if self._lxml_form is None:
raise ValueError("Requested form does not exist")
assert isinstance(self._lxml_form, FormElement)
return self._lxml_form | 32 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.set_input | (self, name: str, value: Any) | Set the value of form element by its `name` attribute.
:param name: name of element
:param value: value which should be set to element
To check/uncheck the checkbox pass boolean value.
Example::
g.set_input('sex', 'male')
# Check the checkbox
g.set_input('accept', True) | Set the value of form element by its `name` attribute. | 513 | 545 | def set_input(self, name: str, value: Any) -> None:
"""Set the value of form element by its `name` attribute.
:param name: name of element
:param value: value which should be set to element
To check/uncheck the checkbox pass boolean value.
Example::
g.set_input('sex', 'male')
# Check the checkbox
g.set_input('accept', True)
"""
if self._lxml_form is None:
self.choose_form_by_element('.//*[@name="%s"]' % name)
elem = self.form.inputs[name]
processed = False
if getattr(elem, "type", None) == "checkbox" and isinstance(value, bool):
elem.checked = value
processed = True
if not processed:
# We need to remember original values of file fields
# Because lxml will convert UploadContent/UploadFile object to
# string
if getattr(elem, "type", "").lower() == "file":
self._file_fields[name] = value
elem.value = ""
else:
elem.value = value | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L513-L545 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
23,
24,
25,
26,
27,
28,
31,
32
] | 87.878788 | [
21,
22,
29,
30
] | 12.121212 | false | 86.167147 | 33 | 6 | 87.878788 | 13 | def set_input(self, name: str, value: Any) -> None:
if self._lxml_form is None:
self.choose_form_by_element('.//*[@name="%s"]' % name)
elem = self.form.inputs[name]
processed = False
if getattr(elem, "type", None) == "checkbox" and isinstance(value, bool):
elem.checked = value
processed = True
if not processed:
# We need to remember original values of file fields
# Because lxml will convert UploadContent/UploadFile object to
# string
if getattr(elem, "type", "").lower() == "file":
self._file_fields[name] = value
elem.value = ""
else:
elem.value = value | 33 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.set_input_by_id | (self, _id: str, value: Any) | return self.set_input(elem.get("name"), value) | Set the value of form element by its `id` attribute.
:param _id: id of element
:param value: value which should be set to element | Set the value of form element by its `id` attribute. | 547 | 558 | def set_input_by_id(self, _id: str, value: Any) -> None:
"""Set the value of form element by its `id` attribute.
:param _id: id of element
:param value: value which should be set to element
"""
xpath = './/*[@id="%s"]' % _id
if self._lxml_form is None:
self.choose_form_by_element(xpath)
sel = XpathSelector(self.form)
elem = sel.select(xpath).node()
return self.set_input(elem.get("name"), value) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L547-L558 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 | [] | 0 | true | 86.167147 | 12 | 2 | 100 | 4 | def set_input_by_id(self, _id: str, value: Any) -> None:
xpath = './/*[@id="%s"]' % _id
if self._lxml_form is None:
self.choose_form_by_element(xpath)
sel = XpathSelector(self.form)
elem = sel.select(xpath).node()
return self.set_input(elem.get("name"), value) | 34 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.set_input_by_number | (self, number: int, value: Any) | return self.set_input(elem.get("name"), value) | Set the value of form element by its number in the form.
:param number: number of element
:param value: value which should be set to element | Set the value of form element by its number in the form. | 560 | 568 | def set_input_by_number(self, number: int, value: Any) -> None:
"""Set the value of form element by its number in the form.
:param number: number of element
:param value: value which should be set to element
"""
sel = XpathSelector(self.form)
elem = sel.select('.//input[@type="text"]')[number].node()
return self.set_input(elem.get("name"), value) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L560-L568 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 | [] | 0 | true | 86.167147 | 9 | 1 | 100 | 4 | def set_input_by_number(self, number: int, value: Any) -> None:
sel = XpathSelector(self.form)
elem = sel.select('.//input[@type="text"]')[number].node()
return self.set_input(elem.get("name"), value) | 35 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.set_input_by_xpath | (self, xpath: str, value: Any) | return self.set_input(elem.get("name"), value) | Set the value of form element by xpath.
:param xpath: xpath path
:param value: value which should be set to element | Set the value of form element by xpath. | 570 | 588 | def set_input_by_xpath(self, xpath: str, value: Any) -> None:
"""Set the value of form element by xpath.
:param xpath: xpath path
:param value: value which should be set to element
"""
elem = self.select(xpath).node()
if self._lxml_form is None:
# Explicitly set the default form
# which contains found element
parent = elem
while True:
parent = parent.getparent()
if parent.tag == "form":
self._lxml_form = parent
break
return self.set_input(elem.get("name"), value) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L570-L588 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18
] | 100 | [] | 0 | true | 86.167147 | 19 | 4 | 100 | 4 | def set_input_by_xpath(self, xpath: str, value: Any) -> None:
elem = self.select(xpath).node()
if self._lxml_form is None:
# Explicitly set the default form
# which contains found element
parent = elem
while True:
parent = parent.getparent()
if parent.tag == "form":
self._lxml_form = parent
break
return self.set_input(elem.get("name"), value) | 36 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.process_extra_post | (
self,
post_items: list[tuple[str, Any]],
extra_post_items: Sequence[tuple[str, Any]],
) | return post_items | 595 | 608 | def process_extra_post(
self,
post_items: list[tuple[str, Any]],
extra_post_items: Sequence[tuple[str, Any]],
) -> list[tuple[str, Any]]:
# Drop existing post items with such key
keys_to_drop = {x for x, y in extra_post_items}
for key in keys_to_drop:
post_items = [(x, y) for x, y in post_items if x != key]
for key, value in extra_post_items:
post_items.append((key, value))
return post_items | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L595-L608 | 1 | [
0
] | 7.142857 | [
7,
8,
9,
11,
12,
13
] | 42.857143 | false | 86.167147 | 14 | 4 | 57.142857 | 0 | def process_extra_post(
self,
post_items: list[tuple[str, Any]],
extra_post_items: Sequence[tuple[str, Any]],
) -> list[tuple[str, Any]]:
# Drop existing post items with such key
keys_to_drop = {x for x, y in extra_post_items}
for key in keys_to_drop:
post_items = [(x, y) for x, y in post_items if x != key]
for key, value in extra_post_items:
post_items.append((key, value))
return post_items | 37 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.clean_submit_controls | (
self, post: MutableMapping[str, Any], submit_name: None | str
) | 610 | 640 | def clean_submit_controls(
self, post: MutableMapping[str, Any], submit_name: None | str
) -> None:
# All this code need only for one reason:
# to not send multiple submit keys in form data
# in real life only this key is submitted whose button
# was pressed
# Build list of submit buttons which have a name
submit_control_names: set[str] = set()
for elem in self.form.inputs:
if (
elem.tag == "input"
and elem.type == "submit"
and elem.get("name") is not None
):
submit_control_names.add(elem.name)
if submit_control_names:
# If name of submit control is not given then
# use the name of first submit control
if submit_name is None or submit_name not in submit_control_names:
submit_name = sorted(submit_control_names)[0]
# FIXME: possibly need to update post
# if new submit_name is not in post
# Form data should contain only one submit control
for name in submit_control_names:
if name != submit_name and name in post:
del post[name] | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L610-L640 | 1 | [
0,
8,
9,
10,
11,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30
] | 64.516129 | [] | 0 | false | 86.167147 | 31 | 11 | 100 | 0 | def clean_submit_controls(
self, post: MutableMapping[str, Any], submit_name: None | str
) -> None:
# All this code need only for one reason:
# to not send multiple submit keys in form data
# in real life only this key is submitted whose button
# was pressed
# Build list of submit buttons which have a name
submit_control_names: set[str] = set()
for elem in self.form.inputs:
if (
elem.tag == "input"
and elem.type == "submit"
and elem.get("name") is not None
):
submit_control_names.add(elem.name)
if submit_control_names:
# If name of submit control is not given then
# use the name of first submit control
if submit_name is None or submit_name not in submit_control_names:
submit_name = sorted(submit_control_names)[0]
# FIXME: possibly need to update post
# if new submit_name is not in post
# Form data should contain only one submit control
for name in submit_control_names:
if name != submit_name and name in post:
del post[name] | 38 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.get_form_request | (
self,
submit_name: None | str = None,
url: None | str = None,
extra_post: None | Mapping[str, Any] | Sequence[tuple[str, Any]] = None,
remove_from_post: None | Sequence[str] = None,
) | return {
"url": action_url,
"method": self.form.method.upper(),
"multipart": "multipart" in self.form.get("enctype", ""),
"fields": post_items,
} | Submit default form.
:param submit_name: name of button which should be "clicked" to
submit form
:param url: explicitly specify form action url
:param extra_post: (dict or list of pairs) additional form data which
will override data automatically extracted from the form.
:param remove_from_post: list of keys to remove from the submitted data
Following input elements are automatically processed:
* input[type="hidden"] - default value
* select: value of last option
* radio - ???
* checkbox - ???
Multipart forms are correctly recognized by grab library. | Submit default form. | 642 | 692 | def get_form_request(
self,
submit_name: None | str = None,
url: None | str = None,
extra_post: None | Mapping[str, Any] | Sequence[tuple[str, Any]] = None,
remove_from_post: None | Sequence[str] = None,
) -> FormRequestParams:
"""Submit default form.
:param submit_name: name of button which should be "clicked" to
submit form
:param url: explicitly specify form action url
:param extra_post: (dict or list of pairs) additional form data which
will override data automatically extracted from the form.
:param remove_from_post: list of keys to remove from the submitted data
Following input elements are automatically processed:
* input[type="hidden"] - default value
* select: value of last option
* radio - ???
* checkbox - ???
Multipart forms are correctly recognized by grab library.
"""
post = self.form_fields()
self.clean_submit_controls(post, submit_name)
assert self.url is not None
action_url = (
urljoin(self.url, url) if url else urljoin(self.url, self.form.action)
)
# Values from `extra_post` should override values in form
# `extra_post` allows multiple value of one key
# Process saved values of file fields
if self.form.method == "POST" and "multipart" in self.form.get("enctype", ""):
for key, obj in self._file_fields.items():
post[key] = obj
post_items: list[tuple[str, Any]] = list(post.items())
del post
if extra_post:
post_items = self.process_extra_post(
post_items, normalize_pairs(extra_post)
)
if remove_from_post:
post_items = [(x, y) for x, y in post_items if x not in remove_from_post]
return {
"url": action_url,
"method": self.form.method.upper(),
"multipart": "multipart" in self.form.get("enctype", ""),
"fields": post_items,
} | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L642-L692 | 1 | [
0,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
37,
38,
39,
42,
43,
44,
45,
46,
47,
48,
49,
50
] | 49.019608 | [
36,
40
] | 3.921569 | false | 86.167147 | 51 | 8 | 96.078431 | 17 | def get_form_request(
self,
submit_name: None | str = None,
url: None | str = None,
extra_post: None | Mapping[str, Any] | Sequence[tuple[str, Any]] = None,
remove_from_post: None | Sequence[str] = None,
) -> FormRequestParams:
post = self.form_fields()
self.clean_submit_controls(post, submit_name)
assert self.url is not None
action_url = (
urljoin(self.url, url) if url else urljoin(self.url, self.form.action)
)
# Values from `extra_post` should override values in form
# `extra_post` allows multiple value of one key
# Process saved values of file fields
if self.form.method == "POST" and "multipart" in self.form.get("enctype", ""):
for key, obj in self._file_fields.items():
post[key] = obj
post_items: list[tuple[str, Any]] = list(post.items())
del post
if extra_post:
post_items = self.process_extra_post(
post_items, normalize_pairs(extra_post)
)
if remove_from_post:
post_items = [(x, y) for x, y in post_items if x not in remove_from_post]
return {
"url": action_url,
"method": self.form.method.upper(),
"multipart": "multipart" in self.form.get("enctype", ""),
"fields": post_items,
} | 39 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.build_fields_to_remove | (
self, fields: Mapping[str, Any], form_inputs: Sequence[HtmlElement]
) | return fields_to_remove | 694 | 717 | def build_fields_to_remove(
self, fields: Mapping[str, Any], form_inputs: Sequence[HtmlElement]
) -> set[str]:
fields_to_remove: set[str] = set()
for elem in form_inputs:
# Ignore elements without name
if not elem.get("name"):
continue
# Do not submit disabled fields
# http://www.w3.org/TR/html4/interact/forms.html#h-17.12
if elem.get("disabled") and elem.name in fields:
fields_to_remove.add(elem.name)
elif getattr(elem, "type", None) == "checkbox":
if (
not elem.checked
and elem.name is not None
and elem.name in fields
and fields[elem.name] is None
):
fields_to_remove.add(elem.name)
elif elem.name in fields_to_remove:
# WHAT THE FUCK DOES THAT MEAN?
fields_to_remove.remove(elem.name)
return fields_to_remove | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L694-L717 | 1 | [
0,
3,
4,
5,
6,
9,
10,
11,
12,
13,
20,
21,
22,
23
] | 58.333333 | [
7,
19
] | 8.333333 | false | 86.167147 | 24 | 11 | 91.666667 | 0 | def build_fields_to_remove(
self, fields: Mapping[str, Any], form_inputs: Sequence[HtmlElement]
) -> set[str]:
fields_to_remove: set[str] = set()
for elem in form_inputs:
# Ignore elements without name
if not elem.get("name"):
continue
# Do not submit disabled fields
# http://www.w3.org/TR/html4/interact/forms.html#h-17.12
if elem.get("disabled") and elem.name in fields:
fields_to_remove.add(elem.name)
elif getattr(elem, "type", None) == "checkbox":
if (
not elem.checked
and elem.name is not None
and elem.name in fields
and fields[elem.name] is None
):
fields_to_remove.add(elem.name)
elif elem.name in fields_to_remove:
# WHAT THE FUCK DOES THAT MEAN?
fields_to_remove.remove(elem.name)
return fields_to_remove | 40 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.process_form_fields | (self, fields: MutableMapping[str, Any]) | 719 | 734 | def process_form_fields(self, fields: MutableMapping[str, Any]) -> None:
for key, val in list(fields.items()):
if isinstance(val, CheckboxValues):
if not val:
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val)
if isinstance(val, MultipleSelectOptions):
if not val:
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L719-L734 | 1 | [
0,
1,
2,
3,
4,
5,
6,
8,
9,
10,
11,
12,
13,
15
] | 87.5 | [] | 0 | false | 86.167147 | 16 | 8 | 100 | 0 | def process_form_fields(self, fields: MutableMapping[str, Any]) -> None:
for key, val in list(fields.items()):
if isinstance(val, CheckboxValues):
if not val:
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val)
if isinstance(val, MultipleSelectOptions):
if not val:
del fields[key]
elif len(val) == 1:
fields[key] = val.pop()
else:
fields[key] = list(val) | 41 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.form_fields | (self) | return fields | Return fields of default form.
Fill some fields with reasonable values. | Return fields of default form. | 736 | 755 | def form_fields(self) -> MutableMapping[str, HtmlElement]:
"""Return fields of default form.
Fill some fields with reasonable values.
"""
fields = dict(self.form.fields)
self.process_form_fields(fields)
for elem in self.form.inputs:
if (
elem.tag == "select"
and elem.name in fields
and fields[elem.name] is None
and elem.value_options
):
fields[elem.name] = elem.value_options[0]
elif (getattr(elem, "type", None) == "radio") and fields[elem.name] is None:
fields[elem.name] = elem.get("value")
for name in self.build_fields_to_remove(fields, self.form.inputs):
del fields[name]
return fields | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L736-L755 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
15,
16,
17,
18,
19
] | 95 | [
14
] | 5 | false | 86.167147 | 20 | 9 | 95 | 3 | def form_fields(self) -> MutableMapping[str, HtmlElement]:
fields = dict(self.form.fields)
self.process_form_fields(fields)
for elem in self.form.inputs:
if (
elem.tag == "select"
and elem.name in fields
and fields[elem.name] is None
and elem.value_options
):
fields[elem.name] = elem.value_options[0]
elif (getattr(elem, "type", None) == "radio") and fields[elem.name] is None:
fields[elem.name] = elem.get("value")
for name in self.build_fields_to_remove(fields, self.form.inputs):
del fields[name]
return fields | 42 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/document.py | Document.choose_form_by_element | (self, xpath: str) | 757 | 764 | def choose_form_by_element(self, xpath: str) -> None:
elem = self.select(xpath).node()
while elem is not None:
if elem.tag == "form":
self._lxml_form = elem
return
elem = elem.getparent()
self._lxml_form = None | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/document.py#L757-L764 | 1 | [
0,
1,
2,
3,
4,
5,
6
] | 87.5 | [
7
] | 12.5 | false | 86.167147 | 8 | 3 | 87.5 | 0 | def choose_form_by_element(self, xpath: str) -> None:
elem = self.select(xpath).node()
while elem is not None:
if elem.tag == "form":
self._lxml_form = elem
return
elem = elem.getparent()
self._lxml_form = None | 43 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/client.py | request | (
url: None | str | HttpRequest = None,
client: None | HttpClient | type[HttpClient] = None,
**request_kwargs: Any,
) | return client.request(url, **request_kwargs) | 38 | 44 | def request(
url: None | str | HttpRequest = None,
client: None | HttpClient | type[HttpClient] = None,
**request_kwargs: Any,
) -> Document:
client = resolve_entity(HttpClient, client, default=HttpClient)
return client.request(url, **request_kwargs) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/client.py#L38-L44 | 1 | [
0,
5,
6
] | 42.857143 | [] | 0 | false | 100 | 7 | 1 | 100 | 0 | def request(
url: None | str | HttpRequest = None,
client: None | HttpClient | type[HttpClient] = None,
**request_kwargs: Any,
) -> Document:
client = resolve_entity(HttpClient, client, default=HttpClient)
return client.request(url, **request_kwargs) | 44 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/client.py | HttpClient.request | (
self, req: None | str | HttpRequest = None, **request_kwargs: Any
) | return super().request(req, **request_kwargs) | 22 | 29 | def request(
self, req: None | str | HttpRequest = None, **request_kwargs: Any
) -> Document:
if req is not None and not isinstance(req, HttpRequest):
assert isinstance(req, str)
request_kwargs["url"] = req
req = None
return super().request(req, **request_kwargs) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/client.py#L22-L29 | 1 | [
0,
3,
4,
5,
6,
7
] | 75 | [] | 0 | false | 100 | 8 | 4 | 100 | 0 | def request(
self, req: None | str | HttpRequest = None, **request_kwargs: Any
) -> Document:
if req is not None and not isinstance(req, HttpRequest):
assert isinstance(req, str)
request_kwargs["url"] = req
req = None
return super().request(req, **request_kwargs) | 45 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/client.py | HttpClient.process_request_result | (self, req: HttpRequest) | return doc | Process result of real request performed via transport extension. | Process result of real request performed via transport extension. | 31 | 35 | def process_request_result(self, req: HttpRequest) -> Document:
"""Process result of real request performed via transport extension."""
doc = self.transport.prepare_response(req, document_class=self.document_class)
all(func(req, doc) for func in self.ext_handlers["response:post"])
return doc | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/client.py#L31-L35 | 1 | [
0,
1,
2,
3,
4
] | 100 | [] | 0 | true | 100 | 5 | 1 | 100 | 1 | def process_request_result(self, req: HttpRequest) -> Document:
doc = self.transport.prepare_response(req, document_class=self.document_class)
all(func(req, doc) for func in self.ext_handlers["response:post"])
return doc | 46 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/errors.py | OriginalExceptionGrabError.__init__ | (self, *args: Any, **kwargs: Any) | 33 | 38 | def __init__(self, *args: Any, **kwargs: Any) -> None:
if len(args) > 1:
self.original_exc = args[1]
else:
self.original_exc = None
super().__init__(*args, **kwargs) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/errors.py#L33-L38 | 1 | [
0,
1,
2,
5
] | 66.666667 | [
4
] | 16.666667 | false | 92.592593 | 6 | 2 | 83.333333 | 0 | def __init__(self, *args: Any, **kwargs: Any) -> None:
if len(args) > 1:
self.original_exc = args[1]
else:
self.original_exc = None
super().__init__(*args, **kwargs) | 47 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.__init__ | (self) | 33 | 41 | def __init__(self) -> None:
super().__init__()
self.pool = self.build_pool()
# WTF: logging is configured here?
logger = logging.getLogger("urllib3.connectionpool")
logger.setLevel(logging.WARNING)
self._response: None | Urllib3HTTPResponse = None
self._connect_time: None | float = None
self.reset() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L33-L41 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 | [] | 0 | true | 95.2 | 9 | 1 | 100 | 0 | def __init__(self) -> None:
super().__init__()
self.pool = self.build_pool()
# WTF: logging is configured here?
logger = logging.getLogger("urllib3.connectionpool")
logger.setLevel(logging.WARNING)
self._response: None | Urllib3HTTPResponse = None
self._connect_time: None | float = None
self.reset() | 48 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.__getstate__ | (self) | return state | 43 | 51 | def __getstate__(self) -> dict[str, Any]:
state = self.__dict__.copy()
# PoolManager could not be pickled
del state["pool"]
# urllib3.HTTPReponse is also not good for pickling
state["_response"] = None
# let's reset request object too
state["_request"] = None
return state | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L43-L51 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 | [] | 0 | true | 95.2 | 9 | 1 | 100 | 0 | def __getstate__(self) -> dict[str, Any]:
state = self.__dict__.copy()
# PoolManager could not be pickled
del state["pool"]
# urllib3.HTTPReponse is also not good for pickling
state["_response"] = None
# let's reset request object too
state["_request"] = None
return state | 49 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.__setstate__ | (self, state: Mapping[str, Any]) | 53 | 56 | def __setstate__(self, state: Mapping[str, Any]) -> None:
for slot, value in state.items():
setattr(self, slot, value)
self.pool = self.build_pool() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L53-L56 | 1 | [
0,
1,
2,
3
] | 100 | [] | 0 | true | 95.2 | 4 | 2 | 100 | 0 | def __setstate__(self, state: Mapping[str, Any]) -> None:
for slot, value in state.items():
setattr(self, slot, value)
self.pool = self.build_pool() | 50 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.build_pool | (self) | return PoolManager(10, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()) | 58 | 60 | def build_pool(self) -> PoolManager:
# http://urllib3.readthedocs.io/en/latest/user-guide.html#certificate-verification
return PoolManager(10, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L58-L60 | 1 | [
0,
1,
2
] | 100 | [] | 0 | true | 95.2 | 3 | 1 | 100 | 0 | def build_pool(self) -> PoolManager:
# http://urllib3.readthedocs.io/en/latest/user-guide.html#certificate-verification
return PoolManager(10, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()) | 51 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.reset | (self) | 62 | 64 | def reset(self) -> None:
self._response = None
self._connect_time = None | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L62-L64 | 1 | [
0,
1,
2
] | 100 | [] | 0 | true | 95.2 | 3 | 1 | 100 | 0 | def reset(self) -> None:
self._response = None
self._connect_time = None | 52 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.wrap_transport_error | (self) | 67 | 79 | def wrap_transport_error(self) -> Generator[None, None, None]:
try:
yield
except exceptions.ReadTimeoutError as ex:
raise GrabTimeoutError("ReadTimeoutError", ex) from ex
except exceptions.ConnectTimeoutError as ex:
raise GrabConnectionError("ConnectTimeoutError", ex) from ex
except exceptions.ProtocolError as ex:
raise GrabConnectionError("ProtocolError", ex) from ex
except exceptions.SSLError as ex:
raise GrabConnectionError("SSLError", ex) from ex
except ssl.SSLError as ex:
raise GrabConnectionError("SSLError", ex) from ex | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L67-L79 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
9,
11
] | 76.923077 | [
8,
10,
12
] | 23.076923 | false | 95.2 | 13 | 6 | 76.923077 | 0 | def wrap_transport_error(self) -> Generator[None, None, None]:
try:
yield
except exceptions.ReadTimeoutError as ex:
raise GrabTimeoutError("ReadTimeoutError", ex) from ex
except exceptions.ConnectTimeoutError as ex:
raise GrabConnectionError("ConnectTimeoutError", ex) from ex
except exceptions.ProtocolError as ex:
raise GrabConnectionError("ProtocolError", ex) from ex
except exceptions.SSLError as ex:
raise GrabConnectionError("SSLError", ex) from ex
except ssl.SSLError as ex:
raise GrabConnectionError("SSLError", ex) from ex | 53 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.select_pool_for_request | (
self, req: HttpRequest
) | return self.pool | 81 | 102 | def select_pool_for_request(
self, req: HttpRequest
) -> PoolManager | ProxyManager | SOCKSProxyManager:
if req.proxy:
if req.proxy_userpwd:
headers = make_headers(
proxy_basic_auth=req.proxy_userpwd
) # type: ignore # FIXME
else:
headers = None
proxy_url = "%s://%s" % (req.proxy_type, req.proxy)
if req.proxy_type == "socks5":
return SOCKSProxyManager(
proxy_url, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()
) # , proxy_headers=headers)
return ProxyManager(
proxy_url,
proxy_headers=headers,
cert_reqs="CERT_REQUIRED",
ca_certs=certifi.where(),
)
return self.pool | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L81-L102 | 1 | [
0,
3,
4,
9,
10,
11,
15,
21
] | 36.363636 | [
5,
12
] | 9.090909 | false | 95.2 | 22 | 4 | 90.909091 | 0 | def select_pool_for_request(
self, req: HttpRequest
) -> PoolManager | ProxyManager | SOCKSProxyManager:
if req.proxy:
if req.proxy_userpwd:
headers = make_headers(
proxy_basic_auth=req.proxy_userpwd
) # type: ignore # FIXME
else:
headers = None
proxy_url = "%s://%s" % (req.proxy_type, req.proxy)
if req.proxy_type == "socks5":
return SOCKSProxyManager(
proxy_url, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()
) # , proxy_headers=headers)
return ProxyManager(
proxy_url,
proxy_headers=headers,
cert_reqs="CERT_REQUIRED",
ca_certs=certifi.where(),
)
return self.pool | 54 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.log_request | (self, req: HttpRequest) | Log request details via logging system. | Log request details via logging system. | 104 | 113 | def log_request(self, req: HttpRequest) -> None:
"""Log request details via logging system."""
proxy_info = (
" via proxy {}://{}{}".format(
req.proxy_type, req.proxy, " with auth" if req.proxy_userpwd else ""
)
if req.proxy
else ""
)
LOG.debug("%s %s%s", req.method or "GET", req.url, proxy_info) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L104-L113 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 | [] | 0 | true | 95.2 | 10 | 2 | 100 | 1 | def log_request(self, req: HttpRequest) -> None:
proxy_info = (
" via proxy {}://{}{}".format(
req.proxy_type, req.proxy, " with auth" if req.proxy_userpwd else ""
)
if req.proxy
else ""
)
LOG.debug("%s %s%s", req.method or "GET", req.url, proxy_info) | 55 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.request | (self, req: HttpRequest) | 115 | 153 | def request(self, req: HttpRequest) -> None:
pool: PoolManager | SOCKSProxyManager | ProxyManager = (
self.select_pool_for_request(req)
)
self.log_request(req)
with self.wrap_transport_error():
# Retries can be disabled by passing False:
# http://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#module-urllib3.util.retry
# Do not use False because of warning:
# Converted retries value: False -> Retry(total=False,
# connect=None, read=None, redirect=0, status=None)
retry = Retry(
total=False,
connect=False,
read=False,
redirect=0,
status=None,
)
# The read timeout is not total response time timeout
# It is the timeout on read of next data chunk from the server
# Total response timeout is handled by Grab
timeout = Timeout(connect=req.timeout.connect, read=req.timeout.read)
req_data = req.compile_request_data()
try:
start_time = time.time()
res = pool.urlopen( # type: ignore # FIXME
req_data["method"],
req_data["url"],
body=req_data["body"],
timeout=timeout,
retries=retry,
headers=req_data["headers"],
preload_content=False,
)
self._connect_time = time.time() - start_time
except LocationParseError as ex:
raise GrabInvalidResponse(str(ex), ex) from ex
self._response = res | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L115-L153 | 1 | [
0,
1,
4,
5,
6,
7,
8,
9,
10,
11,
20,
21,
22,
23,
24,
25,
34,
35,
36,
37,
38
] | 53.846154 | [] | 0 | false | 95.2 | 39 | 3 | 100 | 0 | def request(self, req: HttpRequest) -> None:
pool: PoolManager | SOCKSProxyManager | ProxyManager = (
self.select_pool_for_request(req)
)
self.log_request(req)
with self.wrap_transport_error():
# Retries can be disabled by passing False:
# http://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#module-urllib3.util.retry
# Do not use False because of warning:
# Converted retries value: False -> Retry(total=False,
# connect=None, read=None, redirect=0, status=None)
retry = Retry(
total=False,
connect=False,
read=False,
redirect=0,
status=None,
)
# The read timeout is not total response time timeout
# It is the timeout on read of next data chunk from the server
# Total response timeout is handled by Grab
timeout = Timeout(connect=req.timeout.connect, read=req.timeout.read)
req_data = req.compile_request_data()
try:
start_time = time.time()
res = pool.urlopen( # type: ignore # FIXME
req_data["method"],
req_data["url"],
body=req_data["body"],
timeout=timeout,
retries=retry,
headers=req_data["headers"],
preload_content=False,
)
self._connect_time = time.time() - start_time
except LocationParseError as ex:
raise GrabInvalidResponse(str(ex), ex) from ex
self._response = res | 56 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.read_with_timeout | (self, req: HttpRequest) | return b"".join(chunks) | 155 | 175 | def read_with_timeout(self, req: HttpRequest) -> bytes:
assert self._connect_time is not None
assert self._response is not None
chunks = []
chunk_size = 10000
bytes_read = 0
op_started = time.time()
while True:
chunk = self._response.read(chunk_size)
if chunk:
bytes_read += len(chunk)
chunks.append(chunk)
else:
break
if (
req.timeout.total
and (time.time() - (op_started + self._connect_time))
> req.timeout.total
):
raise GrabTimeoutError
return b"".join(chunks) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L155-L175 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
14,
20
] | 71.428571 | [
19
] | 4.761905 | false | 95.2 | 21 | 7 | 95.238095 | 0 | def read_with_timeout(self, req: HttpRequest) -> bytes:
assert self._connect_time is not None
assert self._response is not None
chunks = []
chunk_size = 10000
bytes_read = 0
op_started = time.time()
while True:
chunk = self._response.read(chunk_size)
if chunk:
bytes_read += len(chunk)
chunks.append(chunk)
else:
break
if (
req.timeout.total
and (time.time() - (op_started + self._connect_time))
> req.timeout.total
):
raise GrabTimeoutError
return b"".join(chunks) | 57 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.get_response_header_items | (self) | return headers.items() | Return current response headers as items.
This funciton is required to isolated smalles part of untyped code
and hide it from mypy | Return current response headers as items. | 177 | 184 | def get_response_header_items(self) -> list[tuple[str, Any]]:
"""Return current response headers as items.
This funciton is required to isolated smalles part of untyped code
and hide it from mypy
"""
headers = cast(HTTPResponse, self._response).headers
return headers.items() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L177-L184 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7
] | 100 | [] | 0 | true | 95.2 | 8 | 1 | 100 | 4 | def get_response_header_items(self) -> list[tuple[str, Any]]:
headers = cast(HTTPResponse, self._response).headers
return headers.items() | 58 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/transport.py | Urllib3Transport.prepare_response | (
self, req: HttpRequest, *, document_class: type[Document] = Document
) | Prepare response, duh.
This methed is called after network request is completed
hence the "self._request" is not None.
Good to know: on python3 urllib3 headers are converted to str type
using latin encoding. | Prepare response, duh. | 186 | 233 | def prepare_response(
self, req: HttpRequest, *, document_class: type[Document] = Document
) -> Document:
"""Prepare response, duh.
This methed is called after network request is completed
hence the "self._request" is not None.
Good to know: on python3 urllib3 headers are converted to str type
using latin encoding.
"""
assert self._response is not None
try:
head_str = ""
# FIXME: head must include first line like "GET / HTTP/1.1"
for key, val in self.get_response_header_items():
# WTF: is going here?
new_key = key.encode("latin").decode("utf-8", errors="ignore")
new_val = val.encode("latin").decode("utf-8", errors="ignore")
head_str += "%s: %s\r\n" % (new_key, new_val)
head_str += "\r\n"
head = head_str.encode("utf-8")
body = self.read_with_timeout(req)
hdr = email.message.Message()
for key, val in self.get_response_header_items():
# WTF: is happening here?
new_key = key.encode("latin").decode("utf-8", errors="ignore")
new_val = val.encode("latin").decode("utf-8", errors="ignore")
hdr[new_key] = new_val
return document_class(
document_type=(
req.document_type if req.document_type is not None else "html"
),
head=head,
body=body,
code=self._response.status,
url=(self._response.get_redirect_location() or req.url),
headers=hdr,
encoding=req.encoding,
cookies=extract_response_cookies(
req.url, req.headers, self._response.headers
),
)
finally:
self._response.release_conn() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/transport.py#L186-L233 | 1 | [
0,
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
] | 81.25 | [] | 0 | false | 95.2 | 48 | 5 | 100 | 7 | def prepare_response(
self, req: HttpRequest, *, document_class: type[Document] = Document
) -> Document:
assert self._response is not None
try:
head_str = ""
# FIXME: head must include first line like "GET / HTTP/1.1"
for key, val in self.get_response_header_items():
# WTF: is going here?
new_key = key.encode("latin").decode("utf-8", errors="ignore")
new_val = val.encode("latin").decode("utf-8", errors="ignore")
head_str += "%s: %s\r\n" % (new_key, new_val)
head_str += "\r\n"
head = head_str.encode("utf-8")
body = self.read_with_timeout(req)
hdr = email.message.Message()
for key, val in self.get_response_header_items():
# WTF: is happening here?
new_key = key.encode("latin").decode("utf-8", errors="ignore")
new_val = val.encode("latin").decode("utf-8", errors="ignore")
hdr[new_key] = new_val
return document_class(
document_type=(
req.document_type if req.document_type is not None else "html"
),
head=head,
body=body,
code=self._response.status,
url=(self._response.get_redirect_location() or req.url),
headers=hdr,
encoding=req.encoding,
cookies=extract_response_cookies(
req.url, req.headers, self._response.headers
),
)
finally:
self._response.release_conn() | 59 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/request.py | HttpRequest.__init__ | ( # pylint: disable=too-many-arguments,too-many-locals
self,
url: str,
*,
method: None | str = None,
headers: None | MutableMapping[str, Any] = None,
timeout: None | int | Timeout = None,
cookies: None | dict[str, Any] = None,
encoding: None | str = None,
# proxy
proxy_type: None | str = None,
proxy: None | str = None,
proxy_userpwd: None | str = None,
# payload
fields: Any = None,
body: None | bytes = None,
multipart: None | bool = None,
document_type: None | str = None,
redirect_limit: None | int = None,
process_redirect: None | bool = None,
meta: None | Mapping[str, Any] = None,
) | 48 | 108 | def __init__( # pylint: disable=too-many-arguments,too-many-locals
self,
url: str,
*,
method: None | str = None,
headers: None | MutableMapping[str, Any] = None,
timeout: None | int | Timeout = None,
cookies: None | dict[str, Any] = None,
encoding: None | str = None,
# proxy
proxy_type: None | str = None,
proxy: None | str = None,
proxy_userpwd: None | str = None,
# payload
fields: Any = None,
body: None | bytes = None,
multipart: None | bool = None,
document_type: None | str = None,
redirect_limit: None | int = None,
process_redirect: None | bool = None,
meta: None | Mapping[str, Any] = None,
) -> None:
self.process_redirect = (
process_redirect if process_redirect else DEFAULT_PROCESS_REDIRECT
)
self.redirect_limit = (
redirect_limit if redirect_limit is not None else DEFAULT_REDIRECT_LIMIT
)
self.encoding = encoding
if url is None:
raise ValueError("URL must be set")
self.url = url
if method is None:
method = DEFAULT_METHOD
if method not in {
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"HEAD",
"CONNECT",
"OPTIONS",
"TRACE",
}:
raise ValueError("Method '{}' is not valid".format(method))
self.method = method
self.cookies = cookies or {}
self.headers = headers or {}
self.timeout: Timeout = self._process_timeout_param(timeout)
# proxy
self.proxy = proxy
self.proxy_userpwd = proxy_userpwd
self.proxy_type = proxy_type
# payload
self.body = body
self.fields = fields
self.multipart = multipart if multipart is not None else True
self.document_type = document_type
self.meta = meta or {}
self.cookie_header: None | str = None | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/request.py#L48-L108 | 1 | [
0,
22,
25,
28,
29,
31,
32,
33,
34,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60
] | 39.344262 | [
30,
45
] | 3.278689 | false | 92 | 61 | 7 | 96.721311 | 0 | def __init__( # pylint: disable=too-many-arguments,too-many-locals
self,
url: str,
*,
method: None | str = None,
headers: None | MutableMapping[str, Any] = None,
timeout: None | int | Timeout = None,
cookies: None | dict[str, Any] = None,
encoding: None | str = None,
# proxy
proxy_type: None | str = None,
proxy: None | str = None,
proxy_userpwd: None | str = None,
# payload
fields: Any = None,
body: None | bytes = None,
multipart: None | bool = None,
document_type: None | str = None,
redirect_limit: None | int = None,
process_redirect: None | bool = None,
meta: None | Mapping[str, Any] = None,
) -> None:
self.process_redirect = (
process_redirect if process_redirect else DEFAULT_PROCESS_REDIRECT
)
self.redirect_limit = (
redirect_limit if redirect_limit is not None else DEFAULT_REDIRECT_LIMIT
)
self.encoding = encoding
if url is None:
raise ValueError("URL must be set")
self.url = url
if method is None:
method = DEFAULT_METHOD
if method not in {
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"HEAD",
"CONNECT",
"OPTIONS",
"TRACE",
}:
raise ValueError("Method '{}' is not valid".format(method))
self.method = method
self.cookies = cookies or {}
self.headers = headers or {}
self.timeout: Timeout = self._process_timeout_param(timeout)
# proxy
self.proxy = proxy
self.proxy_userpwd = proxy_userpwd
self.proxy_type = proxy_type
# payload
self.body = body
self.fields = fields
self.multipart = multipart if multipart is not None else True
self.document_type = document_type
self.meta = meta or {}
self.cookie_header: None | str = None | 60 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/request.py | HttpRequest.get_full_url | (self) | return self.url | 110 | 111 | def get_full_url(self) -> str:
return self.url | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/request.py#L110-L111 | 1 | [
0
] | 50 | [
1
] | 50 | false | 92 | 2 | 1 | 50 | 0 | def get_full_url(self) -> str:
return self.url | 61 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/request.py | HttpRequest._process_timeout_param | (self, value: None | float | Timeout) | return Timeout(total=float(value)) | 113 | 118 | def _process_timeout_param(self, value: None | float | Timeout) -> Timeout:
if isinstance(value, Timeout):
return value
if value is None:
return Timeout()
return Timeout(total=float(value)) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/request.py#L113-L118 | 1 | [
0,
1,
2,
3,
4,
5
] | 100 | [] | 0 | true | 92 | 6 | 3 | 100 | 0 | def _process_timeout_param(self, value: None | float | Timeout) -> Timeout:
if isinstance(value, Timeout):
return value
if value is None:
return Timeout()
return Timeout(total=float(value)) | 62 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/request.py | HttpRequest.compile_request_data | ( # noqa: CCR001
self,
) | return {
"method": self.method,
"url": req_url,
"headers": req_hdr,
"body": req_body,
} | 120 | 163 | def compile_request_data( # noqa: CCR001
self,
) -> CompiledRequestData:
req_url = self.url
req_hdr = copy(self.headers)
req_body = None
if self.method in URL_DATA_METHODS:
if self.body:
raise ValueError(
"Request.body could not be used with {} method".format(self.method)
)
if self.fields:
req_url = req_url + "?" + urlencode(self.fields)
else:
if self.body:
req_body = self.body
if self.fields:
if self.body:
raise ValueError(
"Request.body and Request.fields could not be set both"
)
if self.multipart:
req_body, content_type = encode_multipart_formdata( # type: ignore
self.fields
)
req_body = cast(bytes, req_body)
else:
req_body, content_type = (
urlencode(self.fields).encode(),
"application/x-www-form-urlencoded",
)
req_hdr = merge_with_dict(
req_hdr,
{"Content-Type": content_type, "Content-Length": len(req_body)},
replace=True,
)
if self.cookie_header:
req_hdr["Cookie"] = self.cookie_header
return {
"method": self.method,
"url": req_url,
"headers": req_hdr,
"body": req_body,
} | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/request.py#L120-L163 | 1 | [
0,
3,
4,
5,
6,
7,
11,
14,
15,
16,
17,
21,
22,
25,
27,
31,
36,
37,
38
] | 43.181818 | [
8,
12,
18
] | 6.818182 | false | 92 | 44 | 9 | 93.181818 | 0 | def compile_request_data( # noqa: CCR001
self,
) -> CompiledRequestData:
req_url = self.url
req_hdr = copy(self.headers)
req_body = None
if self.method in URL_DATA_METHODS:
if self.body:
raise ValueError(
"Request.body could not be used with {} method".format(self.method)
)
if self.fields:
req_url = req_url + "?" + urlencode(self.fields)
else:
if self.body:
req_body = self.body
if self.fields:
if self.body:
raise ValueError(
"Request.body and Request.fields could not be set both"
)
if self.multipart:
req_body, content_type = encode_multipart_formdata( # type: ignore
self.fields
)
req_body = cast(bytes, req_body)
else:
req_body, content_type = (
urlencode(self.fields).encode(),
"application/x-www-form-urlencoded",
)
req_hdr = merge_with_dict(
req_hdr,
{"Content-Type": content_type, "Content-Length": len(req_body)},
replace=True,
)
if self.cookie_header:
req_hdr["Cookie"] = self.cookie_header
return {
"method": self.method,
"url": req_url,
"headers": req_hdr,
"body": req_body,
} | 63 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseRequest.__repr__ | (self) | return "{}({})".format(
self.__class__.__name__,
", ".join("{}={!r}".format(*x) for x in self.__dict__.items()),
) | 21 | 25 | def __repr__(self) -> str:
return "{}({})".format(
self.__class__.__name__,
", ".join("{}={!r}".format(*x) for x in self.__dict__.items()),
) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L21-L25 | 1 | [
0
] | 20 | [
1
] | 20 | false | 92.307692 | 5 | 1 | 80 | 0 | def __repr__(self) -> str:
return "{}({})".format(
self.__class__.__name__,
", ".join("{}={!r}".format(*x) for x in self.__dict__.items()),
) | 64 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseRequest.create_from_mapping | (
cls: type[RequestT], mapping: Mapping[str, Any]
) | return cls(**mapping) | 28 | 38 | def create_from_mapping(
cls: type[RequestT], mapping: Mapping[str, Any]
) -> RequestT:
for key in mapping:
if key not in cls.init_keys:
raise TypeError(
"Constructor of {} does not accept {} keyword parameter".format(
cls.__name__, key
)
)
return cls(**mapping) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L28-L38 | 1 | [
0,
3,
4,
10
] | 36.363636 | [
5
] | 9.090909 | false | 92.307692 | 11 | 3 | 90.909091 | 0 | def create_from_mapping(
cls: type[RequestT], mapping: Mapping[str, Any]
) -> RequestT:
for key in mapping:
if key not in cls.init_keys:
raise TypeError(
"Constructor of {} does not accept {} keyword parameter".format(
cls.__name__, key
)
)
return cls(**mapping) | 65 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseExtension.__set_name__ | (self, owner: BaseClient[RequestT, ResponseT], attr: str) | 49 | 54 | def __set_name__(self, owner: BaseClient[RequestT, ResponseT], attr: str) -> None:
owner.extensions[attr] = {
"instance": self,
}
for point_name, func in self.ext_handlers.items():
owner.ext_handlers[point_name].append(func) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L49-L54 | 1 | [
0,
1,
4,
5
] | 66.666667 | [] | 0 | false | 92.307692 | 6 | 2 | 100 | 0 | def __set_name__(self, owner: BaseClient[RequestT, ResponseT], attr: str) -> None:
owner.extensions[attr] = {
"instance": self,
}
for point_name, func in self.ext_handlers.items():
owner.ext_handlers[point_name].append(func) | 66 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseExtension.reset | (self) | 57 | 58 | def reset(self) -> None:
... | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L57-L58 | 1 | [
0
] | 50 | [
1
] | 50 | false | 92.307692 | 2 | 1 | 50 | 0 | def reset(self) -> None:
... | 67 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | Retry.__init__ | (self) | 62 | 63 | def __init__(self) -> None:
self.state: MutableMapping[str, int] = {} | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L62-L63 | 1 | [
0,
1
] | 100 | [] | 0 | true | 92.307692 | 2 | 1 | 100 | 0 | def __init__(self) -> None:
self.state: MutableMapping[str, int] = {} | 68 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseClient.request_class | (self) | 72 | 73 | def request_class(self) -> type[RequestT]:
... | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L72-L73 | 1 | [
0
] | 50 | [
1
] | 50 | false | 92.307692 | 2 | 1 | 50 | 0 | def request_class(self) -> type[RequestT]:
... | 69 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseClient.default_transport_class | (self) | 77 | 78 | def default_transport_class(self) -> type[BaseTransport[RequestT, ResponseT]]:
... | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L77-L78 | 1 | [
0
] | 50 | [
1
] | 50 | false | 92.307692 | 2 | 1 | 50 | 0 | def default_transport_class(self) -> type[BaseTransport[RequestT, ResponseT]]:
... | 70 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseClient.__init__ | (
self,
transport: None
| BaseTransport[RequestT, ResponseT]
| type[BaseTransport[RequestT, ResponseT]] = None,
) | 89 | 99 | def __init__(
self,
transport: None
| BaseTransport[RequestT, ResponseT]
| type[BaseTransport[RequestT, ResponseT]] = None,
):
self.transport = self.default_transport_class.resolve_entity(
transport, self.default_transport_class
)
for item in self.extensions.values():
item["instance"].reset() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L89-L99 | 1 | [
0,
6,
9,
10
] | 36.363636 | [] | 0 | false | 92.307692 | 11 | 2 | 100 | 0 | def __init__(
self,
transport: None
| BaseTransport[RequestT, ResponseT]
| type[BaseTransport[RequestT, ResponseT]] = None,
):
self.transport = self.default_transport_class.resolve_entity(
transport, self.default_transport_class
)
for item in self.extensions.values():
item["instance"].reset() | 71 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseClient.process_request_result | (self, req: RequestT) | 102 | 103 | def process_request_result(self, req: RequestT) -> ResponseT:
... | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L102-L103 | 1 | [
0
] | 50 | [
1
] | 50 | false | 92.307692 | 2 | 1 | 50 | 0 | def process_request_result(self, req: RequestT) -> ResponseT:
... | 72 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseClient.request | (self, req: None | RequestT = None, **request_kwargs: Any) | 105 | 125 | def request(self, req: None | RequestT = None, **request_kwargs: Any) -> ResponseT:
if req is None:
req = self.request_class.create_from_mapping(request_kwargs)
retry = Retry()
all(x(retry) for x in self.ext_handlers["init-retry"])
while True:
all(func(req) for func in self.ext_handlers["request:pre"])
self.transport.reset()
self.transport.request(req)
with self.transport.wrap_transport_error():
doc = self.process_request_result(req)
if any(
(
(item := func(retry, req, doc)) != (None, None)
for func in self.ext_handlers["retry"]
)
):
# pylint: disable=deprecated-typing-alias
retry, req = cast(typing.Tuple[Retry, RequestT], item)
continue
return doc | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L105-L125 | 1 | [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
17,
18,
19,
20
] | 76.190476 | [] | 0 | false | 92.307692 | 21 | 5 | 100 | 0 | def request(self, req: None | RequestT = None, **request_kwargs: Any) -> ResponseT:
if req is None:
req = self.request_class.create_from_mapping(request_kwargs)
retry = Retry()
all(x(retry) for x in self.ext_handlers["init-retry"])
while True:
all(func(req) for func in self.ext_handlers["request:pre"])
self.transport.reset()
self.transport.request(req)
with self.transport.wrap_transport_error():
doc = self.process_request_result(req)
if any(
(
(item := func(retry, req, doc)) != (None, None)
for func in self.ext_handlers["retry"]
)
):
# pylint: disable=deprecated-typing-alias
retry, req = cast(typing.Tuple[Retry, RequestT], item)
continue
return doc | 73 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseClient.clone | (self: T) | return deepcopy(self) | 127 | 128 | def clone(self: T) -> T:
return deepcopy(self) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L127-L128 | 1 | [
0,
1
] | 100 | [] | 0 | true | 92.307692 | 2 | 1 | 100 | 0 | def clone(self: T) -> T:
return deepcopy(self) | 74 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseTransport.reset | (self) | 135 | 136 | def reset(self) -> None: # pragma: no cover
raise NotImplementedError | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L135-L136 | 1 | [] | 0 | [] | 0 | false | 92.307692 | 2 | 1 | 100 | 0 | def reset(self) -> None: # pragma: no cover
raise NotImplementedError | 75 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseTransport.prepare_response | (
self, req: RequestT, *, document_class: type[ResponseT]
) | 139 | 142 | def prepare_response(
self, req: RequestT, *, document_class: type[ResponseT]
) -> ResponseT: # pragma: no cover
raise NotImplementedError | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L139-L142 | 1 | [] | 0 | [] | 0 | false | 92.307692 | 4 | 1 | 100 | 0 | def prepare_response(
self, req: RequestT, *, document_class: type[ResponseT]
) -> ResponseT: # pragma: no cover
raise NotImplementedError | 76 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseTransport.wrap_transport_error | (self) | 146 | 147 | def wrap_transport_error(self) -> Generator[None, None, None]: # pragma: no cover
raise NotImplementedError | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L146-L147 | 1 | [] | 0 | [] | 0 | false | 92.307692 | 2 | 1 | 100 | 0 | def wrap_transport_error(self) -> Generator[None, None, None]: # pragma: no cover
raise NotImplementedError | 77 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseTransport.request | (self, req: RequestT) | 150 | 151 | def request(self, req: RequestT) -> None: # pragma: no cover
raise NotImplementedError | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L150-L151 | 1 | [] | 0 | [] | 0 | false | 92.307692 | 2 | 1 | 100 | 0 | def request(self, req: RequestT) -> None: # pragma: no cover
raise NotImplementedError | 78 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/base.py | BaseTransport.resolve_entity | (
cls,
entity: None
| BaseTransport[RequestT, ResponseT]
| type[BaseTransport[RequestT, ResponseT]],
default: type[BaseTransport[RequestT, ResponseT]],
) | return entity() | 154 | 170 | def resolve_entity(
cls,
entity: None
| BaseTransport[RequestT, ResponseT]
| type[BaseTransport[RequestT, ResponseT]],
default: type[BaseTransport[RequestT, ResponseT]],
) -> BaseTransport[RequestT, ResponseT]:
if entity and (
not isinstance(entity, BaseTransport)
and not issubclass(entity, BaseTransport)
):
raise TypeError("Invalid BaseTransport entity: {}".format(entity))
if entity is None:
return default()
if isinstance(entity, BaseTransport):
return entity
return entity() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/base.py#L154-L170 | 1 | [
0,
7,
12,
13,
14,
15,
16
] | 41.176471 | [
11
] | 5.882353 | false | 92.307692 | 17 | 6 | 94.117647 | 0 | def resolve_entity(
cls,
entity: None
| BaseTransport[RequestT, ResponseT]
| type[BaseTransport[RequestT, ResponseT]],
default: type[BaseTransport[RequestT, ResponseT]],
) -> BaseTransport[RequestT, ResponseT]:
if entity and (
not isinstance(entity, BaseTransport)
and not issubclass(entity, BaseTransport)
):
raise TypeError("Invalid BaseTransport entity: {}".format(entity))
if entity is None:
return default()
if isinstance(entity, BaseTransport):
return entity
return entity() | 79 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | RedirectExtension.__init__ | (self, cookiejar: None | CookieJar = None) | 16 | 21 | def __init__(self, cookiejar: None | CookieJar = None) -> None:
self.cookiejar = cookiejar if cookiejar else CookieJar()
self.ext_handlers = {
"init-retry": self.process_init_retry,
"retry": self.process_retry,
} | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L16-L21 | 1 | [
0,
1,
2
] | 50 | [] | 0 | false | 81.428571 | 6 | 1 | 100 | 0 | def __init__(self, cookiejar: None | CookieJar = None) -> None:
self.cookiejar = cookiejar if cookiejar else CookieJar()
self.ext_handlers = {
"init-retry": self.process_init_retry,
"retry": self.process_retry,
} | 80 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | RedirectExtension.find_redirect_url | (self, doc: Document) | return None | 23 | 27 | def find_redirect_url(self, doc: Document) -> None | str:
assert doc.headers is not None
if doc.code in {301, 302, 303, 307, 308} and doc.headers["Location"]:
return cast(str, doc.headers["Location"])
return None | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L23-L27 | 1 | [
0,
1,
2,
3,
4
] | 100 | [] | 0 | true | 81.428571 | 5 | 4 | 100 | 0 | def find_redirect_url(self, doc: Document) -> None | str:
assert doc.headers is not None
if doc.code in {301, 302, 303, 307, 308} and doc.headers["Location"]:
return cast(str, doc.headers["Location"])
return None | 81 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | RedirectExtension.process_init_retry | (self, retry: Any) | 29 | 30 | def process_init_retry(self, retry: Any) -> None:
retry.state["redirect_count"] = 0 | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L29-L30 | 1 | [
0,
1
] | 100 | [] | 0 | true | 81.428571 | 2 | 1 | 100 | 0 | def process_init_retry(self, retry: Any) -> None:
retry.state["redirect_count"] = 0 | 82 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | RedirectExtension.process_retry | (
self, retry: Any, req: HttpRequest, resp: Document
) | return None, None | 35 | 48 | def process_retry(
self, retry: Any, req: HttpRequest, resp: Document
) -> tuple[None, None] | tuple[Any, HttpRequest]:
if (
req.process_redirect
and (redir_url := self.find_redirect_url(resp)) is not None
):
retry.state["redirect_count"] += 1
if retry.state["redirect_count"] > req.redirect_limit:
raise GrabTooManyRedirectsError()
redir_url = urljoin(req.url, redir_url)
req.url = redir_url
return retry, req
return None, None | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L35-L48 | 1 | [
0,
3,
7,
8,
9,
10,
11,
12,
13
] | 64.285714 | [] | 0 | false | 81.428571 | 14 | 4 | 100 | 0 | def process_retry(
self, retry: Any, req: HttpRequest, resp: Document
) -> tuple[None, None] | tuple[Any, HttpRequest]:
if (
req.process_redirect
and (redir_url := self.find_redirect_url(resp)) is not None
):
retry.state["redirect_count"] += 1
if retry.state["redirect_count"] > req.redirect_limit:
raise GrabTooManyRedirectsError()
redir_url = urljoin(req.url, redir_url)
req.url = redir_url
return retry, req
return None, None | 83 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.__init__ | (self, cookiejar: None | CookieJar = None) | 52 | 57 | def __init__(self, cookiejar: None | CookieJar = None) -> None:
self.cookiejar = cookiejar if cookiejar else CookieJar()
self.ext_handlers = {
"request:pre": self.process_request_pre,
"response:post": self.process_response_post,
} | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L52-L57 | 1 | [
0,
1,
2
] | 50 | [] | 0 | false | 81.428571 | 6 | 1 | 100 | 0 | def __init__(self, cookiejar: None | CookieJar = None) -> None:
self.cookiejar = cookiejar if cookiejar else CookieJar()
self.ext_handlers = {
"request:pre": self.process_request_pre,
"response:post": self.process_response_post,
} | 84 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.set_cookie | (self, cookie: Cookie) | 59 | 60 | def set_cookie(self, cookie: Cookie) -> None:
self.cookiejar.set_cookie(cookie) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L59-L60 | 1 | [
0
] | 50 | [
1
] | 50 | false | 81.428571 | 2 | 1 | 50 | 0 | def set_cookie(self, cookie: Cookie) -> None:
self.cookiejar.set_cookie(cookie) | 85 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.clear | (self) | Clear all remembered cookies. | Clear all remembered cookies. | 62 | 64 | def clear(self) -> None:
"""Clear all remembered cookies."""
self.cookiejar.clear() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L62-L64 | 1 | [
0,
1,
2
] | 100 | [] | 0 | true | 81.428571 | 3 | 1 | 100 | 1 | def clear(self) -> None:
self.cookiejar.clear() | 86 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.clone | (self) | return self.__class__(build_jar(list(self.cookiejar))) | 66 | 67 | def clone(self) -> CookiesExtension:
return self.__class__(build_jar(list(self.cookiejar))) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L66-L67 | 1 | [
0
] | 50 | [
1
] | 50 | false | 81.428571 | 2 | 1 | 50 | 0 | def clone(self) -> CookiesExtension:
return self.__class__(build_jar(list(self.cookiejar))) | 87 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.update | (self, cookies: Mapping[str, Any], request_url: str) | 69 | 77 | def update(self, cookies: Mapping[str, Any], request_url: str) -> None:
request_host = urlsplit(request_url).hostname
if request_host and cookies:
# If cookie item is provided in form with no domain specified,
# then use domain value extracted from request URL
for name, value in cookies.items():
self.cookiejar.set_cookie(
create_cookie(name=name, value=value, domain=request_host)
) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L69-L77 | 1 | [
0,
1,
2,
3,
4,
5,
6
] | 77.777778 | [] | 0 | false | 81.428571 | 9 | 4 | 100 | 0 | def update(self, cookies: Mapping[str, Any], request_url: str) -> None:
request_host = urlsplit(request_url).hostname
if request_host and cookies:
# If cookie item is provided in form with no domain specified,
# then use domain value extracted from request URL
for name, value in cookies.items():
self.cookiejar.set_cookie(
create_cookie(name=name, value=value, domain=request_host)
) | 88 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.__getstate__ | (self) | return state | 79 | 86 | def __getstate__(self) -> MutableMapping[str, Any]:
state = {}
for name, value in self.__dict__.items():
if name == "cookiejar":
state["_cookiejar_items"] = list(value)
else:
state[name] = value
return state | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L79-L86 | 1 | [
0
] | 12.5 | [
1,
2,
3,
4,
6,
7
] | 75 | false | 81.428571 | 8 | 3 | 25 | 0 | def __getstate__(self) -> MutableMapping[str, Any]:
state = {}
for name, value in self.__dict__.items():
if name == "cookiejar":
state["_cookiejar_items"] = list(value)
else:
state[name] = value
return state | 89 |
||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.__setstate__ | (self, state: Mapping[str, Any]) | 88 | 93 | def __setstate__(self, state: Mapping[str, Any]) -> None:
for name, value in state.items():
if name == "_cookiejar_items":
self.cookiejar = build_jar(value)
else:
setattr(self, name, value) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L88-L93 | 1 | [
0
] | 16.666667 | [
1,
2,
3,
5
] | 66.666667 | false | 81.428571 | 6 | 3 | 33.333333 | 0 | def __setstate__(self, state: Mapping[str, Any]) -> None:
for name, value in state.items():
if name == "_cookiejar_items":
self.cookiejar = build_jar(value)
else:
setattr(self, name, value) | 90 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.process_request_pre | (self, req: HttpRequest) | 95 | 103 | def process_request_pre(self, req: HttpRequest) -> None:
self.update(req.cookies, req.url)
if hdr := build_cookie_header(self.cookiejar, req.url, req.headers):
if req.headers.get("Cookie"):
raise ValueError(
"Could not configure request with session cookies"
" because it has already Cookie header"
)
req.cookie_header = hdr | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L95-L103 | 1 | [
0,
1,
2,
3,
8
] | 55.555556 | [
4
] | 11.111111 | false | 81.428571 | 9 | 3 | 88.888889 | 0 | def process_request_pre(self, req: HttpRequest) -> None:
self.update(req.cookies, req.url)
if hdr := build_cookie_header(self.cookiejar, req.url, req.headers):
if req.headers.get("Cookie"):
raise ValueError(
"Could not configure request with session cookies"
" because it has already Cookie header"
)
req.cookie_header = hdr | 91 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.process_response_post | (
self, req: HttpRequest, doc: Document # pylint: disable=unused-argument
) | 105 | 109 | def process_response_post(
self, req: HttpRequest, doc: Document # pylint: disable=unused-argument
) -> None:
for item in doc.cookies:
self.cookiejar.set_cookie(item) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L105-L109 | 1 | [
0,
3,
4
] | 60 | [] | 0 | false | 81.428571 | 5 | 2 | 100 | 0 | def process_response_post(
self, req: HttpRequest, doc: Document # pylint: disable=unused-argument
) -> None:
for item in doc.cookies:
self.cookiejar.set_cookie(item) | 92 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/extensions.py | CookiesExtension.reset | (self) | 111 | 112 | def reset(self) -> None:
self.clear() | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/extensions.py#L111-L112 | 1 | [
0,
1
] | 100 | [] | 0 | true | 81.428571 | 2 | 1 | 100 | 0 | def reset(self) -> None:
self.clear() | 93 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/spider/task.py | Task.__init__ | ( # pylint:disable=too-many-arguments,too-many-locals,too-many-branches
self,
name: None | str = None,
url: None | str | HttpRequest = None,
request: None | HttpRequest = None,
priority: None | int = None,
priority_set_explicitly: bool = True,
network_try_count: int = 0,
task_try_count: int = 1,
valid_status: None | list[int] = None,
use_proxylist: bool = True,
delay: None | float = None,
raw: bool = False,
callback: None | Callable[..., None] = None,
fallback_name: None | str = None,
store: None | dict[str, Any] = None,
**kwargs: Any,
) | Create `Task` object.
If more than one of url, grab_config options are non-empty
then they processed in following order:
* grab_config overwrite url
Args:
:param name: name of the task. After successful network operation
task's result will be passed to `task_<name>` method.
:param priority: priority of the Task. Tasks with lower priority
will be processed earlier. By default each new task is assigned
with random priority from (80, 100) range.
:param priority_set_explicitly: internal flag which tells if that
task priority was assigned manually or generated by spider
according to priority generation rules.
:param network_try_count: you'll probably will not need to use it.
It is used internally to control how many times this task was
restarted due to network errors. The `Spider` instance has
`network_try_limit` option. When `network_try_count` attribute
of the task exceeds the `network_try_limit` attribute then
processing of the task is abandoned.
:param task_try_count: the as `network_try_count` but it increased
only then you use `clone` method. Also you can set it manually.
It is useful if you want to restart the task after it was
cancelled due to multiple network errors. As you might guessed
there is `task_try_limit` option in `Spider` instance. Both
options `network_try_count` and `network_try_limit` guarantee
you that you'll not get infinite loop of restarting some task.
:param valid_status: extra status codes which counts as valid
:param use_proxylist: it means to use proxylist which was
configured via `setup_proxylist` method of spider
:param delay: if specified tells the spider to schedule the task
and execute it after `delay` seconds
:param raw: if `raw` is True then the network response is
forwarding to the corresponding handler without any check of
HTTP status code of network error, if `raw` is False (by
default) then failed response is putting back to task queue or
if tries limit is reached then the processing of this request
is finished.
:param callback: if you pass some function in `callback` option
then the network response will be passed to this callback and
the usual 'task_*' handler will be ignored and no error will be
raised if such 'task_*' handler does not exist.
:param fallback_name: the name of method that is called when spider
gives up to do the task (due to multiple network errors)
Any non-standard named arguments passed to `Task` constructor will
be saved as attributes of the object. You can get their values
later as attributes or with `get` method which allows to use
default value if attribute does not exist. | Create `Task` object. | 20 | 128 | def __init__( # pylint:disable=too-many-arguments,too-many-locals,too-many-branches
self,
name: None | str = None,
url: None | str | HttpRequest = None,
request: None | HttpRequest = None,
priority: None | int = None,
priority_set_explicitly: bool = True,
network_try_count: int = 0,
task_try_count: int = 1,
valid_status: None | list[int] = None,
use_proxylist: bool = True,
delay: None | float = None,
raw: bool = False,
callback: None | Callable[..., None] = None,
fallback_name: None | str = None,
store: None | dict[str, Any] = None,
**kwargs: Any,
) -> None:
"""Create `Task` object.
If more than one of url, grab_config options are non-empty
then they processed in following order:
* grab_config overwrite url
Args:
:param name: name of the task. After successful network operation
task's result will be passed to `task_<name>` method.
:param priority: priority of the Task. Tasks with lower priority
will be processed earlier. By default each new task is assigned
with random priority from (80, 100) range.
:param priority_set_explicitly: internal flag which tells if that
task priority was assigned manually or generated by spider
according to priority generation rules.
:param network_try_count: you'll probably will not need to use it.
It is used internally to control how many times this task was
restarted due to network errors. The `Spider` instance has
`network_try_limit` option. When `network_try_count` attribute
of the task exceeds the `network_try_limit` attribute then
processing of the task is abandoned.
:param task_try_count: the as `network_try_count` but it increased
only then you use `clone` method. Also you can set it manually.
It is useful if you want to restart the task after it was
cancelled due to multiple network errors. As you might guessed
there is `task_try_limit` option in `Spider` instance. Both
options `network_try_count` and `network_try_limit` guarantee
you that you'll not get infinite loop of restarting some task.
:param valid_status: extra status codes which counts as valid
:param use_proxylist: it means to use proxylist which was
configured via `setup_proxylist` method of spider
:param delay: if specified tells the spider to schedule the task
and execute it after `delay` seconds
:param raw: if `raw` is True then the network response is
forwarding to the corresponding handler without any check of
HTTP status code of network error, if `raw` is False (by
default) then failed response is putting back to task queue or
if tries limit is reached then the processing of this request
is finished.
:param callback: if you pass some function in `callback` option
then the network response will be passed to this callback and
the usual 'task_*' handler will be ignored and no error will be
raised if such 'task_*' handler does not exist.
:param fallback_name: the name of method that is called when spider
gives up to do the task (due to multiple network errors)
Any non-standard named arguments passed to `Task` constructor will
be saved as attributes of the object. You can get their values
later as attributes or with `get` method which allows to use
default value if attribute does not exist.
"""
self.check_init_kwargs(kwargs)
if url is not None and request is not None:
raise GrabMisuseError("Options url and ruquest are mutually exclusive")
if request is not None:
if not isinstance(request, HttpRequest):
raise TypeError("Option 'requst' must be HttpRequest instance")
self.request = request
elif url is not None:
if isinstance(url, str):
self.request = HttpRequest(method="GET", url=url)
elif isinstance(url, HttpRequest):
self.request = url
else:
raise TypeError("Parameter 'url' must be str or HttpRequest instance")
else:
raise GrabMisuseError("Either url or request option must be set")
self.schedule_time: None | datetime = None
if name == "generator":
# The name "generator" is restricted because
# `task_generator` handler could not be created because
# this name is already used for special method which
# generates new tasks
raise SpiderMisuseError('Task name could not be "generator"')
self.name = name
if valid_status is None:
self.valid_status = []
else:
self.valid_status = valid_status
self.process_delay_option(delay)
self.fallback_name = fallback_name
self.priority_set_explicitly = priority_set_explicitly
self.priority = priority
self.network_try_count = network_try_count
self.task_try_count = task_try_count
self.use_proxylist = use_proxylist
self.raw = raw
self.callback = callback
self.store = store if store else {}
for key, value in kwargs.items():
setattr(self, key, value) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/spider/task.py#L20-L128 | 1 | [
0,
68,
69,
70,
71,
72,
73,
75,
76,
77,
78,
79,
80,
81,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
100,
101,
102,
103,
104,
105,
106,
107,
108
] | 36.697248 | [
74,
82
] | 1.834862 | false | 88.505747 | 109 | 11 | 98.165138 | 50 | def __init__( # pylint:disable=too-many-arguments,too-many-locals,too-many-branches
self,
name: None | str = None,
url: None | str | HttpRequest = None,
request: None | HttpRequest = None,
priority: None | int = None,
priority_set_explicitly: bool = True,
network_try_count: int = 0,
task_try_count: int = 1,
valid_status: None | list[int] = None,
use_proxylist: bool = True,
delay: None | float = None,
raw: bool = False,
callback: None | Callable[..., None] = None,
fallback_name: None | str = None,
store: None | dict[str, Any] = None,
**kwargs: Any,
) -> None:
self.check_init_kwargs(kwargs)
if url is not None and request is not None:
raise GrabMisuseError("Options url and ruquest are mutually exclusive")
if request is not None:
if not isinstance(request, HttpRequest):
raise TypeError("Option 'requst' must be HttpRequest instance")
self.request = request
elif url is not None:
if isinstance(url, str):
self.request = HttpRequest(method="GET", url=url)
elif isinstance(url, HttpRequest):
self.request = url
else:
raise TypeError("Parameter 'url' must be str or HttpRequest instance")
else:
raise GrabMisuseError("Either url or request option must be set")
self.schedule_time: None | datetime = None
if name == "generator":
# The name "generator" is restricted because
# `task_generator` handler could not be created because
# this name is already used for special method which
# generates new tasks
raise SpiderMisuseError('Task name could not be "generator"')
self.name = name
if valid_status is None:
self.valid_status = []
else:
self.valid_status = valid_status
self.process_delay_option(delay)
self.fallback_name = fallback_name
self.priority_set_explicitly = priority_set_explicitly
self.priority = priority
self.network_try_count = network_try_count
self.task_try_count = task_try_count
self.use_proxylist = use_proxylist
self.raw = raw
self.callback = callback
self.store = store if store else {}
for key, value in kwargs.items():
setattr(self, key, value) | 94 |
|
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/spider/task.py | Task.check_init_kwargs | (self, kwargs: Mapping[str, Any]) | 130 | 134 | def check_init_kwargs(self, kwargs: Mapping[str, Any]) -> None:
if "grab" in kwargs:
raise GrabMisuseError("Task does not accept 'grab' parameter")
if "grab_config" in kwargs:
raise GrabMisuseError("Task does not accept 'grab_config' parameter") | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/spider/task.py#L130-L134 | 1 | [
0,
1,
3
] | 60 | [
2,
4
] | 40 | false | 88.505747 | 5 | 3 | 60 | 0 | def check_init_kwargs(self, kwargs: Mapping[str, Any]) -> None:
if "grab" in kwargs:
raise GrabMisuseError("Task does not accept 'grab' parameter")
if "grab_config" in kwargs:
raise GrabMisuseError("Task does not accept 'grab_config' parameter") | 95 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/spider/task.py | Task.get | (self, key: str, default: Any = None) | return getattr(self, key, default) | Return value of attribute or None if such attribute does not exist. | Return value of attribute or None if such attribute does not exist. | 136 | 138 | def get(self, key: str, default: Any = None) -> Any:
"""Return value of attribute or None if such attribute does not exist."""
return getattr(self, key, default) | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/spider/task.py#L136-L138 | 1 | [
0,
1,
2
] | 100 | [] | 0 | true | 88.505747 | 3 | 1 | 100 | 1 | def get(self, key: str, default: Any = None) -> Any:
return getattr(self, key, default) | 96 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/spider/task.py | Task.process_delay_option | (self, delay: None | float) | 140 | 144 | def process_delay_option(self, delay: None | float) -> None:
if delay:
self.schedule_time = datetime.utcnow() + timedelta(seconds=delay)
else:
self.schedule_time = None | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/spider/task.py#L140-L144 | 1 | [
0,
1,
4
] | 60 | [
2
] | 20 | false | 88.505747 | 5 | 2 | 80 | 0 | def process_delay_option(self, delay: None | float) -> None:
if delay:
self.schedule_time = datetime.utcnow() + timedelta(seconds=delay)
else:
self.schedule_time = None | 97 |
|||
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/spider/task.py | Task.clone | (
self, url: None | str = None, request: None | HttpRequest = None, **kwargs: Any
) | return task | Clone Task instance.
Reset network_try_count, increase task_try_count.
Reset priority attribute if it was not set explicitly. | Clone Task instance. | 146 | 174 | def clone(
self, url: None | str = None, request: None | HttpRequest = None, **kwargs: Any
) -> Task:
"""Clone Task instance.
Reset network_try_count, increase task_try_count.
Reset priority attribute if it was not set explicitly.
"""
if url and request:
raise GrabMisuseError("Options url and request are mutually exclusive")
# First, create exact copy of the current Task object
attr_copy = deepcopy(self.__dict__)
if not attr_copy["priority_set_explicitly"]:
attr_copy["priority"] = None
task = Task(**attr_copy)
if url:
task.request.url = url
if request:
task.request = request
# Reset some task properties if they have not
# been set explicitly in kwargs
if "network_try_count" not in kwargs:
task.network_try_count = 0
if "task_try_count" not in kwargs:
task.task_try_count = self.task_try_count + 1
for key, value in kwargs.items():
setattr(task, key, value)
task.process_delay_option(None)
return task | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/spider/task.py#L146-L174 | 1 | [
0,
7,
8,
10,
11,
12,
13,
14,
15,
16,
17,
20,
21,
22,
23,
24,
25,
26,
27,
28
] | 68.965517 | [
9,
18
] | 6.896552 | false | 88.505747 | 29 | 9 | 93.103448 | 4 | def clone(
self, url: None | str = None, request: None | HttpRequest = None, **kwargs: Any
) -> Task:
if url and request:
raise GrabMisuseError("Options url and request are mutually exclusive")
# First, create exact copy of the current Task object
attr_copy = deepcopy(self.__dict__)
if not attr_copy["priority_set_explicitly"]:
attr_copy["priority"] = None
task = Task(**attr_copy)
if url:
task.request.url = url
if request:
task.request = request
# Reset some task properties if they have not
# been set explicitly in kwargs
if "network_try_count" not in kwargs:
task.network_try_count = 0
if "task_try_count" not in kwargs:
task.task_try_count = self.task_try_count + 1
for key, value in kwargs.items():
setattr(task, key, value)
task.process_delay_option(None)
return task | 98 |
lorien/grab | 2d170c31a3335c2e29578b42a5d62ef3efc5d7ee | grab/spider/task.py | Task.__repr__ | (self) | return "<Task: %s>" % self.request.url | 176 | 177 | def __repr__(self) -> str:
return "<Task: %s>" % self.request.url | https://github.com/lorien/grab/blob/2d170c31a3335c2e29578b42a5d62ef3efc5d7ee/project1/grab/spider/task.py#L176-L177 | 1 | [
0
] | 50 | [
1
] | 50 | false | 88.505747 | 2 | 1 | 50 | 0 | def __repr__(self) -> str:
return "<Task: %s>" % self.request.url | 99 |