1. # 这里引入了redis模块,这个是redis-python库的接口,用于通过python访问redis数据库,
    2. # 这个文件主要是实现连接redis数据库的功能,这些连接接口在其他文件中经常被用到
    3. import redis
    4. import six
    5. from scrapy.utils.misc import load_object
    6. DEFAULT_REDIS_CLS = redis.StrictRedis
    7. # 可以在settings文件中配置套接字的超时时间、等待时间等
    8. # Sane connection defaults.
    9. DEFAULT_PARAMS = {
    10. 'socket_timeout': 30,
    11. 'socket_connect_timeout': 30,
    12. 'retry_on_timeout': True,
    13. }
    14. # 要想连接到redis数据库,和其他数据库差不多,
    15. # 需要一个ip地址、端口号、用户名密码(可选)和一个整形的数据库编号
    16. # Shortcut maps 'setting name' -> 'parmater name'.
    17. SETTINGS_PARAMS_MAP = {
    18. 'REDIS_URL': 'url',
    19. 'REDIS_HOST': 'host',
    20. 'REDIS_PORT': 'port',
    21. }
    22. def get_redis_from_settings(settings):
    23. """Returns a redis client instance from given Scrapy settings object.
    24. This function uses ``get_client`` to instantiate the client and uses
    25. ``DEFAULT_PARAMS`` global as defaults values for the parameters. You can
    26. override them using the ``REDIS_PARAMS`` setting.
    27. Parameters
    28. ----------
    29. settings : Settings
    30. A scrapy settings object. See the supported settings below.
    31. Returns
    32. -------
    33. server
    34. Redis client instance.
    35. Other Parameters
    36. ----------------
    37. REDIS_URL : str, optional
    38. Server connection URL.
    39. REDIS_HOST : str, optional
    40. Server host.
    41. REDIS_PORT : str, optional
    42. Server port.
    43. REDIS_PARAMS : dict, optional
    44. Additional client parameters.
    45. """
    46. params = DEFAULT_PARAMS.copy()
    47. params.update(settings.getdict('REDIS_PARAMS'))
    48. # XXX: Deprecate REDIS_* settings.
    49. for source, dest in SETTINGS_PARAMS_MAP.items():
    50. val = settings.get(source)
    51. if val:
    52. params[dest] = val
    53. # Allow ``redis_cls`` to be a path to a class.
    54. if isinstance(params.get('redis_cls'), six.string_types):
    55. params['redis_cls'] = load_object(params['redis_cls'])
    56. # 返回的是redis库的Redis对象,可以直接用来进行数据操作的对象
    57. return get_redis(**params)
    58. # Backwards compatible alias.
    59. from_settings = get_redis_from_settings
    60. def get_redis(**kwargs):
    61. """Returns a redis client instance.
    62. Parameters
    63. ----------
    64. redis_cls : class, optional
    65. Defaults to ``redis.StrictRedis``.
    66. url : str, optional
    67. If given, ``redis_cls.from_url`` is used to instantiate the class.
    68. **kwargs
    69. Extra parameters to be passed to the ``redis_cls`` class.
    70. Returns
    71. -------
    72. server
    73. Redis client instance.
    74. """
    75. redis_cls = kwargs.pop('redis_cls', DEFAULT_REDIS_CLS)
    76. url = kwargs.pop('url', None)
    77. if url:
    78. return redis_cls.from_url(url, **kwargs)
    79. else:
    80. return redis_cls(**kwargs)
    81. connection.py