forked from alltheplaces/alltheplaces
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgolia.py
More file actions
73 lines (58 loc) · 2.49 KB
/
algolia.py
File metadata and controls
73 lines (58 loc) · 2.49 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from typing import Iterable
from scrapy import Spider
from scrapy.http import JsonRequest, Response
from locations.dict_parser import DictParser
from locations.items import Feature
class AlgoliaSpider(Spider):
"""
Documentation of the Algolia API is available at:
https://www.algolia.com/doc/rest-api/search/
To use this spider, specify the API key and application ID as sent in the
headers of a query request, as well as the name of the "index" found in
either the request URL or in query parameters in the request body.
Override post_process_item to extract attributes from each object.
Optionally set `referer` as the HTTP Referer header of the store search
page.
"""
dataset_attributes = {"source": "api", "api": "algolia"}
api_key: str = ""
app_id: str = ""
index_name: str = ""
myfilter: str | None = None
referer: str | None = None
def _make_request(self, page: int | None = None) -> JsonRequest:
params = "hitsPerPage=1000"
if self.myfilter is not None:
params += f"&filters={self.myfilter}"
if page is not None:
params += f"&page={page}"
headers = {"x-algolia-api-key": self.api_key, "x-algolia-application-id": self.app_id}
if self.referer is not None:
headers["Referer"] = self.referer
return JsonRequest(
url=f"https://{self.app_id}-dsn.algolia.net/1/indexes/*/queries",
headers=headers,
data={
"requests": [
{
"indexName": self.index_name,
"params": params,
}
],
},
)
def start_requests(self) -> Iterable[JsonRequest]:
yield self._make_request(None)
def parse(self, response: Response) -> Iterable[Feature | JsonRequest]:
result = response.json()["results"][0]
for feature in result["hits"]:
self.pre_process_data(feature)
item = DictParser.parse(feature)
yield from self.post_process_item(item, response, feature) or []
if result["page"] + 1 < result["nbPages"]:
yield self._make_request(result["page"] + 1)
def pre_process_data(self, location: dict) -> None:
"""Override with any pre-processing on the item."""
def post_process_item(self, item: Feature, response: Response, feature: dict) -> Iterable[Feature]:
"""Override with any post-processing on the item."""
yield item