V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Yc1992
V2EX  ›  Python

为什么 scrapy middleware 使用 from_crawler 来初始化一个 middleware

  •  
  •   Yc1992 ·
    bufrr · 2016-02-21 15:19:45 +08:00 · 2784 次点击
    这是一个创建于 2997 天前的主题,其中的信息可能已经有所发展或是发生改变。

    例如:

    class CookiesMiddleware(object):
        """This middleware enables working with sites that need cookies"""
    
        def __init__(self, debug=False):
            self.jars = defaultdict(CookieJar)
            self.debug = debug
    
        @classmethod
        def from_crawler(cls, crawler):
            if not crawler.settings.getbool('COOKIES_ENABLED'):
                raise NotConfigured
            return cls(crawler.settings.getbool('COOKIES_DEBUG'))
    

    为什么不可以直接在init中使用 crawler 进行初始化呢,这样做有什么好处?

    1 条回复    2016-02-21 18:07:20 +08:00
    rebornix
        1
    rebornix  
       2016-02-21 18:07:20 +08:00
    你看下初始化 middleware 的代码 https://github.com/scrapy/scrapy/blob/6660175de9abddaf29be2b5f74e3f04a389618bf/scrapy/middleware.py#L33

    mwcls = load_object(clspath)
    if crawler and hasattr(mwcls, 'from_crawler'):
    mw = mwcls.from_crawler(crawler)
    elif hasattr(mwcls, 'from_settings'):
    mw = mwcls.from_settings(settings)
    else:
    mw = mwcls()
    middlewares.append(mw)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2597 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:50 · PVG 23:50 · LAX 08:50 · JFK 11:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.