scrapy配置文件操作核心API解读

简介: scrapy是一个重型框架,但是在使用中却感觉很方便,只需要配置一下,写一点核心的代码,就可以实现高并发爬虫,这是得益于他的强大配置文件的机制,内置很多默认配置,同时还给用户提供了外在的配置,并解决其中的冲突,这是它强大的地方。

scrapy是一个重型框架,但是在使用中却感觉很方便,只需要配置一下,写一点核心的代码,就可以实现高并发爬虫,这是得益于他的强大配置文件的机制,内置很多默认配置,同时还给用户提供了外在的配置,并解决其中的冲突,这是它强大的地方。


完整setting源码

import six
import json
import copy
from collections import MutableMapping
from importlib import import_module
from pprint import pformat

from . import default_settings


SETTINGS_PRIORITIES = {
    
'default'0,
    
'command'10,
    
'project'20,
    
'spider'30,
    
'cmdline'40,
}


def get_settings_priority(priority):
    
"""
    Small helper function that looks up a given string priority in the
    :attr:`~scrapy.settings.SETTINGS_PRIORITIES` dictionary and returns its
    numerical value, or directly returns a given numerical priority.
    """

    
if isinstance(priority, six.string_types):
        
return SETTINGS_PRIORITIES[priority]
    
else:
        
return priority


太多了,删减部分def iter_default_settings():
    
"""Return the default settings as an iterator of (name, value) tuples"""
    
for name in dir(default_settings):
        
if name.isupper():
            
yield name, getattr(default_settings, name)


def overridden_settings(settings):
    
"""Return a dict of the settings that have been overridden"""
    
for name, defvalue in iter_default_settings():
        value = settings[name]
        
if not isinstance(defvalue, dict) and value != defvalue:
            
yield name, value



scrapy.settings.SETTINGS_PRIORITIES


设置了Scrapy中默认的优先级的键名和优先级值的字典。

每个项目定义一个设置入口点,为其提供标识的代码名称和整数优先级。在设置和检索Settings类中的值时,更高优先级优先于较小优先 级。

该值位于scrapy.settings中,默认值如下:

SETTINGS_PRIORITIES = {

        'default': 0,

        'command': 10,

        'project': 20,

        'spider': 30,

        'cmdline': 40,

            }


scrapy.settings.get_settings_priority(priority)

源码

def get_settings_priority(priority):
    """
    Small helper function that looks up a given string priority in the
    :attr:`~scrapy.settings.SETTINGS_PRIORITIES` dictionary and returns its
    numerical value, or directly returns a given numerical priority.
    """

    if isinstance(priority, six.string_types):
        return SETTINGS_PRIORITIES[priority]
    else:
        return priority


用于在SETTINGS_PRIORITIES字典中查找给定的字符串优先级 并返回其数值, 或直接返回给定的数字优先级。


class scrapy.settings.Settings(values = None,priority ='project' )


继承: scrapy.settings.BaseSettings,该对象存储用于配置内部组件的Scrapy设置,并可用于任何进一步的自定义。

它是BaseSettings的子类,支持所有 BaseSettings方法。此外,在实例化此类之后,新对象将具有已在内置设置引用中描述的全局默认设置。

class Settings(BaseSettings):
    """
    This object stores Scrapy settings for the configuration of internal
    components, and can be used for any further customization.

    It is a direct subclass and supports all methods of
    :class:`~scrapy.settings.BaseSettings`. Additionally, after instantiation
    of this class, the new object will have the global default settings
    described on :ref:`topics-settings-ref` already populated.
    """


    def __init__(self, values=None, priority='project'):
        # Do not pass kwarg values here. We don't want to promote user-defined
        # dicts, and we want to update, not replace, default dicts with the
        # values given by the user
        super(Settings, self).__init__()
        self.setmodule(default_settings, 'default')
        # Promote default dictionaries to BaseSettings instances for per-key
        # priorities
        for name, val in six.iteritems(self):
            if isinstance(val, dict):
                self.set(name, BaseSettings(val, 'default'), 'default')
        self.update(values, priority)


class scrapy.settings.BaseSettings(values = None,priority ='project' )


此类的实例表现得像字典,但存储优先级键值对,并且可以被锁定(即标记为不可变)。

键值条目可以在初始化时使用values 参数传递,并且它们将采用该priority级别(除非values已经是实例BaseSettings,在这种情况下将保留现有的优先级)。如果priority 参数是字符串,则将查找优先级名称 SETTINGS_PRIORITIES。否则,应提供特定的整数。


