An open source, non-profit web search engine
Factor out connection code
Daoud Clarkeb8b605daedd1
diff --git a/mwmbl/batches.py b/mwmbl/batches.pynew file mode 100644index 0000000..1026a34--- /dev/null+++ b/mwmbl/batches.py@@ -0,0 +1,3 @@+"""+Database interface for batches of crawled data.+"""diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex 583ffdb..ff5aa4b 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -13,6 +13,7 @@ from fastapi import HTTPException, APIRouterfrom pydantic import BaseModelfrom mwmbl.crawler.urls import URLDatabase+from mwmbl.database import DatabaseAPPLICATION_KEY = os.environ['MWMBL_APPLICATION_KEY']KEY_ID = os.environ['MWMBL_KEY_ID']@@ -81,8 +82,9 @@ last_batch = None@router.on_event("startup")async def on_startup():- with URLDatabase() as db:- return db.create_tables()+ with Database() as db:+ url_db = URLDatabase(db.connection)+ return url_db.create_tables()@router.post('/batches/')@@ -132,8 +134,9 @@ def _get_user_id_hash(batch: Union[Batch, NewBatchRequest]):def request_new_batch(batch_request: NewBatchRequest):user_id_hash = _get_user_id_hash(batch_request)- with URLDatabase() as db:- return db.get_new_batch_for_user(user_id_hash)+ with Database() as db:+ url_db = URLDatabase(db.connection)+ return url_db.get_new_batch_for_user(user_id_hash)@router.post('/batches/historical')@@ -147,17 +150,18 @@ def create_historical_batch(batch: HashedBatch):def _record_urls_in_database(batch: Union[Batch, HashedBatch], user_id_hash: str, timestamp: datetime):- with URLDatabase() as db:+ with Database() as db:+ url_db = URLDatabase(db.connection)found_urls = set()for item in batch.items:if item.content is not None:found_urls |= set(item.content.links)if len(found_urls) > 0:- db.user_found_urls(user_id_hash, list(found_urls), timestamp)+ url_db.user_found_urls(user_id_hash, list(found_urls), timestamp)crawled_urls = [item.url for item in batch.items]- db.user_crawled_urls(user_id_hash, crawled_urls, timestamp)+ url_db.user_crawled_urls(user_id_hash, crawled_urls, timestamp)@router.get('/batches/{date_str}/users/{public_user_id}')diff --git a/mwmbl/crawler/urls.py b/mwmbl/crawler/urls.pyindex f1be9ed..d96397b 100644--- a/mwmbl/crawler/urls.py+++ b/mwmbl/crawler/urls.py@@ -11,6 +11,8 @@ from psycopg2.extras import execute_values# Client has one hour to crawl a URL that has been assigned to them, or it will be reassigned+from mwmbl.database import Database+REASSIGN_MIN_HOURS = 1BATCH_SIZE = 100@@ -26,17 +28,8 @@ class URLStatus(Enum):class URLDatabase:- def __init__(self):- self.connection = None-- def __enter__(self):- self.connection = connect(os.environ["DATABASE_URL"])- self.connection.__enter__()- return self-- def __exit__(self, exc_type, exc_val, exc_tb):- self.connection.__exit__(exc_type, exc_val, exc_tb)- self.connection.close()+ def __init__(self, connection):+ self.connection = connectiondef create_tables(self):sql = """@@ -111,11 +104,12 @@ class URLDatabase:if __name__ == "__main__":- with URLDatabase() as db:- db.create_tables()+ with Database() as db:+ url_db = URLDatabase(db.connection)+ url_db.create_tables()# update_url_status(conn, [URLStatus("https://mwmbl.org", URLState.NEW, "test-user", datetime.now())])- # db.user_found_urls("Test user", ["a", "b", "c"], datetime.utcnow())- # db.user_found_urls("Another user", ["b", "c", "d"], datetime.utcnow())- # db.user_crawled_urls("Test user", ["c"], datetime.utcnow())- batch = db.get_new_batch_for_user('test user 4')+ # url_db.user_found_urls("Test user", ["a", "b", "c"], datetime.utcnow())+ # url_db.user_found_urls("Another user", ["b", "c", "d"], datetime.utcnow())+ # url_db.user_crawled_urls("Test user", ["c"], datetime.utcnow())+ batch = url_db.get_new_batch_for_user('test user 4')print("Batch", len(batch), batch)diff --git a/mwmbl/database.py b/mwmbl/database.pynew file mode 100644index 0000000..8886ca3--- /dev/null+++ b/mwmbl/database.py@@ -0,0 +1,17 @@+import os++from psycopg2 import connect+++class Database:+ def __init__(self):+ self.connection = None++ def __enter__(self):+ self.connection = connect(os.environ["DATABASE_URL"])+ self.connection.__enter__()+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ self.connection.__exit__(exc_type, exc_val, exc_tb)+ self.connection.close()diff --git a/mwmbl/indexer/batch.py b/mwmbl/indexer/batch.pydeleted file mode 100644index 86887ac..0000000--- a/mwmbl/indexer/batch.py+++ /dev/null@@ -1,10 +0,0 @@-from itertools import islice-from typing import Iterator---def grouper(n: int, iterator: Iterator):- while True:- chunk = tuple(islice(iterator, n))- if not chunk:- return- yield chunk\ No newline at end of filediff --git a/mwmbl/indexer/dedupe.py b/mwmbl/indexer/dedupe.pyindex 5a09f4d..26caba7 100644--- a/mwmbl/indexer/dedupe.py+++ b/mwmbl/indexer/dedupe.py@@ -4,8 +4,9 @@ Dedupe pages that have been crawled more than once and prepare them for indexingimport globimport gzipimport json+from itertools import islice+from typing import Iterator-from mwmbl.indexer.batch import grouperfrom mwmbl.indexer.fsqueue import FSQueue, GzipJsonBlobSerializerfrom mwmbl.indexer.paths import CRAWL_GLOB, TINYSEARCH_DATA_DIR@@ -40,3 +41,11 @@ def run():if __name__ == '__main__':run()+++def grouper(n: int, iterator: Iterator):+ while True:+ chunk = tuple(islice(iterator, n))+ if not chunk:+ return+ yield chunk\ No newline at end of file