File size: 1,931 Bytes
936253d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
from typing import Any, Dict, Iterable, Optional

from apify_client import ApifyClient
from dotenv import load_dotenv

load_dotenv()

client: Optional[ApifyClient] = None


def create_client() -> ApifyClient:
    """Create or return the shared Apify client connection."""
    global client
    if client is None:
        token = os.getenv("APIFY_API_TOKEN")
        if not token:
            raise RuntimeError(
                "APIFY_API_TOKEN is not set. Add it to your environment or .env file."
            )
        client = ApifyClient(token)
    return client


class BaseClient:
    """Common Apify client wrapper for actor-based scrapers."""

    actor_id: str = ""

    def __init__(
        self,
        client: Optional[ApifyClient] = None,
        actor_id: Optional[str] = None,
        default_run_input: Optional[Dict[str, Any]] = None,
    ) -> None:
        self.client = client if client is not None else create_client()
        self.actor_id = actor_id or self.actor_id
        self.default_run_input = default_run_input or {}

    def build_run_input(self, run_input: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        combined_input = dict(self.default_run_input)
        if run_input:
            combined_input.update(run_input)
        return combined_input

    def run(self, run_input: Optional[Dict[str, Any]] = None) -> Iterable[Dict[str, Any]]:
        if not self.actor_id:
            raise NotImplementedError("No Apify actor is configured for this scraper.")

        actor_input = self.build_run_input(run_input)
        run = self.client.actor(self.actor_id).call(run_input=actor_input)
        if run.status != "SUCCEEDED":
            raise RuntimeError(f"Actor run failed with status: {run.status}")

        dataset_id = run.default_dataset_id
        if not dataset_id:
            return []

        return list(self.client.dataset(dataset_id).iterate_items())