创建对象后,可以使用该set()方法加载或更新新设置,并可使用 字典的方括号表示法或get()实例的 方法及其值转换变体进行访问。请求存储密钥时,将检索具有最高优先级的值。


该类具有以下方法


copy()

制作当前设置的深层副本。

此方法返回类的新实例,其中Settings填充了相同的值及其优先级。

对新对象的修改不会反映在原始设置上。


copy_to_dict()

制作当前设置的副本并转换为字典。

此法返回一个新的dict,其中填充了与当前设置相同的值及其优先级。

对返回的dict的修改不会影响原始设置上。

此方法可用于例如在Scrapy shell中打印设置。


freeze()

禁用对当前设置的进一步更改。

调用此方法后,设置的当前状态将变为不可变。试图通过该set()方法及其变体更改值是不可能的,并将被警告。


frozencopy()

返回当前设置的不可变副本。

freeze()在返回的对象中调用的别名copy()。


get(name,default=None)

    获取设置值而不影响其原始类型。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getbool(name,default = False )

获取设置值作为布尔值。

1,'1',TRUE、'True'返回True,同时0,'0',False,'False'、None返回False。

例如,通过设置为的环境变量填充的设置 '0'将False在使用此方法时返回。

参数:

name(字符串) - 设置名称

default(any) - 如果未找到设置则返回的值


getdict(name,default=None)

获取设置值作为字典。

如果设置原始类型是字典,则将返回其副本。如果它是一个字符串,它将被转化为为JSON字典。如果它是一个 BaseSettings实例本身,它将被转换为一个字典,包含它们将返回的所有当前设置值get(),并丢失有关优先级和可变性的所有信息。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getfloat(name,default= 0.0 )

    获取设置值作为浮点数。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getint(name,default= 0 )

    获取设置值作为int。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getlist(name,default=None)

    获取设置值作为列表。如果设置原始类型是列表,则将返回其副本。如果它是一个字符串,它将被“,”拆分。

    例如,通过设置为的环境变量填充的设置 'one,two'将在使用此方法时返回列表['one','two']。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getpriority(name)

    返回设置的当前数字优先级值,或者None如果给定的name不存在。

    参数:name(字符串) - 设置名称


getwithbase(名字)

    获得类似字典的设置及其_BASE 对应的组合。

    参数: name(字符串) - 类字典设置的名称


maxpriority()

返回所有设置中存在的最高优先级的数值,或者如果没有存储设置则返回defaultfrom 的数值SETTINGS_PRIORITIES。


set(name,value,priority='project' )

设置给定优先级的键/值属性。

在配置Crawler对象(通过configure()方法)之前应该填充设置,否则它们将不起作用。

参数:

name(字符串) - 设置名称

value(any) - 与设置关联的值

priority(字符串或整数) - 设置的优先级。应该是一个键 SETTINGS_PRIORITIES或整数


setmodule(modulepriority='project' )

存储具有给定优先级的模块的设置。

这是一个辅助函数,它使用提供的函数调用 set()每个全局声明的大写变量。modulepriority

参数:

module(模块对象或字符串) - 模块或模块的路径

priority(字符串或整数) - 设置的优先级。应该是一个键 SETTINGS_PRIORITIES或整数


update(values,priority ='project' )

存储具有给定优先级的键/值对。

这是一个辅助函数调用 set()为每一个项目values 与所提供的priority。

如果values是字符串,则假定它是JSON编码的并且首先解析为dict json.loads()。如果是 BaseSettings实例,将使用每个键的优先级并priority忽略该参数。这允许使用单个命令插入/更新具有不同优先级的设置。

参数:

values(dict或string或BaseSettings) - 设置名称和值

priority(字符串或整数) - 设置的优先级。应该是一个键 SETTINGS_PRIORITIES或整数


scrapy.settings.BaseSettings完整源码及其方法如下:

