【问题标题】:Scrapy - Activating an Item Pipeline component - ITEM_PIPELINES settingScrapy - 激活项目管道组件 - ITEM_PIPELINES 设置
【发布时间】:2015-04-27 09:58:00
【问题描述】:
在scrapy文档中有这样的信息:
激活项目管道组件
要激活 Item Pipeline 组件,您必须将其类添加到
ITEM_PIPELINES 设置,如下例所示:
ITEM_PIPELINES = {
'myproject.pipelines.PricePipeline': 300,
'myproject.pipelines.JsonWriterPipeline': 800, }
您在此设置中分配给类的整数值决定了
他们运行的订单 - 项目通过管道从订单号低到
高的。通常将这些数字定义在 0-1000 范围内。
最后一段没看懂,主要是“确定
他们运行的订单 - 项目通过管道从订单号低到
高”,你能解释一下吗?选择数字是因为什么?在 0-1000 范围内如何选择值?
【问题讨论】:
标签:
python
scrapy
settings
pipeline
【解决方案1】:
由于Python 中的字典是无序集合,而ITEM_PIPELINES 必须是字典(与许多其他设置一样,例如SPIDER_MIDDLEWARES),您需要,以某种方式,定义应用管道的顺序。这就是为什么您需要为您定义的每个管道分配一个从 0 到 1000 的数字。
仅供参考,如果您查看 Scrapy 源代码,您会发现 build_component_list() 函数为每个设置调用,例如 ITEM_PIPELINES - 它使用您在 ITEM_PIPELINES 中定义的字典创建一个列表(有序集合)用于排序的字典值:
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)
items = (x for x in six.iteritems(compdict) if x[1] is not None)
return [x[0] for x in sorted(items, key=itemgetter(1))]
【解决方案2】:
来自docs
ITEM_PIPELINES
默认值:{}
包含要使用的项目管道及其顺序的字典。这
dict 默认为空 order 值是任意的,但它是习惯性的
在 0-1000 范围内定义它们。