1

Scrapy の統計ミドルウェアを変更しようとしています。

完全な Scrapy の stats.py は次のとおりです。

from scrapy.exceptions import NotConfigured
from scrapy.utils.request import request_httprepr
from scrapy.utils.response import response_httprepr

class DownloaderStats(object):

    def __init__(self, stats):
        self.stats = stats

    @classmethod
    def from_crawler(cls, crawler):
        if not crawler.settings.getbool('DOWNLOADER_STATS'):
            raise NotConfigured
        return cls(crawler.stats)

    def process_request(self, request, spider):
        self.stats.inc_value('downloader/request_count', spider=spider)
        self.stats.inc_value('downloader/request_method_count/%s' % request.method, spider=spider)
        reqlen = len(request_httprepr(request))
        self.stats.inc_value('downloader/request_bytes', reqlen, spider=spider)

    def process_response(self, request, response, spider):
        self.stats.inc_value('downloader/response_count', spider=spider)
        self.stats.inc_value('downloader/response_status_count/%s' % response.status, spider=spider)
        reslen = len(response_httprepr(response))
        self.stats.inc_value('downloader/response_bytes', reslen, spider=spider)
        return response

    def process_exception(self, request, exception, spider):
        ex_class = "%s.%s" % (exception.__class__.__module__, exception.__class__.__name__)
        self.stats.inc_value('downloader/exception_count', spider=spider)
        self.stats.inc_value('downloader/exception_type_count/%s' % ex_class, spider=spider)

from_crawlerclassmethod で渡されるのは、正確には何ですか?

4

1 に答える 1

2

まず、DownloaderStats(object)DownloaderStats にオブジェクトが渡されるという意味ではなく、DownloaderStats クラスがクラスを拡張するという意味ですobject

クラス メソッドでclsは、 が呼び出されるクラスです。この場合はDownloaderStatsです。したがって、このコードは、クラス DownloaderStats のオブジェクトをインスタンス化するcls(crawler.stats)と考えることができます。DownloaderStats(crawler.stats)Python でオブジェクトをインスタンス化すると、その__init__メソッドが呼び出されるため、 の値がメソッドのパラメーターにcrawler.stats割り当てられ、メソッドのstatsパラメーターが に割り当てられます。__init__self.stats

于 2013-08-27T22:58:22.057 に答える