class BaseSettings(MutableMapping):
"""
Instances of this class behave like dictionaries, but store priorities
along with their ``(key, value)`` pairs, and can be frozen (i.e. marked
immutable).
Key-value entries can be passed on initialization with the ``values``
argument, and they would take the ``priority`` level (unless ``values`` is
already an instance of :class:`~scrapy.settings.BaseSettings`, in which
case the existing priority levels will be kept). If the ``priority``
argument is a string, the priority name will be looked up in
:attr:`~scrapy.settings.SETTINGS_PRIORITIES`. Otherwise, a specific integer
should be provided.
Once the object is created, new settings can be loaded or updated with the
:meth:`~scrapy.settings.BaseSettings.set` method, and can be accessed with
the square bracket notation of dictionaries, or with the
:meth:`~scrapy.settings.BaseSettings.get` method of the instance and its
value conversion variants. When requesting a stored key, the value with the
highest priority will be retrieved.
"""
def __init__(self, values=None, priority='project'):
self.frozen = False
self.attributes = {}
self.update(values, priority)

def __getitem__(self, opt_name):
if opt_name not in self:
return None
return self.attributes[opt_name].value

def __contains__(self, name):
return name in self.attributes

def get(self, name, default=None):
"""
Get a setting value without affecting its original type.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
return self[name] if self[name] is not None else default

def getbool(self, name, default=False):
"""
Get a setting value as a boolean.
``1``, ``'1'``, `True`` and ``'True'`` return ``True``,
while ``0``, ``'0'``, ``False``, ``'False'`` and ``None`` return ``False``.
For example, settings populated through environment variables set to
``'0'`` will return ``False`` when using this method.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
got = self.get(name, default)
try:
return bool(int(got))
except ValueError:
if got in ("True", "true"):
return True
if got in ("False", "false"):
return False
raise ValueError("Supported values for boolean settings "
"are 0/1, True/False, '0'/'1', "
"'True'/'False' and 'true'/'false'")

def getint(self, name, default=0):
"""
Get a setting value as an int.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
return int(self.get(name, default))

def getfloat(self, name, default=0.0):
"""
Get a setting value as a float.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
return float(self.get(name, default))

def getlist(self, name, default=None):
"""
Get a setting value as a list. If the setting original type is a list, a
copy of it will be returned. If it's a string it will be split by ",".
For example, settings populated through environment variables set to
``'one,two'`` will return a list ['one', 'two'] when using this method.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
value = self.get(name, default or [])
if isinstance(value, six.string_types):
value = value.split(',')
return list(value)

def getdict(self, name, default=None):
"""
Get a setting value as a dictionary. If the setting original type is a
dictionary, a copy of it will be returned. If it is a string it will be
evaluated as a JSON dictionary. In the case that it is a
:class:`~scrapy.settings.BaseSettings` instance itself, it will be
converted to a dictionary, containing all its current settings values
as they would be returned by :meth:`~scrapy.settings.BaseSettings.get`,
and losing all information about priority and mutability.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
value = self.get(name, default or {})
if isinstance(value, six.string_types):
value = json.loads(value)
return dict(value)

def getwithbase(self, name):
"""Get a composition of a dictionary-like setting and its `_BASE`
counterpart.
:param name: name of the dictionary-like setting
:type name: string
"""
compbs = BaseSettings()
compbs.update(self[name + '_BASE'])
compbs.update(self[name])
return compbs

def getpriority(self, name):
"""
Return the current numerical priority value of a setting, or ``None`` if
the given ``name`` does not exist.
:param name: the setting name
:type name: string
"""
if name not in self:
return None
return self.attributes[name].priority

def maxpriority(self):
"""
Return the numerical value of the highest priority present throughout
all settings, or the numerical value for ``default`` from
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` if there are no settings
stored.
"""
if len(self) > 0:
return max(self.getpriority(name) for name in self)
else:
return get_settings_priority('default')

def __setitem__(self, name, value):
self.set(name, value)

def set(self, name, value, priority='project'):
"""
Store a key/value attribute with a given priority.
Settings should be populated *before* configuring the Crawler object
(through the :meth:`~scrapy.crawler.Crawler.configure` method),
otherwise they won't have any effect.
:param name: the setting name
:type name: string
:param value: the value to associate with the setting
:type value: any
:param priority: the priority of the setting. Should be a key of
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
:type priority: string or int
"""
self._assert_mutability()
priority = get_settings_priority(priority)
if name not in self:
if isinstance(value, SettingsAttribute):
self.attributes[name] = value
else:
self.attributes[name] = SettingsAttribute(value, priority)
else:
self.attributes[name].set(value, priority)

def setdict(self, values, priority='project'):
self.update(values, priority)

def setmodule(self, module, priority='project'):
"""
Store settings from a module with a given priority.
This is a helper function that calls
:meth:`~scrapy.settings.BaseSettings.set` for every globally declared
uppercase variable of ``module`` with the provided ``priority``.
:param module: the module or the path of the module
:type module: module object or string
:param priority: the priority of the settings. Should be a key of
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
:type priority: string or int
"""
self._assert_mutability()
if isinstance(module, six.string_types):
module = import_module(module)
for key in dir(module):
if key.isupper():
self.set(key, getattr(module, key), priority)

def update(self, values, priority='project'):
"""
Store key/value pairs with a given priority.
This is a helper function that calls
:meth:`~scrapy.settings.BaseSettings.set` for every item of ``values``
with the provided ``priority``.
If ``values`` is a string, it is assumed to be JSON-encoded and parsed
into a dict with ``json.loads()`` first. If it is a
:class:`~scrapy.settings.BaseSettings` instance, the per-key priorities
will be used and the ``priority`` parameter ignored. This allows
inserting/updating settings with different priorities with a single
command.
:param values: the settings names and values
:type values: dict or string or :class:`~scrapy.settings.BaseSettings`
:param priority: the priority of the settings. Should be a key of
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
:type priority: string or int
"""
self._assert_mutability()
if isinstance(values, six.string_types):
values = json.loads(values)
if values is not None:
if isinstance(values, BaseSettings):
for name, value in six.iteritems(values):
self.set(name, value, values.getpriority(name))
else:
for name, value in six.iteritems(values):
self.set(name, value, priority)

def delete(self, name, priority='project'):
self._assert_mutability()
priority = get_settings_priority(priority)
if priority >= self.getpriority(name):
del self.attributes[name]

def __delitem__(self, name):
self._assert_mutability()
del self.attributes[name]

def _assert_mutability(self):
if self.frozen:
raise TypeError("Trying to modify an immutable Settings object")

def copy(self):
"""
Make a deep copy of current settings.
This method returns a new instance of the :class:`Settings` class,
populated with the same values and their priorities.
Modifications to the new object won't be reflected on the original
settings.
"""
return copy.deepcopy(self)

def freeze(self):
"""
Disable further changes to the current settings.
After calling this method, the present state of the settings will become
immutable. Trying to change values through the :meth:`~set` method and
its variants won't be possible and will be alerted.
"""
self.frozen = True
def frozencopy(self):
"""
Return an immutable copy of the current settings.
Alias for a :meth:`~freeze` call in the object returned by :meth:`copy`.
"""
copy = self.copy()
copy.freeze()
return copy

def __iter__(self):
return iter(self.attributes)

def __len__(self):
return len(self.attributes)

def _to_dict(self):
return {k: (v._to_dict() if isinstance(v, BaseSettings) else v)
for k, v in six.iteritems(self)}

def copy_to_dict(self):
"""
Make a copy of current settings and convert to a dict.
This method returns a new dict populated with the same values
and their priorities as the current settings.
Modifications to the returned dict won't be reflected on the original
settings.
This method can be useful for example for printing settings
in Scrapy shell.
"""
settings = self.copy()
return settings._to_dict()

def _repr_pretty_(self, p, cycle):
if cycle:
p.text(repr(self))
else:
p.text(pformat(self.copy_to_dict()))


这些API的主要作用是用于在项目中导入或者设置setting.py的值。

scrapy是一个重型框架,但是在使用中却感觉很方面,只需要配置以下,写一点核心的代码,就可以实现高并发爬虫,这是得益于他的强大配置文件的机制,内置很多默认配置,同时还给用户提供了外在的配置,并解决其中的冲突,这是它强大的地方。


完整setting源码

import six
import json
import copy
from collections import MutableMapping
from importlib import import_module
from pprint import pformat

from . import default_settings


SETTINGS_PRIORITIES = {
    
'default'0,
    
'command'10,
    
'project'20,
    
'spider'30,
    
'cmdline'40,
}


def get_settings_priority(priority):
    
"""
    Small helper function that looks up a given string priority in the
    :attr:`~scrapy.settings.SETTINGS_PRIORITIES` dictionary and returns its
    numerical value, or directly returns a given numerical priority.
    """

    
if isinstance(priority, six.string_types):
        
return SETTINGS_PRIORITIES[priority]
    
else:
        
return priority


太多了,删减部分

def iter_default_settings():
    
"""Return the default settings as an iterator of (name, value) tuples"""
    
for name in dir(default_settings):
        
if name.isupper():
            
yield name, getattr(default_settings, name)


def overridden_settings(settings):
    
"""Return a dict of the settings that have been overridden"""
    
for name, defvalue in iter_default_settings():
        value = settings[name]
        
if not isinstance(defvalue, dict) and value != defvalue:
            
yield name, value



scrapy.settings.SETTINGS_PRIORITIES


设置了Scrapy中默认的优先级的键名和优先级值的字典。

每个项目定义一个设置入口点,为其提供标识的代码名称和整数优先级。在设置和检索Settings类中的值时,更高优先级优先于较小优先 级。

该值位于scrapy.settings中,默认值如下:

SETTINGS_PRIORITIES = {

        'default': 0,

        'command': 10,

        'project': 20,

        'spider': 30,

        'cmdline': 40,

            }


scrapy.settings.get_settings_priority(priority)

源码

def get_settings_priority(priority):
    """
    Small helper function that looks up a given string priority in the
    :attr:`~scrapy.settings.SETTINGS_PRIORITIES` dictionary and returns its
    numerical value, or directly returns a given numerical priority.
    """

    if isinstance(priority, six.string_types):
        return SETTINGS_PRIORITIES[priority]
    else:
        return priority


用于在SETTINGS_PRIORITIES字典中查找给定的字符串优先级 并返回其数值, 或直接返回给定的数字优先级。


class scrapy.settings.Settings(values = None,priority ='project' )


继承: scrapy.settings.BaseSettings,该对象存储用于配置内部组件的Scrapy设置,并可用于任何进一步的自定义。

它是BaseSettings的子类,支持所有 BaseSettings方法。此外,在实例化此类之后,新对象将具有已在内置设置引用中描述的全局默认设置。

class Settings(BaseSettings):
    """
    This object stores Scrapy settings for the configuration of internal
    components, and can be used for any further customization.

    It is a direct subclass and supports all methods of
    :class:`~scrapy.settings.BaseSettings`. Additionally, after instantiation
    of this class, the new object will have the global default settings
    described on :ref:`topics-settings-ref` already populated.
    """


    def __init__(self, values=None, priority='project'):
        # Do not pass kwarg values here. We don't want to promote user-defined
        # dicts, and we want to update, not replace, default dicts with the
        # values given by the user
        super(Settings, self).__init__()
        self.setmodule(default_settings, 'default')
        # Promote default dictionaries to BaseSettings instances for per-key
        # priorities
        for name, val in six.iteritems(self):
            if isinstance(val, dict):
                self.set(name, BaseSettings(val, 'default'), 'default')
        self.update(values, priority)


class scrapy.settings.BaseSettings(values = None,priority ='project' )


此类的实例表现得像字典,但存储优先级键值对,并且可以被锁定(即标记为不可变)。

键值条目可以在初始化时使用values 参数传递,并且它们将采用该priority级别(除非values已经是实例BaseSettings,在这种情况下将保留现有的优先级)。如果priority 参数是字符串,则将查找优先级名称 SETTINGS_PRIORITIES。否则,应提供特定的整数。


创建对象后,可以使用该set()方法加载或更新新设置,并可使用 字典的方括号表示法或get()实例的 方法及其值转换变体进行访问。请求存储密钥时,将检索具有最高优先级的值。


该类具有以下方法


copy()

制作当前设置的深层副本。

此方法返回类的新实例,其中Settings填充了相同的值及其优先级。

对新对象的修改不会反映在原始设置上。


copy_to_dict()

制作当前设置的副本并转换为字典。

此法返回一个新的dict,其中填充了与当前设置相同的值及其优先级。

对返回的dict的修改不会影响原始设置上。

此方法可用于例如在Scrapy shell中打印设置。


freeze()

禁用对当前设置的进一步更改。

调用此方法后,设置的当前状态将变为不可变。试图通过该set()方法及其变体更改值是不可能的,并将被警告。


frozencopy()

返回当前设置的不可变副本。

freeze()在返回的对象中调用的别名copy()。


get(name,default=None)

    获取设置值而不影响其原始类型。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getbool(name,default = False )

获取设置值作为布尔值。

1,'1',TRUE、'True'返回True,同时0,'0',False,'False'、None返回False。

例如,通过设置为的环境变量填充的设置 '0'将False在使用此方法时返回。

参数:

name(字符串) - 设置名称

default(any) - 如果未找到设置则返回的值


getdict(name,default=None)

获取设置值作为字典。

如果设置原始类型是字典,则将返回其副本。如果它是一个字符串,它将被转化为为JSON字典。如果它是一个 BaseSettings实例本身,它将被转换为一个字典,包含它们将返回的所有当前设置值get(),并丢失有关优先级和可变性的所有信息。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getfloat(name,default= 0.0 )

    获取设置值作为浮点数。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getint(name,default= 0 )

    获取设置值作为int。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getlist(name,default=None)

    获取设置值作为列表。如果设置原始类型是列表,则将返回其副本。如果它是一个字符串,它将被“,”拆分。

    例如,通过设置为的环境变量填充的设置 'one,two'将在使用此方法时返回列表['one','two']。

    参数:

    name(字符串) - 设置名称

    default(any) - 如果未找到设置则返回的值


getpriority(name)

    返回设置的当前数字优先级值,或者None如果给定的name不存在。

    参数:name(字符串) - 设置名称


getwithbase(名字)

    获得类似字典的设置及其_BASE 对应的组合。

    参数: name(字符串) - 类字典设置的名称


maxpriority()

返回所有设置中存在的最高优先级的数值,或者如果没有存储设置则返回defaultfrom 的数值SETTINGS_PRIORITIES。


set(name,value,priority='project' )

设置给定优先级的键/值属性。

在配置Crawler对象(通过configure()方法)之前应该填充设置,否则它们将不起作用。

参数:

name(字符串) - 设置名称

value(any) - 与设置关联的值

priority(字符串或整数) - 设置的优先级。应该是一个键 SETTINGS_PRIORITIES或整数


setmodule(modulepriority='project' )

存储具有给定优先级的模块的设置。

这是一个辅助函数,它使用提供的函数调用 set()每个全局声明的大写变量。modulepriority

参数:

module(模块对象或字符串) - 模块或模块的路径

priority(字符串或整数) - 设置的优先级。应该是一个键 SETTINGS_PRIORITIES或整数


update(values,priority ='project' )

存储具有给定优先级的键/值对。

这是一个辅助函数调用 set()为每一个项目values 与所提供的priority。

如果values是字符串,则假定它是JSON编码的并且首先解析为dict json.loads()。如果是 BaseSettings实例,将使用每个键的优先级并priority忽略该参数。这允许使用单个命令插入/更新具有不同优先级的设置。

参数:

values(dict或string或BaseSettings) - 设置名称和值

priority(字符串或整数) - 设置的优先级。应该是一个键 SETTINGS_PRIORITIES或整数


scrapy.settings.BaseSettings完整源码及其方法如下:

class BaseSettings(MutableMapping):
"""
Instances of this class behave like dictionaries, but store priorities
along with their ``(key, value)`` pairs, and can be frozen (i.e. marked
immutable).
Key-value entries can be passed on initialization with the ``values``
argument, and they would take the ``priority`` level (unless ``values`` is
already an instance of :class:`~scrapy.settings.BaseSettings`, in which
case the existing priority levels will be kept). If the ``priority``
argument is a string, the priority name will be looked up in
:attr:`~scrapy.settings.SETTINGS_PRIORITIES`. Otherwise, a specific integer
should be provided.
Once the object is created, new settings can be loaded or updated with the
:meth:`~scrapy.settings.BaseSettings.set` method, and can be accessed with
the square bracket notation of dictionaries, or with the
:meth:`~scrapy.settings.BaseSettings.get` method of the instance and its
value conversion variants. When requesting a stored key, the value with the
highest priority will be retrieved.
"""
def __init__(self, values=None, priority='project'):
self.frozen = False
self.attributes = {}
self.update(values, priority)

def __getitem__(self, opt_name):
if opt_name not in self:
return None
return self.attributes[opt_name].value

def __contains__(self, name):
return name in self.attributes

def get(self, name, default=None):
"""
Get a setting value without affecting its original type.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
return self[name] if self[name] is not None else default

