Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Multiprocess

Daoud Clarke2278b264a35f
diff --git a/crawl.py b/crawl.py
index cc98084..9b3ca9c 100644
--- a/crawl.py
+++ b/crawl.py
@@ -1,10 +1,12 @@
import logging
import os
import time
+from multiprocessing import Process
from pathlib import Path
import django
from django.conf import settings
+from redis import Redis
os.environ["DJANGO_SETTINGS_MODULE"] = "mwmbl.settings_crawler"
@@ -22,22 +24,58 @@ from mwmbl.crawler.batch import HashedBatch
from mwmbl.indexer.index_batches import index_batches
+logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
+BATCH_QUEUE_KEY = "batch-queue"
+
def run():
+ for i in range(10):
+ process = Process(target=process_batch_continuously())
+ process.start()
+
+ index_process = Process(target=run_indexing)
+ index_process.start()
+
+
+def process_batch_continuously():
+ while True:
+ try:
+ process_batch()
+ except Exception:
+ logger.exception("Error processing batch")
+ time.sleep(10)
+
+
+def process_batch():
user_id = "test"
urls = url_queue.get_batch(user_id)
results = crawl_batch(list(urls)[:10], 20)
for result in results:
print("Result", result)
-
js_timestamp = int(time.time() * 1000)
batch = HashedBatch.parse_obj({"user_id_hash": user_id, "timestamp": js_timestamp, "items": results})
record_urls_in_database([batch], url_queue)
index_path = data_path / settings.INDEX_NAME
+ redis = Redis(host='localhost', port=6379, decode_responses=True)
+ # Push the batch into the Redis queue
+ batch_json = batch.json()
+ redis.rpush(BATCH_QUEUE_KEY, batch_json)
- index_batches([batch], index_path)
+
+def run_indexing():
+ redis = Redis(host='localhost', port=6379, decode_responses=True)
+ index_path = data_path / settings.INDEX_NAME
+ while True:
+ batch_jsons = redis.lpop(BATCH_QUEUE_KEY, 1000)
+ logger.info(f"Got {len(batch_jsons)} batches to index")
+ if batch_jsons is None:
+ logger.info("No more batches to index. Sleeping for 10 seconds.")
+ time.sleep(10)
+ continue
+ batches = [HashedBatch.parse_raw(b) for b in batch_jsons]
+ index_batches(batches, index_path)
if __name__ == "__main__":