Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Implement a NO_CALLBACK value for Request.callback

Adrián Chaves50500a6b2897
diff --git a/docs/topics/request-response.rst b/docs/topics/request-response.rst
index a0d9fc03e..766710d66 100644
--- a/docs/topics/request-response.rst
+++ b/docs/topics/request-response.rst
@@ -32,11 +32,22 @@ Request objects
:type url: str
:param callback: the function that will be called with the response of this
- request (once it's downloaded) as its first parameter. For more information
- see :ref:`topics-request-response-ref-request-callback-arguments` below.
- If a Request doesn't specify a callback, the spider's
- :meth:`~scrapy.Spider.parse` method will be used.
- Note that if exceptions are raised during processing, errback is called instead.
+ request (once it's downloaded) as its first parameter.
+
+ In addition to a function, the following values are supported:
+
+ - ``None`` (default), which indicates that the spider's
+ :meth:`~scrapy.Spider.parse` method must be used.
+
+ - :py:data:`scrapy.http.request.NO_CALLBACK`
+
+ .. autodata:: scrapy.http.request.NO_CALLBACK
+
+ For more information, see
+ :ref:`topics-request-response-ref-request-callback-arguments`.
+
+ .. note:: If exceptions are raised during processing, ``errback`` is
+ called instead.
:type callback: collections.abc.Callable
@@ -69,16 +80,24 @@ Request objects
1. Using a dict::
- request_with_cookies = Request(url="http://www.example.com",
- cookies={'currency': 'USD', 'country': 'UY'})
+ request_with_cookies = Request(
+ url="http://www.example.com",
+ cookies={'currency': 'USD', 'country': 'UY'},
+ )
2. Using a list of dicts::
- request_with_cookies = Request(url="http://www.example.com",
- cookies=[{'name': 'currency',
- 'value': 'USD',
- 'domain': 'example.com',
- 'path': '/currency'}])
+ request_with_cookies = Request(
+ url="http://www.example.com",
+ cookies=[
+ {
+ 'name': 'currency',
+ 'value': 'USD',
+ 'domain': 'example.com',
+ 'path': '/currency',
+ },
+ ],
+ )
The latter form allows for customizing the ``domain`` and ``path``
attributes of the cookie. This is only useful if the cookies are saved
diff --git a/scrapy/downloadermiddlewares/robotstxt.py b/scrapy/downloadermiddlewares/robotstxt.py
index 7bd39aa43..67e14b7b5 100644
--- a/scrapy/downloadermiddlewares/robotstxt.py
+++ b/scrapy/downloadermiddlewares/robotstxt.py
@@ -9,6 +9,7 @@ import logging
from twisted.internet.defer import Deferred, maybeDeferred
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.http import Request
+from scrapy.http.request import NO_CALLBACK
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.log import failure_to_exc_info
from scrapy.utils.misc import load_object
@@ -65,7 +66,8 @@ class RobotsTxtMiddleware:
robotsreq = Request(
robotsurl,
priority=self.DOWNLOAD_PRIORITY,
- meta={'dont_obey_robotstxt': True}
+ meta={'dont_obey_robotstxt': True},
+ callback=NO_CALLBACK,
)
dfd = self.crawler.engine.download(robotsreq)
dfd.addCallback(self._parse_robots, netloc, spider)
diff --git a/scrapy/http/request/__init__.py b/scrapy/http/request/__init__.py
index a1001fc4a..b57faf121 100644
--- a/scrapy/http/request/__init__.py
+++ b/scrapy/http/request/__init__.py
@@ -20,6 +20,17 @@ from scrapy.utils.url import escape_ajax
RequestTypeVar = TypeVar("RequestTypeVar", bound="Request")
+#: When assigned to the ``callback`` parameter of
+#: :class:`~scrapy.http.Request`, it indicates that the request it not meant to
+#: have a spider callback at all.
+#:
+#: This value should be used by :ref:`components <topics-components>`
+#: that create and handle their own requests, e.g. through
+#: :meth:`scrapy.core.engine.ExecutionEngine.download`, so that download
+#: middlewares handling such requests can treat them differently from requests
+#: intended for the :meth:`~scrapy.Spider.parse` callback.
+NO_CALLBACK = object()
+
class Request(object_ref):
"""Represents an HTTP request, which is usually generated in a Spider and
@@ -63,12 +74,8 @@ class Request(object_ref):
raise TypeError(f"Request priority not an integer: {priority!r}")
self.priority = priority
- if callback is not None and not callable(callback):
- raise TypeError(f'callback must be a callable, got {type(callback).__name__}')
- if errback is not None and not callable(errback):
- raise TypeError(f'errback must be a callable, got {type(errback).__name__}')
- self.callback = callback
- self.errback = errback
+ self._set_xback("callback", callback)
+ self._set_xback("errback", errback)
self.cookies = cookies or {}
self.headers = Headers(headers or {}, encoding=encoding)
@@ -78,6 +85,15 @@ class Request(object_ref):
self._cb_kwargs = dict(cb_kwargs) if cb_kwargs else None
self.flags = [] if flags is None else list(flags)
+ def _set_xback(self, name: str, value: Optional[Callable]) -> None:
+ if (
+ value is not None
+ and (name != "callback" or value is not NO_CALLBACK)
+ and not callable(value)
+ ):
+ raise TypeError(f'{name} must be a callable, got {type(value).__name__}')
+ setattr(self, name, value)
+
@property
def cb_kwargs(self) -> dict:
if self._cb_kwargs is None:
diff --git a/scrapy/pipelines/media.py b/scrapy/pipelines/media.py
index 5308a9793..fc5db58e8 100644
--- a/scrapy/pipelines/media.py
+++ b/scrapy/pipelines/media.py
@@ -7,6 +7,7 @@ from warnings import warn
from twisted.internet.defer import Deferred, DeferredList
from twisted.python.failure import Failure
+from scrapy.http.request import NO_CALLBACK
from scrapy.settings import Settings
from scrapy.utils.datatypes import SequenceExclude
from scrapy.utils.defer import mustbe_deferred, defer_result
@@ -93,7 +94,7 @@ class MediaPipeline:
fp = self._fingerprinter.fingerprint(request)
cb = request.callback or (lambda _: _)
eb = request.errback
- request.callback = None
+ request.callback = NO_CALLBACK
request.errback = None
# Return cached result if request was already seen
diff --git a/tests/test_downloadermiddleware_robotstxt.py b/tests/test_downloadermiddleware_robotstxt.py
index 1460d88eb..71d53ff1a 100644
--- a/tests/test_downloadermiddleware_robotstxt.py
+++ b/tests/test_downloadermiddleware_robotstxt.py
@@ -8,6 +8,7 @@ from scrapy.downloadermiddlewares.robotstxt import (RobotsTxtMiddleware,
logger as mw_module_logger)
from scrapy.exceptions import IgnoreRequest, NotConfigured
from scrapy.http import Request, Response, TextResponse
+from scrapy.http.request import NO_CALLBACK
from scrapy.settings import Settings
from tests.test_robotstxt_interface import rerp_available, reppy_available
@@ -53,6 +54,7 @@ Disallow: /some/randome/page.html
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
return DeferredList([
self.assertNotIgnored(Request('http://site.local/allowed'), middleware),
+ maybeDeferred(self.assertRobotsTxtRequested, "http://site.local"),
self.assertIgnored(Request('http://site.local/admin/main'), middleware),
self.assertIgnored(Request('http://site.local/static/'), middleware),
self.assertIgnored(Request('http://site.local/wiki/K%C3%A4ytt%C3%A4j%C3%A4:'), middleware),
@@ -183,6 +185,12 @@ Disallow: /some/randome/page.html
return self.assertFailure(maybeDeferred(middleware.process_request, request, spider),
IgnoreRequest)
+ def assertRobotsTxtRequested(self, base_url):
+ calls = self.crawler.engine.download.call_args_list
+ request = calls[0][0][0]
+ self.assertEqual(request.url, f"{base_url}/robots.txt")
+ self.assertEqual(request.callback, NO_CALLBACK)
+
class RobotsTxtMiddlewareWithRerpTest(RobotsTxtMiddlewareTest):
if not rerp_available():
diff --git a/tests/test_http_request.py b/tests/test_http_request.py
index 81cebdc7b..e14f8c8f4 100644
--- a/tests/test_http_request.py
+++ b/tests/test_http_request.py
@@ -7,6 +7,7 @@ from unittest import mock
from urllib.parse import parse_qs, unquote_to_bytes, urlparse
from scrapy.http import Request, FormRequest, XmlRpcRequest, JsonRequest, Headers, HtmlResponse
+from scrapy.http.request import NO_CALLBACK
from scrapy.utils.python import to_bytes, to_unicode
@@ -277,6 +278,12 @@ class RequestTest(unittest.TestCase):
self.assertIs(r4.callback, a_function)
self.assertIs(r4.errback, a_function)
+ r5 = self.request_class(
+ url='http://example.com',
+ callback=NO_CALLBACK,
+ )
+ self.assertIs(r5.callback, NO_CALLBACK)
+
def test_callback_and_errback_type(self):
with self.assertRaises(TypeError):
self.request_class('http://example.com', callback='a_function')
@@ -288,6 +295,8 @@ class RequestTest(unittest.TestCase):
callback='a_function',
errback='a_function',
)
+ with self.assertRaises(TypeError):
+ self.request_class('http://example.com', errback=NO_CALLBACK)
def test_from_curl(self):
# Note: more curated tests regarding curl conversion are in
diff --git a/tests/test_pipeline_files.py b/tests/test_pipeline_files.py
index 4acd29bf7..83572e74f 100644
--- a/tests/test_pipeline_files.py
+++ b/tests/test_pipeline_files.py
@@ -33,10 +33,7 @@ from scrapy.utils.test import (
skip_if_no_boto,
)
-
-def _mocked_download_func(request, info):
- response = request.meta.get('response')
- return response() if callable(response) else response
+from .test_pipeline_media import _mocked_download_func
class FilesPipelineTestCase(unittest.TestCase):
diff --git a/tests/test_pipeline_images.py b/tests/test_pipeline_images.py
index 6f5466191..3b39212bd 100644
--- a/tests/test_pipeline_images.py
+++ b/tests/test_pipeline_images.py
@@ -31,18 +31,13 @@ else:
skip_pillow = None
-def _mocked_download_func(request, info):
- response = request.meta.get('response')
- return response() if callable(response) else response
-
-
class ImagesPipelineTestCase(unittest.TestCase):
skip = skip_pillow
def setUp(self):
self.tempdir = mkdtemp()
- self.pipeline = ImagesPipeline(self.tempdir, download_func=_mocked_download_func)
+ self.pipeline = ImagesPipeline(self.tempdir)
def tearDown(self):
rmtree(self.tempdir)
diff --git a/tests/test_pipeline_media.py b/tests/test_pipeline_media.py
index 0a94ae699..99fb424f4 100644
--- a/tests/test_pipeline_media.py
+++ b/tests/test_pipeline_media.py
@@ -9,6 +9,7 @@ from twisted.internet.defer import Deferred, inlineCallbacks
from scrapy import signals
from scrapy.http import Request, Response
+from scrapy.http.request import NO_CALLBACK
from scrapy.settings import Settings
from scrapy.spiders import Spider
from scrapy.pipelines.files import FileException
@@ -29,6 +30,7 @@ else:
def _mocked_download_func(request, info):
+ assert request.callback is NO_CALLBACK
response = request.meta.get('response')
return response() if callable(response) else response