def getbool(self, name, default=False):
"""
Get a setting value as a boolean.
``1``, ``'1'``, `True`` and ``'True'`` return ``True``,
while ``0``, ``'0'``, ``False``, ``'False'`` and ``None`` return ``False``.
For example, settings populated through environment variables set to
``'0'`` will return ``False`` when using this method.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
got = self.get(name, default)
try:
return bool(int(got))
except ValueError:
if got in ("True", "true"):
return True
if got in ("False", "false"):
return False
raise ValueError("Supported values for boolean settings "
"are 0/1, True/False, '0'/'1', "
"'True'/'False' and 'true'/'false'")

def getint(self, name, default=0):
"""
Get a setting value as an int.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
return int(self.get(name, default))

def getfloat(self, name, default=0.0):
"""
Get a setting value as a float.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
return float(self.get(name, default))

def getlist(self, name, default=None):
"""
Get a setting value as a list. If the setting original type is a list, a
copy of it will be returned. If it's a string it will be split by ",".
For example, settings populated through environment variables set to
``'one,two'`` will return a list ['one', 'two'] when using this method.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
value = self.get(name, default or [])
if isinstance(value, six.string_types):
value = value.split(',')
return list(value)

def getdict(self, name, default=None):
"""
Get a setting value as a dictionary. If the setting original type is a
dictionary, a copy of it will be returned. If it is a string it will be
evaluated as a JSON dictionary. In the case that it is a
:class:`~scrapy.settings.BaseSettings` instance itself, it will be
converted to a dictionary, containing all its current settings values
as they would be returned by :meth:`~scrapy.settings.BaseSettings.get`,
and losing all information about priority and mutability.
:param name: the setting name
:type name: string
:param default: the value to return if no setting is found
:type default: any
"""
value = self.get(name, default or {})
if isinstance(value, six.string_types):
value = json.loads(value)
return dict(value)

