天天看點

scrapy配置檔案操作核心API解讀

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(),并丢失有關優先級和可變性的所有資訊。

getfloat(name,default= 0.0 )

    擷取設定值作為浮點數。

getint(name,default= 0 )

    擷取設定值作為int。

getlist(name,default=None)

    擷取設定值作為清單。如果設定原始類型是清單,則将傳回其副本。如果它是一個字元串,它将被“,”拆分。

    例如,通過設定為的環境變量填充的設定 'one,two'将在使用此方法時傳回清單['one','two']。

getpriority(name)

    傳回設定的目前數字優先級值,或者None如果給定的name不存在。

    參數:name(字元串) - 設定名稱

getwithbase(名字)

    獲得類似字典的設定及其_BASE 對應的組合。

    參數: name(字元串) - 類字典設定的名稱

maxpriority()

傳回所有設定中存在的最高優先級的數值,或者如果沒有存儲設定則傳回defaultfrom 的數值SETTINGS_PRIORITIES。

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

設定給定優先級的鍵/值屬性。

在配置Crawler對象(通過configure()方法)之前應該填充設定,否則它們将不起作用。

value(any) - 與設定關聯的值

priority(字元串或整數) - 設定的優先級。應該是一個鍵 SETTINGS_PRIORITIES或整數

setmodule(module, priority='project' )

存儲具有給定優先級的子產品的設定。

這是一個輔助函數,它使用提供的函數調用 set()每個全局聲明的大寫變量。modulepriority

module(子產品對象或字元串) - 子產品或子產品的路徑

update(values,priority ='project' )

存儲具有給定優先級的鍵/值對。

這是一個輔助函數調用 set()為每一個項目values 與所提供的priority。

如果values是字元串,則假定它是JSON編碼的并且首先解析為dict json.loads()。如果是 BaseSettings執行個體,将使用每個鍵的優先級并priority忽略該參數。這允許使用單個指令插入/更新具有不同優先級的設定。

values(dict或string或BaseSettings) - 設定名稱和值

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是一個重型架構,但是在使用中卻感覺很方面,隻需要配置以下,寫一點核心的代碼,就可以實作高并發爬蟲,這是得益于他的強大配置檔案的機制,内置很多預設配置,同時還給使用者提供了外在的配置,并解決其中的沖突,這是它強大的地方。

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
           
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
           
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 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()))