Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·55 lines (46 loc) · 2.04 KB
/
Copy pathrun.py
File metadata and controls
executable file
·55 lines (46 loc) · 2.04 KB
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
#!/usr/bin/env python3
"""Run the hosted Actor and print its dataset as JSON."""
import argparse
import json
import os
from pathlib import Path
from urllib.error import URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener
DEFAULT_INPUT = Path(__file__).resolve().parents[1] / "input.json"
ENDPOINT = "https://api.apify.com/v2/acts/deepmine~reddit-scraper/run-sync-get-dataset-items?timeout=240&maxTotalChargeUsd=0.10"
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def run_actor(payload, token, *, endpoint=ENDPOINT):
request = Request(
endpoint,
data=json.dumps(payload, allow_nan=False).encode(),
headers={"Content-Type": "application/json", "Accept": "application/json"},
method="POST",
)
request.add_unredirected_header("Authorization", f"Bearer {token}")
with build_opener(NoRedirect()).open(request, timeout=310) as response:
items = json.load(response)
if not isinstance(items, list):
raise TypeError("Apify did not return a dataset array")
return items
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dry-run", action="store_true", help="Print the JSON input without an API call")
parser.add_argument("input", type=Path, nargs="?", default=DEFAULT_INPUT)
args = parser.parse_args()
try:
payload = json.loads(args.input.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise TypeError("Actor input must be a JSON object")
if args.dry_run:
print(json.dumps(payload, indent=2, allow_nan=False))
return
token = os.environ.get("APIFY_TOKEN")
if not token:
parser.error("Set APIFY_TOKEN to run the Actor")
print(json.dumps(run_actor(payload, token), indent=2, ensure_ascii=False))
except (OSError, URLError, TypeError, ValueError) as err:
parser.exit(1, f"Run failed: {err}\n")
if __name__ == "__main__":
main()