def getwithbase(self, name):
"""Get a composition of a dictionary-like setting and its `_BASE`
counterpart.
:param name: name of the dictionary-like setting
:type name: string
"""
compbs = BaseSettings()
compbs.update(self[name + '_BASE'])
compbs.update(self[name])
return compbs

def getpriority(self, name):
"""
Return the current numerical priority value of a setting, or ``None`` if
the given ``name`` does not exist.
:param name: the setting name
:type name: string
"""
if name not in self:
return None
return self.attributes[name].priority

def maxpriority(self):
"""
Return the numerical value of the highest priority present throughout
all settings, or the numerical value for ``default`` from
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` if there are no settings
stored.
"""
if len(self) > 0:
return max(self.getpriority(name) for name in self)
else:
return get_settings_priority('default')

def __setitem__(self, name, value):
self.set(name, value)

def set(self, name, value, priority='project'):
"""
Store a key/value attribute with a given priority.
Settings should be populated *before* configuring the Crawler object
(through the :meth:`~scrapy.crawler.Crawler.configure` method),
otherwise they won't have any effect.
:param name: the setting name
:type name: string
:param value: the value to associate with the setting
:type value: any
:param priority: the priority of the setting. Should be a key of
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
:type priority: string or int
"""
self._assert_mutability()
priority = get_settings_priority(priority)
if name not in self:
if isinstance(value, SettingsAttribute):
self.attributes[name] = value
else:
self.attributes[name] = SettingsAttribute(value, priority)
else:
self.attributes[name].set(value, priority)

