-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtask.py
More file actions
599 lines (520 loc) · 25.5 KB
/
Copy pathtask.py
File metadata and controls
599 lines (520 loc) · 25.5 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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
from __future__ import annotations
import json as jsonlib
from typing import TYPE_CHECKING, Any, cast
from apify_client._utils import (
catch_not_found_or_throw,
encode_webhook_list_to_base64,
filter_out_none_values_recursively,
maybe_extract_enum_member_value,
parse_date_fields,
pluck_data,
)
from apify_client.clients.base import ResourceClient, ResourceClientAsync
from apify_client.clients.resource_clients.run import RunClient, RunClientAsync
from apify_client.clients.resource_clients.run_collection import RunCollectionClient, RunCollectionClientAsync
from apify_client.clients.resource_clients.webhook_collection import (
WebhookCollectionClient,
WebhookCollectionClientAsync,
)
from apify_client.errors import ApifyApiError
if TYPE_CHECKING:
from apify_shared.consts import ActorJobStatus, MetaOrigin
def get_task_representation(
actor_id: str | None = None,
name: str | None = None,
task_input: dict | None = None,
build: str | None = None,
max_items: int | None = None,
memory_mbytes: int | None = None,
timeout_secs: int | None = None,
restart_on_error: bool | None = None,
title: str | None = None,
actor_standby_desired_requests_per_actor_run: int | None = None,
actor_standby_max_requests_per_actor_run: int | None = None,
actor_standby_idle_timeout_secs: int | None = None,
actor_standby_build: str | None = None,
actor_standby_memory_mbytes: int | None = None,
) -> dict:
"""Get the dictionary representation of a task."""
return {
'actId': actor_id,
'name': name,
'options': {
'build': build,
'maxItems': max_items,
'memoryMbytes': memory_mbytes,
'timeoutSecs': timeout_secs,
'restartOnError': restart_on_error,
},
'input': task_input,
'title': title,
'actorStandby': {
'desiredRequestsPerActorRun': actor_standby_desired_requests_per_actor_run,
'maxRequestsPerActorRun': actor_standby_max_requests_per_actor_run,
'idleTimeoutSecs': actor_standby_idle_timeout_secs,
'build': actor_standby_build,
'memoryMbytes': actor_standby_memory_mbytes,
},
}
class TaskClient(ResourceClient):
"""Sub-client for manipulating a single task."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
resource_path = kwargs.pop('resource_path', 'actor-tasks')
super().__init__(*args, resource_path=resource_path, **kwargs)
def get(self) -> dict | None:
"""Retrieve the task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-object/get-task
Returns:
The retrieved task.
"""
return self._get()
def update(
self,
*,
name: str | None = None,
task_input: dict | None = None,
build: str | None = None,
max_items: int | None = None,
memory_mbytes: int | None = None,
timeout_secs: int | None = None,
restart_on_error: bool | None = None,
title: str | None = None,
actor_standby_desired_requests_per_actor_run: int | None = None,
actor_standby_max_requests_per_actor_run: int | None = None,
actor_standby_idle_timeout_secs: int | None = None,
actor_standby_build: str | None = None,
actor_standby_memory_mbytes: int | None = None,
) -> dict:
"""Update the task with specified fields.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-object/update-task
Args:
name: Name of the task.
build: Actor build to run. It can be either a build tag or build number. By default, the run uses
the build specified in the task settings (typically latest).
max_items: Maximum number of results that will be returned by this run. If the Actor is charged per result,
you will not be charged for more results than the given limit.
memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
in the task settings.
timeout_secs: Optional timeout for the run, in seconds. By default, the run uses timeout specified
in the task settings.
task_input: Task input dictionary.
restart_on_error: If true, the Task run process will be restarted whenever it exits with
a non-zero status code.
title: A human-friendly equivalent of the name.
actor_standby_desired_requests_per_actor_run: The desired number of concurrent HTTP requests for
a single Actor Standby run.
actor_standby_max_requests_per_actor_run: The maximum number of concurrent HTTP requests for
a single Actor Standby run.
actor_standby_idle_timeout_secs: If the Actor run does not receive any requests for this time,
it will be shut down.
actor_standby_build: The build tag or number to run when the Actor is in Standby mode.
actor_standby_memory_mbytes: The memory in megabytes to use when the Actor is in Standby mode.
Returns:
The updated task.
"""
task_representation = get_task_representation(
name=name,
task_input=task_input,
build=build,
max_items=max_items,
memory_mbytes=memory_mbytes,
timeout_secs=timeout_secs,
restart_on_error=restart_on_error,
title=title,
actor_standby_desired_requests_per_actor_run=actor_standby_desired_requests_per_actor_run,
actor_standby_max_requests_per_actor_run=actor_standby_max_requests_per_actor_run,
actor_standby_idle_timeout_secs=actor_standby_idle_timeout_secs,
actor_standby_build=actor_standby_build,
actor_standby_memory_mbytes=actor_standby_memory_mbytes,
)
return self._update(filter_out_none_values_recursively(task_representation))
def delete(self) -> None:
"""Delete the task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-object/delete-task
"""
return self._delete()
def start(
self,
*,
task_input: dict | None = None,
build: str | None = None,
max_items: int | None = None,
memory_mbytes: int | None = None,
timeout_secs: int | None = None,
restart_on_error: bool | None = None,
wait_for_finish: int | None = None,
webhooks: list[dict] | None = None,
) -> dict:
"""Start the task and immediately return the Run object.
https://docs.apify.com/api/v2#/reference/actor-tasks/run-collection/run-task
Args:
task_input: Task input dictionary.
build: Specifies the Actor build to run. It can be either a build tag or build number. By default,
the run uses the build specified in the task settings (typically latest).
max_items: Maximum number of results that will be returned by this run. If the Actor is charged
per result, you will not be charged for more results than the given limit.
memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
in the task settings.
timeout_secs: Optional timeout for the run, in seconds. By default, the run uses timeout specified
in the task settings.
restart_on_error: If true, the Task run process will be restarted whenever it exits with
a non-zero status code.
wait_for_finish: The maximum number of seconds the server waits for the run to finish. By default,
it is 0, the maximum value is 60.
webhooks: Optional ad-hoc webhooks (https://docs.apify.com/webhooks/ad-hoc-webhooks) associated with
the Actor run which can be used to receive a notification, e.g. when the Actor finished or failed.
If you already have a webhook set up for the Actor or task, you do not have to add it again here.
Each webhook is represented by a dictionary containing these items:
* `event_types`: List of ``WebhookEventType`` values which trigger the webhook.
* `request_url`: URL to which to send the webhook HTTP request.
* `payload_template`: Optional template for the request payload.
Returns:
The run object.
"""
request_params = self._params(
build=build,
maxItems=max_items,
memory=memory_mbytes,
timeout=timeout_secs,
restartOnError=restart_on_error,
waitForFinish=wait_for_finish,
webhooks=encode_webhook_list_to_base64(webhooks) if webhooks is not None else None,
)
response = self.http_client.call(
url=self._url('runs'),
method='POST',
headers={'content-type': 'application/json; charset=utf-8'},
json=task_input,
params=request_params,
)
return parse_date_fields(pluck_data(jsonlib.loads(response.text)))
def call(
self,
*,
task_input: dict | None = None,
build: str | None = None,
max_items: int | None = None,
memory_mbytes: int | None = None,
timeout_secs: int | None = None,
restart_on_error: bool | None = None,
webhooks: list[dict] | None = None,
wait_secs: int | None = None,
) -> dict | None:
"""Start a task and wait for it to finish before returning the Run object.
It waits indefinitely, unless the wait_secs argument is provided.
https://docs.apify.com/api/v2#/reference/actor-tasks/run-collection/run-task
Args:
task_input: Task input dictionary.
build: Specifies the Actor build to run. It can be either a build tag or build number. By default,
the run uses the build specified in the task settings (typically latest).
max_items: Maximum number of results that will be returned by this run. If the Actor is charged per result,
you will not be charged for more results than the given limit.
memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
in the task settings.
timeout_secs: Optional timeout for the run, in seconds. By default, the run uses timeout specified
in the task settings.
restart_on_error: If true, the Task run process will be restarted whenever it exits with
a non-zero status code.
webhooks: Specifies optional webhooks associated with the Actor run, which can be used to receive
a notification e.g. when the Actor finished or failed. Note: if you already have a webhook set up for
the Actor or task, you do not have to add it again here.
wait_secs: The maximum number of seconds the server waits for the task run to finish. If not provided,
waits indefinitely.
Returns:
The run object.
"""
started_run = self.start(
task_input=task_input,
build=build,
max_items=max_items,
memory_mbytes=memory_mbytes,
timeout_secs=timeout_secs,
restart_on_error=restart_on_error,
webhooks=webhooks,
)
return self.root_client.run(started_run['id']).wait_for_finish(wait_secs=wait_secs)
def get_input(self) -> dict | None:
"""Retrieve the default input for this task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-input-object/get-task-input
Returns:
Retrieved task input.
"""
try:
response = self.http_client.call(
url=self._url('input'),
method='GET',
params=self._params(),
)
return cast('dict', jsonlib.loads(response.text))
except ApifyApiError as exc:
catch_not_found_or_throw(exc)
return None
def update_input(self, *, task_input: dict) -> dict:
"""Update the default input for this task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-input-object/update-task-input
Returns:
Retrieved task input.
"""
response = self.http_client.call(
url=self._url('input'),
method='PUT',
params=self._params(),
json=task_input,
)
return cast('dict', jsonlib.loads(response.text))
def runs(self) -> RunCollectionClient:
"""Retrieve a client for the runs of this task."""
return RunCollectionClient(**self._sub_resource_init_options(resource_path='runs'))
def last_run(self, *, status: ActorJobStatus | None = None, origin: MetaOrigin | None = None) -> RunClient:
"""Retrieve the client for the last run of this task.
Last run is retrieved based on the start time of the runs.
Args:
status: Consider only runs with this status.
origin: Consider only runs started with this origin.
Returns:
The resource client for the last run of this task.
"""
return RunClient(
**self._sub_resource_init_options(
resource_id='last',
resource_path='runs',
params=self._params(
status=maybe_extract_enum_member_value(status),
origin=maybe_extract_enum_member_value(origin),
),
)
)
def webhooks(self) -> WebhookCollectionClient:
"""Retrieve a client for webhooks associated with this task."""
return WebhookCollectionClient(**self._sub_resource_init_options())
class TaskClientAsync(ResourceClientAsync):
"""Async sub-client for manipulating a single task."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
resource_path = kwargs.pop('resource_path', 'actor-tasks')
super().__init__(*args, resource_path=resource_path, **kwargs)
async def get(self) -> dict | None:
"""Retrieve the task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-object/get-task
Returns:
The retrieved task.
"""
return await self._get()
async def update(
self,
*,
name: str | None = None,
task_input: dict | None = None,
build: str | None = None,
max_items: int | None = None,
memory_mbytes: int | None = None,
timeout_secs: int | None = None,
restart_on_error: bool | None = None,
title: str | None = None,
actor_standby_desired_requests_per_actor_run: int | None = None,
actor_standby_max_requests_per_actor_run: int | None = None,
actor_standby_idle_timeout_secs: int | None = None,
actor_standby_build: str | None = None,
actor_standby_memory_mbytes: int | None = None,
) -> dict:
"""Update the task with specified fields.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-object/update-task
Args:
name: Name of the task.
build: Actor build to run. It can be either a build tag or build number. By default, the run uses
the build specified in the task settings (typically latest).
max_items: Maximum number of results that will be returned by this run. If the Actor is charged per result,
you will not be charged for more results than the given limit.
memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
in the task settings.
timeout_secs: Optional timeout for the run, in seconds. By default, the run uses timeout specified
in the task settings.
restart_on_error: If true, the Task run process will be restarted whenever it exits with
a non-zero status code.
task_input: Task input dictionary.
title: A human-friendly equivalent of the name.
actor_standby_desired_requests_per_actor_run: The desired number of concurrent HTTP requests for
a single Actor Standby run.
actor_standby_max_requests_per_actor_run: The maximum number of concurrent HTTP requests for
a single Actor Standby run.
actor_standby_idle_timeout_secs: If the Actor run does not receive any requests for this time,
it will be shut down.
actor_standby_build: The build tag or number to run when the Actor is in Standby mode.
actor_standby_memory_mbytes: The memory in megabytes to use when the Actor is in Standby mode.
Returns:
The updated task.
"""
task_representation = get_task_representation(
name=name,
task_input=task_input,
build=build,
max_items=max_items,
memory_mbytes=memory_mbytes,
timeout_secs=timeout_secs,
restart_on_error=restart_on_error,
title=title,
actor_standby_desired_requests_per_actor_run=actor_standby_desired_requests_per_actor_run,
actor_standby_max_requests_per_actor_run=actor_standby_max_requests_per_actor_run,
actor_standby_idle_timeout_secs=actor_standby_idle_timeout_secs,
actor_standby_build=actor_standby_build,
actor_standby_memory_mbytes=actor_standby_memory_mbytes,
)
return await self._update(filter_out_none_values_recursively(task_representation))
async def delete(self) -> None:
"""Delete the task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-object/delete-task
"""
return await self._delete()
async def start(
self,
*,
task_input: dict | None = None,
build: str | None = None,
max_items: int | None = None,
memory_mbytes: int | None = None,
timeout_secs: int | None = None,
restart_on_error: bool | None = None,
wait_for_finish: int | None = None,
webhooks: list[dict] | None = None,
) -> dict:
"""Start the task and immediately return the Run object.
https://docs.apify.com/api/v2#/reference/actor-tasks/run-collection/run-task
Args:
task_input: Task input dictionary.
build: Specifies the Actor build to run. It can be either a build tag or build number. By default,
the run uses the build specified in the task settings (typically latest).
max_items: Maximum number of results that will be returned by this run. If the Actor is charged
per result, you will not be charged for more results than the given limit.
memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
in the task settings.
timeout_secs: Optional timeout for the run, in seconds. By default, the run uses timeout specified
in the task settings.
restart_on_error: If true, the Task run process will be restarted whenever it exits with
a non-zero status code.
wait_for_finish: The maximum number of seconds the server waits for the run to finish. By default,
it is 0, the maximum value is 60.
webhooks: Optional ad-hoc webhooks (https://docs.apify.com/webhooks/ad-hoc-webhooks) associated with
the Actor run which can be used to receive a notification, e.g. when the Actor finished or failed.
If you already have a webhook set up for the Actor or task, you do not have to add it again here.
Each webhook is represented by a dictionary containing these items:
* `event_types`: List of ``WebhookEventType`` values which trigger the webhook.
* `request_url`: URL to which to send the webhook HTTP request.
* `payload_template`: Optional template for the request payload.
Returns:
The run object.
"""
request_params = self._params(
build=build,
maxItems=max_items,
memory=memory_mbytes,
timeout=timeout_secs,
restartOnError=restart_on_error,
waitForFinish=wait_for_finish,
webhooks=encode_webhook_list_to_base64(webhooks) if webhooks is not None else None,
)
response = await self.http_client.call(
url=self._url('runs'),
method='POST',
headers={'content-type': 'application/json; charset=utf-8'},
json=task_input,
params=request_params,
)
return parse_date_fields(pluck_data(jsonlib.loads(response.text)))
async def call(
self,
*,
task_input: dict | None = None,
build: str | None = None,
max_items: int | None = None,
memory_mbytes: int | None = None,
timeout_secs: int | None = None,
restart_on_error: bool | None = None,
webhooks: list[dict] | None = None,
wait_secs: int | None = None,
) -> dict | None:
"""Start a task and wait for it to finish before returning the Run object.
It waits indefinitely, unless the wait_secs argument is provided.
https://docs.apify.com/api/v2#/reference/actor-tasks/run-collection/run-task
Args:
task_input: Task input dictionary.
build: Specifies the Actor build to run. It can be either a build tag or build number. By default,
the run uses the build specified in the task settings (typically latest).
max_items: Maximum number of results that will be returned by this run. If the Actor is charged per result,
you will not be charged for more results than the given limit.
memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
in the task settings.
timeout_secs: Optional timeout for the run, in seconds. By default, the run uses timeout specified
in the task settings.
restart_on_error: If true, the Task run process will be restarted whenever it exits with
a non-zero status code.
webhooks: Specifies optional webhooks associated with the Actor run, which can be used to receive
a notification e.g. when the Actor finished or failed. Note: if you already have a webhook set up for
the Actor or task, you do not have to add it again here.
wait_secs: The maximum number of seconds the server waits for the task run to finish. If not provided,
waits indefinitely.
Returns:
The run object.
"""
started_run = await self.start(
task_input=task_input,
build=build,
max_items=max_items,
memory_mbytes=memory_mbytes,
timeout_secs=timeout_secs,
restart_on_error=restart_on_error,
webhooks=webhooks,
)
return await self.root_client.run(started_run['id']).wait_for_finish(wait_secs=wait_secs)
async def get_input(self) -> dict | None:
"""Retrieve the default input for this task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-input-object/get-task-input
Returns:
Retrieved task input.
"""
try:
response = await self.http_client.call(
url=self._url('input'),
method='GET',
params=self._params(),
)
return cast('dict', jsonlib.loads(response.text))
except ApifyApiError as exc:
catch_not_found_or_throw(exc)
return None
async def update_input(self, *, task_input: dict) -> dict:
"""Update the default input for this task.
https://docs.apify.com/api/v2#/reference/actor-tasks/task-input-object/update-task-input
Returns:
Retrieved task input.
"""
response = await self.http_client.call(
url=self._url('input'),
method='PUT',
params=self._params(),
json=task_input,
)
return cast('dict', jsonlib.loads(response.text))
def runs(self) -> RunCollectionClientAsync:
"""Retrieve a client for the runs of this task."""
return RunCollectionClientAsync(**self._sub_resource_init_options(resource_path='runs'))
def last_run(self, *, status: ActorJobStatus | None = None, origin: MetaOrigin | None = None) -> RunClientAsync:
"""Retrieve the client for the last run of this task.
Last run is retrieved based on the start time of the runs.
Args:
status: Consider only runs with this status.
origin: Consider only runs started with this origin.
Returns:
The resource client for the last run of this task.
"""
return RunClientAsync(
**self._sub_resource_init_options(
resource_id='last',
resource_path='runs',
params=self._params(
status=maybe_extract_enum_member_value(status),
origin=maybe_extract_enum_member_value(origin),
),
)
)
def webhooks(self) -> WebhookCollectionClientAsync:
"""Retrieve a client for webhooks associated with this task."""
return WebhookCollectionClientAsync(**self._sub_resource_init_options())