Skip to content

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

added support for defining EXTENSIONS setting using dicts, like middleware settings

Pablo Hoffman7f3046141063
diff --git a/docs/ref/extension-manager.rst b/docs/ref/extension-manager.rst
index 96fe0a188..2e0d18dee 100644
--- a/docs/ref/extension-manager.rst
+++ b/docs/ref/extension-manager.rst
@@ -9,59 +9,54 @@ Extension Manager
The Extension Manager is responsible for loading and keeping track of installed
extensions and it's configured through the :setting:`EXTENSIONS` setting which
-contains a list of all available extensions.
-
-The extension manager is a singleton-type class, which is instantiated at
-module load time and can be accessed like this::
-
- from scrapy.extension import extensions
- webconsole_extension = extensions.enabled['WebConsole']
+contains a dictionary of all available extensions and their order similar to
+how you :ref:`configure the downloader middlewares
+<topics-downloader-middleware-setting>`.
.. class:: ExtensionManager
-Attributes
-----------
+ The extension manager is a singleton object, which is instantiated at module
+ loading time and can be accessed like this::
-.. attribute:: ExtensionManager.loaded
+ from scrapy.extension import extensions
- A boolean which is True if extensions are already loaded or False if
- they're not.
+ .. attribute:: loaded
-.. attribute:: ExtensionManager.enabled
+ A boolean which is True if extensions are already loaded or False if
+ they're not.
- A dict with the enabled extensions. The keys are the extension class names,
- and the values are the extension objects. Example::
+ .. attribute:: enabled
- >>> from scrapy.extension import extensions
- >>> extensions.load()
- >>> print extensions.enabled
- {'CoreStats': <scrapy.stats.corestats.CoreStats object at 0x9e272ac>,
- 'WebConsoke': <scrapy.management.telnet.TelnetConsole instance at 0xa05670c>,
- ...
+ A dict with the enabled extensions. The keys are the extension class names,
+ and the values are the extension objects. Example::
-.. attribute:: ExtensionManager.disabled
+ >>> from scrapy.extension import extensions
+ >>> extensions.load()
+ >>> print extensions.enabled
+ {'CoreStats': <scrapy.stats.corestats.CoreStats object at 0x9e272ac>,
+ 'WebConsoke': <scrapy.management.telnet.TelnetConsole instance at 0xa05670c>,
+ ...
- A dict with the disabled extensions. The keys are the extension class names,
- and the values are the extension class paths (because objects are never
- instantiated for disabled extensions). Example::
+ .. attribute:: disabled
- >>> from scrapy.extension import extensions
- >>> extensions.load()
- >>> print extensions.disabled
- {'MemoryDebugger': 'scrapy.contrib.webconsole.stats.MemoryDebugger',
- 'SpiderProfiler': 'scrapy.contrib.spider.profiler.SpiderProfiler',
- ...
+ A dict with the disabled extensions. The keys are the extension class names,
+ and the values are the extension class paths (because objects are never
+ instantiated for disabled extensions). Example::
-Methods
--------
+ >>> from scrapy.extension import extensions
+ >>> extensions.load()
+ >>> print extensions.disabled
+ {'MemoryDebugger': 'scrapy.contrib.webconsole.stats.MemoryDebugger',
+ 'SpiderProfiler': 'scrapy.contrib.spider.profiler.SpiderProfiler',
+ ...
-.. method:: ExtensionManager.load()
+ .. method:: load()
- Load the available extensions configured in the :setting:`EXTENSIONS`
- setting. On a standard run, this method is usually called by the Execution
- Manager, but you may need to call it explicitly if you're dealing with
- code outside Scrapy.
+ Load the available extensions configured in the :setting:`EXTENSIONS`
+ setting. On a standard run, this method is usually called by the Execution
+ Manager, but you may need to call it explicitly if you're dealing with
+ code outside Scrapy.
-.. method:: ExtensionManager.reload()
+ .. method:: reload()
- Reload the available extensions. See ``load()``.
+ Reload the available extensions. See :meth:`load`.
diff --git a/docs/ref/settings.rst b/docs/ref/settings.rst
index bbeddafbc..b3bc77840 100644
--- a/docs/ref/settings.rst
+++ b/docs/ref/settings.rst
@@ -278,28 +278,37 @@ The class used to detect and filter duplicate requests.
The default (``RequestFingerprintDupeFilter``) filters based on request fingerprint
(using ``scrapy.utils.request.request_fingerprint``) and grouping per domain.
-.. setting:: EXTENSIONS
+.. setting:: EXTENSIONS
EXTENSIONS
----------
+Default:: ``{}``
+
+A dict containing the extensions enabled in your project, and their orders.
+
+.. setting:: EXTENSIONS_BASE
+
+EXTENSIONS_BASE
+---------------
+
Default::
- [
- 'scrapy.stats.corestats.CoreStats',
- 'scrapy.management.web.WebConsole',
- 'scrapy.management.telnet.TelnetConsole',
- 'scrapy.contrib.webconsole.scheduler.SchedulerQueue',
- 'scrapy.contrib.webconsole.livestats.LiveStats',
- 'scrapy.contrib.webconsole.spiderctl.Spiderctl',
- 'scrapy.contrib.webconsole.enginestatus.EngineStatus',
- 'scrapy.contrib.webconsole.stats.StatsDump',
- 'scrapy.contrib.spider.reloader.SpiderReloader',
- 'scrapy.contrib.memusage.MemoryUsage',
- 'scrapy.contrib.memdebug.MemoryDebugger',
- 'scrapy.contrib.closedomain.CloseDomain',
- 'scrapy.contrib.debug.StackTraceDump',
- ]
+ {
+ 'scrapy.stats.corestats.CoreStats': 0,
+ 'scrapy.management.web.WebConsole': 0,
+ 'scrapy.management.telnet.TelnetConsole': 0,
+ 'scrapy.contrib.webconsole.scheduler.SchedulerQueue': 0,
+ 'scrapy.contrib.webconsole.livestats.LiveStats': 0,
+ 'scrapy.contrib.webconsole.spiderctl.Spiderctl': 0,
+ 'scrapy.contrib.webconsole.enginestatus.EngineStatus': 0,
+ 'scrapy.contrib.webconsole.stats.StatsDump': 0,
+ 'scrapy.contrib.spider.reloader.SpiderReloader': 0,
+ 'scrapy.contrib.memusage.MemoryUsage': 0,
+ 'scrapy.contrib.memdebug.MemoryDebugger': 0,
+ 'scrapy.contrib.closedomain.CloseDomain': 0,
+ 'scrapy.contrib.debug.StackTraceDump': 0,
+ }
The list of available extensions. Keep in mind that some of them need need to
be enabled through a setting. By default, this setting contains all stable
diff --git a/docs/topics/extensions.rst b/docs/topics/extensions.rst
index 62524658e..3172887de 100644
--- a/docs/topics/extensions.rst
+++ b/docs/topics/extensions.rst
@@ -30,19 +30,33 @@ Extensions are loaded and activated at startup by instantiating a single
instance of the extension class. Therefore, all the extension initialization
code must be performed in the class constructor (``__init__`` method).
-To make an extension available, add it to the :setting:`EXTENSIONS` list in
+To make an extension available, add it to the :setting:`EXTENSIONS` setting in
your Scrapy settings. In :setting:`EXTENSIONS`, each extension is represented
by a string: the full Python path to the extension's class name. For example::
- EXTENSIONS = [
- 'scrapy.stats.corestats.CoreStats',
- 'scrapy.management.web.WebConsole',
- 'scrapy.management.telnet.TelnetConsole',
- 'scrapy.contrib.webconsole.enginestatus.EngineStatus',
- 'scrapy.contrib.webconsole.stats.StatsDump',
- 'scrapy.contrib.debug.StackTraceDump',
- ]
-
+ EXTENSIONS = {
+ 'scrapy.stats.corestats.CoreStats': 500,
+ 'scrapy.management.web.WebConsole': 500,
+ 'scrapy.management.telnet.TelnetConsole': 500,
+ 'scrapy.contrib.webconsole.enginestatus.EngineStatus': 500,
+ 'scrapy.contrib.webconsole.stats.StatsDump': 500,
+ 'scrapy.contrib.debug.StackTraceDump': 500,
+ }
+
+
+As you can see, the :setting:`EXTENSIONS` setting is a dict where the keys are
+the extension paths, and their values are the orders, which define the
+extension *loading* order. Extensions orders are not as important as middleware
+orders though, and they are typically irrelevant, ie. it doesn't matter in
+which order the extensions are loaded because they don't depend on each other
+[1].
+
+However this feature can be exploited if you need to add an extension which
+depends on other extension already loaded.
+
+[1] This is is why the :setting:`EXTENSIONS_BASE` setting in Scrapy (which
+contains all built-in extensions enabled by default) defines all the extensions
+with the same order (``500``).
Available, enabled and disabled extensions
==========================================
diff --git a/scrapy/conf/default_settings.py b/scrapy/conf/default_settings.py
index e895c88bc..07ec182ba 100644
--- a/scrapy/conf/default_settings.py
+++ b/scrapy/conf/default_settings.py
@@ -70,21 +70,23 @@ DOWNLOADER_STATS = True
DUPEFILTER_CLASS = 'scrapy.contrib.dupefilter.RequestFingerprintDupeFilter'
-EXTENSIONS = [
- 'scrapy.stats.corestats.CoreStats',
- 'scrapy.management.web.WebConsole',
- 'scrapy.management.telnet.TelnetConsole',
- 'scrapy.contrib.webconsole.scheduler.SchedulerQueue',
- 'scrapy.contrib.webconsole.livestats.LiveStats',
- 'scrapy.contrib.webconsole.spiderctl.Spiderctl',
- 'scrapy.contrib.webconsole.enginestatus.EngineStatus',
- 'scrapy.contrib.webconsole.stats.StatsDump',
- 'scrapy.contrib.spider.reloader.SpiderReloader',
- 'scrapy.contrib.memusage.MemoryUsage',
- 'scrapy.contrib.memdebug.MemoryDebugger',
- 'scrapy.contrib.closedomain.CloseDomain',
- 'scrapy.contrib.debug.StackTraceDump',
-]
+EXTENSIONS = {}
+
+EXTENSIONS_BASE = {
+ 'scrapy.stats.corestats.CoreStats': 0,
+ 'scrapy.management.web.WebConsole': 0,
+ 'scrapy.management.telnet.TelnetConsole': 0,
+ 'scrapy.contrib.webconsole.scheduler.SchedulerQueue': 0,
+ 'scrapy.contrib.webconsole.livestats.LiveStats': 0,
+ 'scrapy.contrib.webconsole.spiderctl.Spiderctl': 0,
+ 'scrapy.contrib.webconsole.enginestatus.EngineStatus': 0,
+ 'scrapy.contrib.webconsole.stats.StatsDump': 0,
+ 'scrapy.contrib.spider.reloader.SpiderReloader': 0,
+ 'scrapy.contrib.memusage.MemoryUsage': 0,
+ 'scrapy.contrib.memdebug.MemoryDebugger': 0,
+ 'scrapy.contrib.closedomain.CloseDomain': 0,
+ 'scrapy.contrib.debug.StackTraceDump': 0,
+}
GROUPSETTINGS_ENABLED = False
GROUPSETTINGS_MODULE = ''
diff --git a/scrapy/core/downloader/middleware.py b/scrapy/core/downloader/middleware.py
index 4c97b0d26..9822f5c59 100644
--- a/scrapy/core/downloader/middleware.py
+++ b/scrapy/core/downloader/middleware.py
@@ -12,7 +12,7 @@ from scrapy.http import Request, Response
from scrapy.core.exceptions import NotConfigured
from scrapy.utils.misc import load_object
from scrapy.utils.defer import mustbe_deferred
-from scrapy.utils.middleware import build_middleware_list
+from scrapy.utils.conf import build_component_list
from scrapy.conf import settings
class DownloaderMiddlewareManager(object):
@@ -36,8 +36,8 @@ class DownloaderMiddlewareManager(object):
def load(self):
"""Load middleware defined in settings module"""
- mwlist = build_middleware_list(settings['DOWNLOADER_MIDDLEWARES_BASE'],
- settings['DOWNLOADER_MIDDLEWARES'])
+ mwlist = build_component_list(settings['DOWNLOADER_MIDDLEWARES_BASE'], \
+ settings['DOWNLOADER_MIDDLEWARES'])
self.enabled.clear()
self.disabled.clear()
for mwpath in mwlist:
diff --git a/scrapy/core/scheduler/middleware.py b/scrapy/core/scheduler/middleware.py
index 799af905f..483a7aa5d 100644
--- a/scrapy/core/scheduler/middleware.py
+++ b/scrapy/core/scheduler/middleware.py
@@ -13,7 +13,7 @@ from scrapy.http import Response
from scrapy.core.exceptions import NotConfigured
from scrapy.utils.misc import load_object
from scrapy.utils.defer import mustbe_deferred
-from scrapy.utils.middleware import build_middleware_list
+from scrapy.utils.conf import build_component_list
from scrapy.conf import settings
class SchedulerMiddlewareManager(object):
@@ -27,8 +27,8 @@ class SchedulerMiddlewareManager(object):
def load(self):
"""Load middleware defined in settings module"""
- mwlist = build_middleware_list(settings['SCHEDULER_MIDDLEWARES_BASE'],
- settings['SCHEDULER_MIDDLEWARES'])
+ mwlist = build_component_list(settings['SCHEDULER_MIDDLEWARES_BASE'], \
+ settings['SCHEDULER_MIDDLEWARES'])
self.enabled.clear()
self.disabled.clear()
for mwpath in mwlist:
diff --git a/scrapy/extension.py b/scrapy/extension.py
index a9d81f9c8..4f3ed8da7 100644
--- a/scrapy/extension.py
+++ b/scrapy/extension.py
@@ -5,6 +5,7 @@ ExtensionManager (extensions) to be used as singleton.
"""
from scrapy.core.exceptions import NotConfigured
from scrapy.utils.misc import load_object
+from scrapy.utils.conf import build_component_list
from scrapy import log
from scrapy.conf import settings
@@ -23,7 +24,9 @@ class ExtensionManager(object):
self.loaded = False
self.enabled.clear()
self.disabled.clear()
- for extension_path in settings.getlist('EXTENSIONS'):
+ extlist = build_component_list(settings['EXTENSIONS_BASE'], \
+ settings['EXTENSIONS'])
+ for extension_path in extlist:
try:
cls = load_object(extension_path)
self.enabled[cls.__name__] = cls()
diff --git a/scrapy/spider/middleware.py b/scrapy/spider/middleware.py
index ffb1d0770..e446a6a24 100644
--- a/scrapy/spider/middleware.py
+++ b/scrapy/spider/middleware.py
@@ -9,7 +9,7 @@ docs/topics/spider-middleware.rst
from scrapy import log
from scrapy.core.exceptions import NotConfigured
from scrapy.utils.misc import load_object
-from scrapy.utils.middleware import build_middleware_list
+from scrapy.utils.conf import build_component_list
from scrapy.utils.defer import mustbe_deferred
from scrapy.http import Request
from scrapy.conf import settings
@@ -37,8 +37,8 @@ class SpiderMiddlewareManager(object):
def load(self):
"""Load middleware defined in settings module"""
- mwlist = build_middleware_list(settings['SPIDER_MIDDLEWARES_BASE'],
- settings['SPIDER_MIDDLEWARES'])
+ mwlist = build_component_list(settings['SPIDER_MIDDLEWARES_BASE'], \
+ settings['SPIDER_MIDDLEWARES'])
self.enabled.clear()
self.disabled.clear()
for mwpath in mwlist:
diff --git a/scrapy/tests/test_utils_middleware.py b/scrapy/tests/test_utils_conf.py
similarity index 50%
rename from scrapy/tests/test_utils_middleware.py
rename to scrapy/tests/test_utils_conf.py
index f0bdec84b..44a940fe7 100644
--- a/scrapy/tests/test_utils_middleware.py
+++ b/scrapy/tests/test_utils_conf.py
@@ -1,17 +1,17 @@
import unittest
-from scrapy.utils.middleware import build_middleware_list
+from scrapy.utils.conf import build_component_list
-class UtilsMiddlewareTestCase(unittest.TestCase):
+class UtilsConfTestCase(unittest.TestCase):
- def test_build_middleware_list(self):
+ def test_build_component_list(self):
base = {'one': 1, 'two': 2, 'three': 3, 'five': 5, 'six': None}
custom = {'two': None, 'three': 8, 'four': 4}
- self.assertEqual(build_middleware_list(base, custom),
+ self.assertEqual(build_component_list(base, custom),
['one', 'four', 'five', 'three'])
custom = ['a', 'b', 'c']
- self.assertEqual(build_middleware_list(base, custom), custom)
+ self.assertEqual(build_component_list(base, custom), custom)
if __name__ == "__main__":
unittest.main()
diff --git a/scrapy/utils/conf.py b/scrapy/utils/conf.py
new file mode 100644
index 000000000..e49ea2e53
--- /dev/null
+++ b/scrapy/utils/conf.py
@@ -0,0 +1,13 @@
+from operator import itemgetter
+
+def build_component_list(base, custom):
+ """Compose a component list based on a custom and base dict of components
+ (typically middlewares or extensions), unless custom is already a list, in
+ which case it's returned.
+ """
+ if isinstance(custom, (list, tuple)):
+ return custom
+ compdict = base.copy()
+ compdict.update(custom)
+ return [k for k, v in sorted(compdict.items(), key=itemgetter(1)) \
+ if v is not None]
diff --git a/scrapy/utils/middleware.py b/scrapy/utils/middleware.py
deleted file mode 100644
index 051e4c990..000000000
--- a/scrapy/utils/middleware.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from operator import itemgetter
-
-def build_middleware_list(base, custom):
- """Compose a middleware list based on a custom and base dict of
- middlewares, unless custom is already a list, in which case it's returned.
- """
- if isinstance(custom, (list, tuple)):
- return custom
- mwdict = base.copy()
- mwdict.update(custom)
- return [k for k, v in sorted(mwdict.items(), key=itemgetter(1)) if v is not None]