def setdict(self, values, priority='project'):
self.update(values, priority)

def setmodule(self, module, priority='project'):
"""
Store settings from a module with a given priority.
This is a helper function that calls
:meth:`~scrapy.settings.BaseSettings.set` for every globally declared
uppercase variable of ``module`` with the provided ``priority``.
:param module: the module or the path of the module
:type module: module object or string
:param priority: the priority of the settings. Should be a key of
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
:type priority: string or int
"""
self._assert_mutability()
if isinstance(module, six.string_types):
module = import_module(module)
for key in dir(module):
if key.isupper():
self.set(key, getattr(module, key), priority)

def update(self, values, priority='project'):
"""
Store key/value pairs with a given priority.
This is a helper function that calls
:meth:`~scrapy.settings.BaseSettings.set` for every item of ``values``
with the provided ``priority``.
If ``values`` is a string, it is assumed to be JSON-encoded and parsed
into a dict with ``json.loads()`` first. If it is a
:class:`~scrapy.settings.BaseSettings` instance, the per-key priorities
will be used and the ``priority`` parameter ignored. This allows
inserting/updating settings with different priorities with a single
command.
:param values: the settings names and values
:type values: dict or string or :class:`~scrapy.settings.BaseSettings`
:param priority: the priority of the settings. Should be a key of
:attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
:type priority: string or int
"""
self._assert_mutability()
if isinstance(values, six.string_types):
values = json.loads(values)
if values is not None:
if isinstance(values, BaseSettings):
for name, value in six.iteritems(values):
self.set(name, value, values.getpriority(name))
else:
for name, value in six.iteritems(values):
self.set(name, value, priority)

