-
Notifications
You must be signed in to change notification settings - Fork 766
feat: provide Request instances in skipped request callbacks #1999
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
vdusek
wants to merge
4
commits into
master
Choose a base branch
from
provide-request-in-skipped-callbacks
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+388
−98
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3bfba40
feat: provide Request instances in skipped request callbacks
vdusek af58657
docs: remove stray blank line in robots.txt skipped request example
vdusek 564183c
fix(crawlers): robust skipped-request callback dispatch and keep robo…
vdusek 608fbb6
docs: shorten skipped-request callback comments and drop helper modul…
vdusek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,8 +2,10 @@ | |
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| import asyncio | ||
| import functools | ||
| import inspect | ||
| import logging | ||
| import signal | ||
| import sys | ||
|
|
@@ -17,7 +19,7 @@ | |
| from http import HTTPStatus | ||
| from io import StringIO | ||
| from pathlib import Path | ||
| from typing import TYPE_CHECKING, Any, Generic, Literal, ParamSpec, cast | ||
| from typing import TYPE_CHECKING, Any, Generic, Literal, ParamSpec, cast, get_args | ||
| from weakref import WeakKeyDictionary | ||
|
|
||
| from cachetools import LRUCache | ||
|
|
@@ -110,7 +112,58 @@ | |
|
|
||
| ErrorHandler = Callable[[TCrawlingContext, Exception], Awaitable[Request | None]] | ||
| FailedRequestHandler = Callable[[TCrawlingContext, Exception], Awaitable[None]] | ||
| SkippedRequestCallback = Callable[[str, SkippedReason], Awaitable[None]] | ||
| SkippedRequestCallback = ( | ||
| Callable[[str, SkippedReason], Awaitable[None]] | Callable[[Request, SkippedReason], Awaitable[None]] | ||
| ) | ||
| """A skipped-request callback receives either the URL `str` or the full `Request`. | ||
|
|
||
| For backward compatibility, callbacks whose first parameter is annotated as `str` (or is unannotated) | ||
| receive `request.url`; callbacks that annotate it as `Request` receive the `Request` object. See | ||
| `_skipped_request_callback_expects_request`. | ||
| """ | ||
|
|
||
|
|
||
| def _skipped_request_callback_expects_request(callback: Callable[..., Awaitable[None]]) -> bool: | ||
| """Whether a skipped-request callback wants the full `Request` rather than the URL string. | ||
|
|
||
| The first parameter's annotation decides: `Request` (or a union such as `Request | None`) gets the | ||
| `Request` object; `str` or no annotation keeps the legacy `(url, reason)` signature. String | ||
| annotations (PEP 563, or a `TYPE_CHECKING`-only `Request` import) are matched by name so such hooks | ||
| don't silently degrade to the `str` form. | ||
| """ | ||
| try: | ||
| parameters = list(inspect.signature(callback).parameters.values()) | ||
| except (TypeError, ValueError): # Uninspectable callable falls back to the `str` form. | ||
| return False | ||
|
|
||
| if not parameters: | ||
| return False | ||
|
|
||
| annotation = parameters[0].annotation | ||
|
|
||
| if annotation is inspect.Parameter.empty: | ||
| return False | ||
|
|
||
| # A string annotation may not resolve to the class (e.g. a `TYPE_CHECKING`-only import), so match by name. | ||
| if isinstance(annotation, str): | ||
| return _annotation_names_request(annotation) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If I'm not mistaken, this won't match when the annotation uses an import alias under if TYPE_CHECKING:
from crawlee import Request as CrawleeRequest
async def skipped_hook(request: CrawleeRequest, _reason: SkippedReason) -> None:
pass |
||
|
|
||
| # A resolved annotation: match `Request` directly or inside a union. | ||
| return annotation is Request or Request in get_args(annotation) | ||
|
|
||
|
|
||
| def _annotation_names_request(annotation: str) -> bool: | ||
| """Whether a string annotation names `Request` (e.g. `Request`, `Request | None`), not `RequestOptions`.""" | ||
| try: | ||
| tree = ast.parse(annotation, mode='eval') | ||
| except SyntaxError: | ||
| return False | ||
|
|
||
| return any( | ||
| (isinstance(node, ast.Name) and node.id == Request.__name__) | ||
| or (isinstance(node, ast.Attribute) and node.attr == Request.__name__) | ||
| for node in ast.walk(tree) | ||
| ) | ||
|
|
||
|
|
||
| class _BasicCrawlerOptions(TypedDict): | ||
|
|
@@ -417,6 +470,7 @@ def __init__( | |
| self._error_handler: ErrorHandler[TCrawlingContext | BasicCrawlingContext] | None = None | ||
| self._failed_request_handler: FailedRequestHandler[TCrawlingContext | BasicCrawlingContext] | None = None | ||
| self._on_skipped_request: SkippedRequestCallback | None = None | ||
| self._on_skipped_request_expects_request = False | ||
| self._abort_on_error = abort_on_error | ||
|
|
||
| # Crawler callbacks | ||
|
|
@@ -678,8 +732,13 @@ def on_skipped_request(self, callback: SkippedRequestCallback) -> SkippedRequest | |
| """Register a function to handle skipped requests. | ||
|
|
||
| The skipped request handler is invoked when a request is skipped due to a collision or other reasons. | ||
|
|
||
| The callback receives either the request URL as a `str` or the full `Request` object, depending on | ||
| how its first parameter is annotated. Annotate it as `Request` to access request metadata such as | ||
| `user_data`; a `str` annotation (or no annotation) keeps the original URL-only behavior. | ||
| """ | ||
| self._on_skipped_request = callback | ||
| self._on_skipped_request_expects_request = _skipped_request_callback_expects_request(callback) | ||
| return callback | ||
|
|
||
| async def run( | ||
|
|
@@ -826,12 +885,14 @@ async def add_requests( | |
| wait_for_all_requests_to_be_added: If True, wait for all requests to be added before returning. | ||
| wait_for_all_requests_to_be_added_timeout: Timeout for waiting for all requests to be added. | ||
| """ | ||
| allowed_requests = [] | ||
| skipped = [] | ||
|
|
||
| for request in requests: | ||
| check_url = request.url if isinstance(request, Request) else request | ||
| if await self._is_allowed_based_on_robots_txt_file(check_url): | ||
| allowed_requests: list[Request] = [] | ||
| skipped: list[Request] = [] | ||
|
|
||
| for original in requests: | ||
| # Normalize `str` URLs to `Request` once, so robots-skipped items always reach the | ||
| # skipped-request callback as a `Request` (see `_handle_skipped_request`). | ||
| request = original if isinstance(original, Request) else Request.from_url(original) | ||
| if await self._is_allowed_based_on_robots_txt_file(request.url): | ||
| allowed_requests.append(request) | ||
| else: | ||
| skipped.append(request) | ||
|
|
@@ -1210,17 +1271,19 @@ async def _handle_failed_request(self, context: TCrawlingContext | BasicCrawling | |
| raise UserDefinedErrorHandlerError('Exception thrown in user-defined failed request handler') from e | ||
|
|
||
| async def _handle_skipped_request( | ||
| self, request: Request | str, reason: SkippedReason, *, need_mark: bool = False | ||
| self, request: Request, reason: SkippedReason, *, need_mark: bool = False | ||
| ) -> None: | ||
| if need_mark and isinstance(request, Request): | ||
| if need_mark: | ||
| request.state = RequestState.SKIPPED | ||
| await self._mark_request_as_handled(request) | ||
|
|
||
| url = request.url if isinstance(request, Request) else request | ||
|
|
||
| if self._on_skipped_request: | ||
| if self._on_skipped_request is not None: | ||
| # Pass the full `Request` or just its URL, depending on how the callback annotated its first | ||
| # parameter (see `on_skipped_request`). The cast reflects that dual-dispatch contract. | ||
| callback = cast('Callable[[str | Request, SkippedReason], Awaitable[None]]', self._on_skipped_request) | ||
| argument: str | Request = request if self._on_skipped_request_expects_request else request.url | ||
| try: | ||
| await self._on_skipped_request(url, reason) | ||
| await callback(argument, reason) | ||
| except Exception as e: | ||
| raise UserDefinedErrorHandlerError('Exception thrown in user-defined skipped request callback') from e | ||
|
|
||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we can wait for v2 release and make a breaking change with a clear signature to avoid this kind of fragile runtime inspection.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed