forked from scrapinghub/python-scrapinghub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrapinghub.py
380 lines (306 loc) · 11.9 KB
/
scrapinghub.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
Scrapinghub API Client Library
"""
import os
import json
import logging
import socket
import time
import warnings
__all__ = ["APIError", "Connection"]
__version__ = '1.5.0'
logger = logging.getLogger('scrapinghub')
class Connection(object):
"""Main class to access Scrapinghub API.
"""
DEFAULT_ENDPOINT = 'https://dash.scrapinghub.com/api/'
API_METHODS = {
'addversion': 'scrapyd/addversion',
'listprojects': 'scrapyd/listprojects',
'jobs_count': 'jobs/count',
'jobs_list': 'jobs/list',
'jobs_update': 'jobs/update',
'jobs_stop': 'jobs/stop',
'jobs_delete': 'jobs/delete',
'eggs_add': 'eggs/add',
'eggs_delete': 'eggs/delete',
'eggs_list': 'eggs/list',
'as_project_slybot': 'as/project-slybot',
'as_spider_properties': 'as/spider-properties',
'schedule': 'schedule',
'items': 'items',
'log': 'log',
'spiders': 'spiders/list',
'reports_add': 'reports/add',
}
def __init__(self, apikey=None, password='', _old_passwd='', url=None):
if apikey is None:
apikey = os.environ.get('SH_APIKEY')
if apikey is None:
raise RuntimeError("No API key provided and SH_APIKEY environment variable not set")
assert not apikey.startswith('http://'), \
"Instantiating scrapinghub.Connection with url as first argument is not supported"
assert not password, \
"Authentication with user:pass is not supported, use your apikey instead"
self.apikey = apikey
self.url = url or self.DEFAULT_ENDPOINT
self._session = self._create_session()
def __repr__(self):
return "Connection(%r)" % self.apikey
@property
def auth(self):
warnings.warn("'auth' connection attribute is deprecated, "
"use 'apikey' attribute instead", stacklevel=2)
return (self.apikey, '')
def _create_session(self):
from requests import session
s = session()
s.auth = (self.apikey, '')
s.headers.update({
'User-Agent': 'python-scrapinghub/{0}'.format(__version__),
})
# For python-requests >= 1.x
s.stream = True
# For python-requests < 1.x
s.prefetch = False
return s
def _build_url(self, method, format):
"""Returns full url for given method and format"""
from requests.compat import urljoin
# TODO: verify method's format support
try:
base_path = self.API_METHODS[method]
except KeyError:
raise APIError("Unknown method: {0}".format(method))
else:
path = "{0}.{1}".format(base_path, format)
return urljoin(self.url, path)
def _get(self, method, format, params=None, headers=None, raw=False):
"""Performs GET request"""
from requests.compat import urlencode
url = self._build_url(method, format)
if params:
url = "{0}?{1}".format(url, urlencode(params, True))
return self._request(url, None, headers, format, raw)
def _post(self, method, format, params=None, headers=None, raw=False, files=None):
"""Performs POST request"""
url = self._build_url(method, format)
return self._request(url, params, headers, format, raw, files)
def _request(self, url, data, headers, format, raw, files=None):
"""Performs the request using and returns the content deserialized,
based on given `format`.
Available formats:
* json - Returns a json object and checks for errors
* jl - Returns a generator of json object per item
Raises APIError if json response have error status.
"""
if format not in ('json', 'jl') and not raw:
raise APIError("format must be either json or jl")
if data is None and files is None:
response = self._session.get(url, headers=headers)
else:
response = self._session.post(url, headers=headers,
data=data, files=files)
return self._decode_response(response, format, raw)
def _decode_response(self, response, format, raw):
if raw:
return response.raw
elif format == 'json':
data = json.loads(response.text)
# validate response
try:
if data['status'] == 'ok':
return data
elif data['status'] in ('error', 'badrequest'):
raise APIError(data['message'])
else:
raise APIError("Unknown response status: {0[status]}".format(data))
except KeyError:
raise APIError("JSON response does not contain status")
else: # jl
return (json.loads(line) for line in response.iter_lines())
##
## public methods
##
def __getitem__(self, key):
"""Returns `Project` instance for given key.
Does not verify if project exists.
"""
return Project(self, key)
def project_ids(self):
"""Returns a list of projects available for this connection and
crendentials.
"""
result = self._get('listprojects', 'json')
return result['projects']
def project_names(self):
warnings.warn("scrapinghub.Connection.project_names() method is deprecated, use project_ids() method instead", stacklevel=2)
return self.project_ids()
class RequestProxyMixin(object):
def _add_params(self, params):
return params
def _get(self, method, format, params=None, headers=None, raw=False):
params = self._add_params(params or {})
return self._request_proxy._get(method, format, params, headers, raw)
def _post(self, method, format, params=None, headers=None, raw=False, files=None):
params = self._add_params(params or {})
return self._request_proxy._post(method, format, params, headers, raw, files)
class Project(RequestProxyMixin):
def __init__(self, connection, projectid):
self.connection = connection
self.id = projectid
def __repr__(self):
return "Project({0.connection!r}, {0.id})".format(self)
@property
def name(self):
warnings.warn("Project.name is deprecated, use Project.id instead", stacklevel=2)
return self.id
def schedule(self, spider, **params):
params['spider'] = spider
result = self._post('schedule', 'json', params)
return result['jobid']
def jobs(self, **params):
return JobSet(self, **params)
def job(self, id):
try:
return iter(self.jobs(job=id, count=1)).next()
except StopIteration:
return None
def spiders(self, **params):
result = self._get('spiders', 'json', params)
return result['spiders']
@property
def _request_proxy(self):
return self.connection
def _add_params(self, params):
# force project param
params.update(project=self.id)
return params
def autoscraping_project_slybot(self, spiders=(), outputfile=None):
from shutil import copyfileobj
params = {}
if spiders:
params['spider'] = spiders
r = self._get('as_project_slybot', 'zip', params, raw=True)
return r if outputfile is None else copyfileobj(r, outputfile)
def autoscraping_spider_properties(self, spider, start_urls=None):
params = {'spider': spider}
if start_urls:
params['start_url'] = start_urls
return self._post('as_spider_properties', 'json', params)
return self._get('as_spider_properties', 'json', params)
class JobSet(RequestProxyMixin):
def __init__(self, project, **params):
self.project = project
self.params = params
# jobs one-shot iterator
self._jobs = None
def __repr__(self):
params = ', '.join("{0}={1}".format(*i) for i in self.params.iteritems())
return "JobSet({0.project!r}, {1})".format(self, params)
def __iter__(self):
self._load_jobs()
return (Job(self.project, info['id'], info) for info in self._jobs)
def count(self):
"""Returns total results count of current filters.
Does not inclue `count` neither `offset`.
"""
result = self._get('jobs_count', 'json')
return result['total']
def update(self, **modifiers):
params = self.params.copy()
params.update(modifiers)
result = self._post('jobs_update', 'json', params)
return result['count']
def stop(self):
for job in self:
job.stop()
def delete(self):
for job in self:
job.delete()
def _load_jobs(self):
# only load once
if self._jobs is None:
result = self._get('jobs_list', 'jl', self.params)
try:
status_line = result.next()
except StopIteration:
raise APIError("JSON response does not contain status")
else:
# jl status expected is only "ok"
status = status_line.get('status', '')
if status != 'ok':
raise APIError("Unknown response status: {0}".format(status))
self._jobs = result
@property
def _request_proxy(self):
return self.project
def _add_params(self, params):
# default to JobSet's params
params2 = self.params.copy()
# update with user params
params2.update(params)
return params2
class Job(RequestProxyMixin):
MAX_RETRIES = 180
RETRY_INTERVAL = 60
def __init__(self, project, id, info):
self.project = project
self._id = id
self.info = info
@property
def id(self):
return self._id
def __repr__(self):
return "Job({0.project!r}, {0.id})".format(self)
def items(self, offset=0, meta=None):
import requests
params = {}
if meta is not None:
params['meta'] = meta
lastexc = None
for attempt in xrange(self.MAX_RETRIES):
params['offset'] = offset
try:
for item in self._get('items', 'jl', params=params):
yield item
offset += 1
break
except (ValueError, socket.error, requests.RequestException) as exc:
lastexc = exc
msg = "Retrying read of items.jl in %ds: project=%s job=%s offset=%d attempt=%d/%d error=%s"
args = (self.RETRY_INTERVAL, self.project, self._id, offset, attempt, self.MAX_RETRIES, exc)
logger.debug(msg, *args)
time.sleep(self.RETRY_INTERVAL)
else:
logger.error('Failed %d times reading items from %s, last error was: %s', self.MAX_RETRIES, self._id, lastexc)
def update(self, **modifiers):
# XXX: only allow add_tag/remove_tag
result = self._post('jobs_update', 'json', modifiers)
return result['count']
def stop(self):
result = self._post('jobs_stop', 'json')
return result['status'] == 'ok'
def delete(self):
result = self._post('jobs_delete', 'json')
return result['count']
def add_report(self, key, content, content_type='text/plain'):
from requests.compat import StringIO
params = {
'project': self.project.id,
'job': self.id,
'key': key,
'content_type': content_type,
}
files = {'content': ('report', StringIO(content))}
self._post('reports_add', 'json', params, files=files)
def log(self, **params):
return self._get('log', 'jl', params)
@property
def _request_proxy(self):
return self.project
def _add_params(self, params):
params['job'] = self.id
return params
class APIError(Exception):
pass