def delete(self, name, priority='project'):
self._assert_mutability()
priority = get_settings_priority(priority)
if priority >= self.getpriority(name):
del self.attributes[name]

def __delitem__(self, name):
self._assert_mutability()
del self.attributes[name]

def _assert_mutability(self):
if self.frozen:
raise TypeError("Trying to modify an immutable Settings object")

def copy(self):
"""
Make a deep copy of current settings.
This method returns a new instance of the :class:`Settings` class,
populated with the same values and their priorities.
Modifications to the new object won't be reflected on the original
settings.
"""
return copy.deepcopy(self)

def freeze(self):
"""
Disable further changes to the current settings.
After calling this method, the present state of the settings will become
immutable. Trying to change values through the :meth:`~set` method and
its variants won't be possible and will be alerted.
"""
self.frozen = True
def frozencopy(self):
"""
Return an immutable copy of the current settings.
Alias for a :meth:`~freeze` call in the object returned by :meth:`copy`.
"""
copy = self.copy()
copy.freeze()
return copy

def __iter__(self):
return iter(self.attributes)

def __len__(self):
return len(self.attributes)

def _to_dict(self):
return {k: (v._to_dict() if isinstance(v, BaseSettings) else v)
for k, v in six.iteritems(self)}

def copy_to_dict(self):
"""
Make a copy of current settings and convert to a dict.
This method returns a new dict populated with the same values
and their priorities as the current settings.
Modifications to the returned dict won't be reflected on the original
settings.
This method can be useful for example for printing settings
in Scrapy shell.
"""
settings = self.copy()
return settings._to_dict()

