Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Set up Django before importing mwmbl modules in the crawler

Daoud Clarke413ba7f5a8d1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1068d25..995d1d5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -66,6 +66,14 @@ jobs:
- name: Create test directories and files
run: |
mkdir -p /tmp/test_mwmbl_data
+ #----------------------------------------------
+ # The crawler container runs mwmbl-crawl with no DJANGO_SETTINGS_MODULE and no
+ # database - mwmbl.crawl configures Django itself. Import it with that environment
+ # (this step deliberately sets neither) so an import reaching Django models before
+ # django.setup() fails here rather than in the running container.
+ #----------------------------------------------
+ - name: Check the crawler entry point imports standalone
+ run: uv run python -c "from mwmbl.crawl import run"
- name: Run tests
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/test_mwmbl
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.py
index da79577..bf6a67d 100644
--- a/mwmbl/crawl.py
+++ b/mwmbl/crawl.py
@@ -11,17 +11,13 @@ import requests
from django.conf import settings
from redis import Redis
-from mwmbl.crawler.env_vars import CRAWLER_WORKERS, CRAWL_DELAY_SECONDS, MWMBL_API_KEY, MWMBL_CONTACT_INFO
-from mwmbl.rankeval.evaluation.remote_index import RemoteIndex
-from mwmbl.redis_url_queue import RedisURLQueue
-from mwmbl.tinysearchengine.indexer import TinyIndex, Document
-from mwmbl.tinysearchengine.rank import score_result
-from mwmbl.tokenizer import tokenize
-
FORMAT = "%(process)d:%(levelname)s:%(name)s:%(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)
+# The mwmbl imports below reach Django models, so the app registry has to be ready before
+# any of them run. The app registry creates the index on startup, so the data path has to
+# exist before that.
os.environ["DJANGO_SETTINGS_MODULE"] = "mwmbl.settings_crawler"
data_path = Path(settings.DATA_PATH)
@@ -32,10 +28,16 @@ print("Mwmbl crawling statistics: https://mwmbl.org/stats")
django.setup()
-from mwmbl.indexer.update_urls import record_urls_in_database
-from mwmbl.crawler.retrieve import crawl_batch, crawl_url, CRAWLER_VERSION, USER_AGENT
from mwmbl.crawler.batch import HashedBatch, Result, Results
+from mwmbl.crawler.env_vars import CRAWLER_WORKERS, CRAWL_DELAY_SECONDS, MWMBL_API_KEY, MWMBL_CONTACT_INFO
+from mwmbl.crawler.retrieve import crawl_batch, crawl_url, CRAWLER_VERSION, USER_AGENT
from mwmbl.indexer.index_batches import index_batches, index_pages
+from mwmbl.indexer.update_urls import record_urls_in_database
+from mwmbl.rankeval.evaluation.remote_index import RemoteIndex
+from mwmbl.redis_url_queue import RedisURLQueue
+from mwmbl.tinysearchengine.indexer import TinyIndex, Document
+from mwmbl.tinysearchengine.rank import score_result
+from mwmbl.tokenizer import tokenize
BATCH_QUEUE_KEY = "batch-queue"
REMOTE_SERVER = "https://api.mwmbl.org"
diff --git a/test/test_crawl_import_order.py b/test/test_crawl_import_order.py
new file mode 100644
index 0000000..85b102a
--- /dev/null
+++ b/test/test_crawl_import_order.py
@@ -0,0 +1,31 @@
+"""The standalone crawler has no database and no DJANGO_SETTINGS_MODULE in its environment.
+
+mwmbl.crawl sets the settings module and calls django.setup() itself, so every mwmbl import
+in it must come after that call - the mwmbl package reaches Django models (via
+curated_domains) and raises ImproperlyConfigured if the app registry is not ready.
+"""
+import ast
+from pathlib import Path
+
+CRAWL_PATH = Path(__file__).parent.parent / "mwmbl" / "crawl.py"
+
+
+def _django_setup_line(module: ast.Module) -> int:
+ for node in ast.walk(module):
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "setup" and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == "django"):
+ return node.lineno
+ raise AssertionError("mwmbl/crawl.py does not call django.setup()")
+
+
+def test_mwmbl_imports_come_after_django_setup():
+ module = ast.parse(CRAWL_PATH.read_text())
+ setup_line = _django_setup_line(module)
+
+ early_imports = [
+ node.module for node in module.body
+ if isinstance(node, ast.ImportFrom) and node.lineno < setup_line
+ and node.module is not None and node.module.startswith("mwmbl")
+ ]
+ assert early_imports == []