-
Notifications
You must be signed in to change notification settings - Fork 0
/
saver.py
143 lines (106 loc) · 3.73 KB
/
saver.py
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from functools import partial
from io import BytesIO
from threading import Thread
from typing import Iterable, Set, Mapping, Union, Callable
import aiofiles
import aioredis
import asyncio
import logging
import os
import tarfile
class ItemSaver(object):
_logger: logging.Logger
crawl_manager: 'CrawlManager'
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
# self.crawl_manager is set by the CrawlManager itself when it is initialized
async def save(self, item, response):
raise NotImplementedError()
async def close(self):
raise NotImplementedError()
class NullItemSaver(ItemSaver):
"""
An item saver that doesn't actually save anything.
Useful for just crawling for IDs.
"""
async def save(self, item, response):
pass
async def close(self):
pass
class RedisItemSaver(ItemSaver):
"""
An item saver that stores the response text into redis.
"""
_redis_address: str
crawl_manager: 'CrawlManager'
def __init__(self, redis_address: str):
super().__init__()
self._redis_address = redis_address
asyncio.get_event_loop().run_until_complete(self.async_init())
async def async_init(self):
self._redis = await aioredis.create_redis_pool(self._redis_address, minsize=1, maxsize=4)
def _keyname(self, item: str):
return f"{self.crawl_manager.name}_item_{item}"
async def save(self, item, response):
content = await response.read()
self._redis.set(self._keyname(item), content)
async def close(self):
self._redis.close()
await self._redis.wait_closed()
class FileItemSaver(ItemSaver):
"""
An ItemSaver that saves responses to files on disk.
"""
file_path_fmt: Union[str, Callable[[str], str]]
def __init__(self, file_path_fmt='{0}'):
super().__init__()
self.file_path_fmt = file_path_fmt
async def save(self, item, response):
content = await response.read()
if callable(self.file_path_fmt):
file_path = self.file_path_fmt(item)
else:
file_path = self.file_path_fmt.format(item)
dirs = os.path.dirname(file_path)
if dirs:
try:
if not os.path.exists(dirs):
os.makedirs(dirs)
except OSError:
pass
async with aiofiles.open(file_path, 'wb') as f:
await f.write(content)
async def close(self):
pass
class TarItemSaver(ItemSaver):
"""
An ItemSaver that saves items into a tar(.gz|.bz2) file
"""
tar_path: str
file_path_fmt: Union[str, Callable[[str], str]]
def __init__(self, tar_path, file_path_fmt='{0}'):
super().__init__()
self.tar_path = tar_path
self.file_path_fmt = file_path_fmt
compression = ''
if self.tar_path.endswith('gz'):
compression = ':gz'
elif self.tar_path.endswith('bz2'):
compression = ':bz2'
self._tarfile = tarfile.open(self.tar_path, 'w'+compression)
def _do_save(self, item: str, response, content: bytes):
bio = BytesIO()
bio.write(content)
bio.seek(0)
if callable(self.file_path_fmt):
file_path = self.file_path_fmt(item)
else:
file_path = self.file_path_fmt.format(item)
tinfo = tarfile.TarInfo(name=file_path)
tinfo.size = len(content)
self._tarfile.addfile(tarinfo=tinfo, fileobj=bio)
async def save(self, item, response):
content = await response.read()
await asyncio.get_event_loop().run_in_executor(None, partial(self._do_save, item, response, content))
async def close(self):
self._tarfile.close()