def _repr_pretty_(self, p, cycle):
if cycle:
p.text(repr(self))
else:
p.text(pformat(self.copy_to_dict()))


这些API的主要作用是用于在项目中导入或者设置setting.py的值。


相关文章
|
数据采集 API Python
scrapy爬虫加载API,配置自定义加载模块
当我们在scrapy中写了几个爬虫程序之后,他们是怎么被检索出来的,又是怎么被加载的?这就涉及到爬虫加载的API,今天我们就来分享爬虫加载过程及其自定义加载程序。 SpiderLoader API  该API是爬虫实例化API,主要实现一个类SpiderLoader class scrapy.loader.SpiderLoader 该类负责检索和处理项目中定义的spider类。
1351 0
|
1月前
|
数据采集 存储 JSON
Python网络爬虫:Scrapy框架的实战应用与技巧分享
【10月更文挑战第27天】本文介绍了Python网络爬虫Scrapy框架的实战应用与技巧。首先讲解了如何创建Scrapy项目、定义爬虫、处理JSON响应、设置User-Agent和代理,以及存储爬取的数据。通过具体示例,帮助读者掌握Scrapy的核心功能和使用方法,提升数据采集效率。
113 6
|
2月前
|
数据采集 中间件 开发者
Scrapy爬虫框架-自定义中间件
Scrapy爬虫框架-自定义中间件
64 1
|
2月前
|
数据采集 中间件 Python
Scrapy爬虫框架-通过Cookies模拟自动登录
Scrapy爬虫框架-通过Cookies模拟自动登录
120 0
|
1月前
|
数据采集 前端开发 中间件
Python网络爬虫:Scrapy框架的实战应用与技巧分享
【10月更文挑战第26天】Python是一种强大的编程语言,在数据抓取和网络爬虫领域应用广泛。Scrapy作为高效灵活的爬虫框架,为开发者提供了强大的工具集。本文通过实战案例,详细解析Scrapy框架的应用与技巧,并附上示例代码。文章介绍了Scrapy的基本概念、创建项目、编写简单爬虫、高级特性和技巧等内容。
81 4
|
1月前
|
数据采集 中间件 API
在Scrapy爬虫中应用Crawlera进行反爬虫策略
在Scrapy爬虫中应用Crawlera进行反爬虫策略
|
7月前
|
数据采集 中间件 Python
Scrapy爬虫:利用代理服务器爬取热门网站数据
Scrapy爬虫:利用代理服务器爬取热门网站数据
|
2月前
|
数据采集 中间件 数据挖掘
Scrapy 爬虫框架(一)
Scrapy 爬虫框架(一)
58 0
|
2月前
|
数据采集 XML 前端开发
Scrapy 爬虫框架(二)
Scrapy 爬虫框架(二)
52 0
|
4月前
|
数据采集 中间件 调度
Scrapy 爬虫框架的基本使用
Scrapy 爬虫框架的基本使用