Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add CRAWL_ONCE_RESET setting #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ Settings
(False by default). When True, all requests are handled by
this middleware unless disabled explicitly using
``request.meta['crawl_once'] = False``.
* ``CRAWL_ONCE_RESET`` - reset the state, clearing out all seen requests
Default is False.

Alternatives
------------
Expand Down
11 changes: 9 additions & 2 deletions scrapy_crawl_once/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,18 @@ class CrawlOnceMiddleware(object):
(False by default). When True, all requests are handled by
this middleware unless disabled explicitly using
``request.meta['crawl_once'] = False``.
* ``CRAWL_ONCE_RESET`` - reset the state, clearing out all seen requests
Default is False.

This middleware puts all requests to the Scheduler, and then filters
them out at Downloader.
"""

def __init__(self, path, stats, default):
def __init__(self, path, stats, default, reset=False):
self.path = path
self.stats = stats
self.default = default
self.reset = reset

@classmethod
def from_crawler(cls, crawler):
Expand All @@ -69,13 +72,17 @@ def from_crawler(cls, crawler):
path = data_path(s.get('CRAWL_ONCE_PATH', 'crawl_once'),
createdir=True)
default = s.getbool('CRAWL_ONCE_DEFAULT', default=False)
o = cls(path, crawler.stats, default)
reset = s.getbool('CRAWL_ONCE_RESET', default=False)
o = cls(path, crawler.stats, default, reset)
crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
crawler.signals.connect(o.spider_closed, signal=signals.spider_closed)
return o

def spider_opened(self, spider):
self.db, dbpath = self._spider_db(spider)
reset = self.reset or getattr(spider, 'crawl_once_reset', False)
if reset:
self.db.clear()
num_records = len(self.db)
logger.info("Opened crawl database %r with %d existing records" % (
dbpath, num_records
Expand Down