apify 1.7.3b4__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of apify might be problematic. Click here for more details.

Files changed (61) hide show
  1. apify/__init__.py +19 -4
  2. apify/_actor.py +979 -0
  3. apify/_configuration.py +310 -0
  4. apify/_consts.py +10 -0
  5. apify/_crypto.py +29 -27
  6. apify/_models.py +110 -0
  7. apify/_platform_event_manager.py +222 -0
  8. apify/_proxy_configuration.py +316 -0
  9. apify/_utils.py +0 -497
  10. apify/apify_storage_client/__init__.py +3 -0
  11. apify/apify_storage_client/_apify_storage_client.py +56 -0
  12. apify/apify_storage_client/_dataset_client.py +188 -0
  13. apify/apify_storage_client/_dataset_collection_client.py +50 -0
  14. apify/apify_storage_client/_key_value_store_client.py +98 -0
  15. apify/apify_storage_client/_key_value_store_collection_client.py +50 -0
  16. apify/apify_storage_client/_request_queue_client.py +208 -0
  17. apify/apify_storage_client/_request_queue_collection_client.py +50 -0
  18. apify/apify_storage_client/py.typed +0 -0
  19. apify/log.py +24 -105
  20. apify/scrapy/__init__.py +11 -3
  21. apify/scrapy/middlewares/__init__.py +3 -1
  22. apify/scrapy/middlewares/apify_proxy.py +21 -21
  23. apify/scrapy/middlewares/py.typed +0 -0
  24. apify/scrapy/pipelines/__init__.py +3 -1
  25. apify/scrapy/pipelines/actor_dataset_push.py +1 -1
  26. apify/scrapy/pipelines/py.typed +0 -0
  27. apify/scrapy/py.typed +0 -0
  28. apify/scrapy/requests.py +55 -54
  29. apify/scrapy/scheduler.py +19 -13
  30. apify/scrapy/utils.py +2 -31
  31. apify/storages/__init__.py +2 -10
  32. apify/storages/py.typed +0 -0
  33. apify-2.0.0.dist-info/METADATA +209 -0
  34. apify-2.0.0.dist-info/RECORD +37 -0
  35. {apify-1.7.3b4.dist-info → apify-2.0.0.dist-info}/WHEEL +1 -2
  36. apify/_memory_storage/__init__.py +0 -3
  37. apify/_memory_storage/file_storage_utils.py +0 -71
  38. apify/_memory_storage/memory_storage_client.py +0 -219
  39. apify/_memory_storage/resource_clients/__init__.py +0 -19
  40. apify/_memory_storage/resource_clients/base_resource_client.py +0 -141
  41. apify/_memory_storage/resource_clients/base_resource_collection_client.py +0 -114
  42. apify/_memory_storage/resource_clients/dataset.py +0 -452
  43. apify/_memory_storage/resource_clients/dataset_collection.py +0 -48
  44. apify/_memory_storage/resource_clients/key_value_store.py +0 -533
  45. apify/_memory_storage/resource_clients/key_value_store_collection.py +0 -48
  46. apify/_memory_storage/resource_clients/request_queue.py +0 -466
  47. apify/_memory_storage/resource_clients/request_queue_collection.py +0 -48
  48. apify/actor.py +0 -1357
  49. apify/config.py +0 -130
  50. apify/consts.py +0 -67
  51. apify/event_manager.py +0 -236
  52. apify/proxy_configuration.py +0 -365
  53. apify/storages/base_storage.py +0 -181
  54. apify/storages/dataset.py +0 -494
  55. apify/storages/key_value_store.py +0 -257
  56. apify/storages/request_queue.py +0 -602
  57. apify/storages/storage_client_manager.py +0 -72
  58. apify-1.7.3b4.dist-info/METADATA +0 -150
  59. apify-1.7.3b4.dist-info/RECORD +0 -41
  60. apify-1.7.3b4.dist-info/top_level.txt +0 -1
  61. {apify-1.7.3b4.dist-info → apify-2.0.0.dist-info}/LICENSE +0 -0
apify/actor.py DELETED
@@ -1,1357 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import asyncio
4
- import contextlib
5
- import inspect
6
- import os
7
- import sys
8
- from datetime import datetime, timedelta, timezone
9
- from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypeVar, cast
10
-
11
- from apify_client import ApifyClientAsync
12
- from apify_shared.consts import ActorEnvVars, ActorEventTypes, ActorExitCodes, ApifyEnvVars, WebhookEventType
13
- from apify_shared.utils import ignore_docs, maybe_extract_enum_member_value
14
-
15
- from apify._crypto import decrypt_input_secrets, load_private_key
16
- from apify._utils import (
17
- dualproperty,
18
- fetch_and_parse_env_var,
19
- get_cpu_usage_percent,
20
- get_memory_usage_bytes,
21
- get_system_info,
22
- is_running_in_ipython,
23
- run_func_at_interval_async,
24
- wrap_internal,
25
- )
26
- from apify.config import Configuration
27
- from apify.consts import EVENT_LISTENERS_TIMEOUT_SECS
28
- from apify.event_manager import EventManager
29
- from apify.log import logger
30
- from apify.proxy_configuration import ProxyConfiguration
31
- from apify.storages import Dataset, KeyValueStore, RequestQueue, StorageClientManager
32
-
33
- if TYPE_CHECKING:
34
- import logging
35
- from types import TracebackType
36
-
37
- from apify._memory_storage import MemoryStorageClient
38
-
39
- T = TypeVar('T')
40
- MainReturnType = TypeVar('MainReturnType')
41
-
42
- # This metaclass is needed so you can do `async with Actor: ...` instead of `async with Actor() as a: ...`
43
- # and have automatic `Actor.init()` and `Actor.exit()`
44
-
45
-
46
- class _ActorContextManager(type):
47
- @staticmethod
48
- async def __aenter__() -> type[Actor]:
49
- await Actor.init()
50
- return Actor
51
-
52
- @staticmethod
53
- async def __aexit__(
54
- _exc_type: type[BaseException] | None,
55
- exc_value: BaseException | None,
56
- _exc_traceback: TracebackType | None,
57
- ) -> None:
58
- if not Actor._get_default_instance()._is_exiting:
59
- if exc_value:
60
- await Actor.fail(
61
- exit_code=ActorExitCodes.ERROR_USER_FUNCTION_THREW.value,
62
- exception=exc_value,
63
- )
64
- else:
65
- await Actor.exit()
66
-
67
-
68
- class Actor(metaclass=_ActorContextManager):
69
- """The main class of the SDK, through which all the actor operations should be done."""
70
-
71
- _default_instance: Actor | None = None
72
- _apify_client: ApifyClientAsync
73
- _memory_storage_client: MemoryStorageClient
74
- _config: Configuration
75
- _event_manager: EventManager
76
- _send_system_info_interval_task: asyncio.Task | None = None
77
- _send_persist_state_interval_task: asyncio.Task | None = None
78
- _is_exiting = False
79
- _was_final_persist_state_emitted = False
80
-
81
- def __init__(self: Actor, config: Configuration | None = None) -> None:
82
- """Create an Actor instance.
83
-
84
- Note that you don't have to do this, all the methods on this class function as classmethods too,
85
- and that is their preferred usage.
86
-
87
- Args:
88
- config (Configuration, optional): The actor configuration to be used. If not passed, a new Configuration instance will be created.
89
- """
90
- # To have methods which work the same as classmethods and instance methods,
91
- # so you can do both Actor.xxx() and Actor().xxx(),
92
- # we need to have an `_xxx_internal` instance method which contains the actual implementation of the method,
93
- # and then in the instance constructor overwrite the `xxx` classmethod with the `_xxx_internal` instance method,
94
- # while copying the annotations, types and so on.
95
- self.init = wrap_internal(self._init_internal, self.init) # type: ignore
96
- self.exit = wrap_internal(self._exit_internal, self.exit) # type: ignore
97
- self.fail = wrap_internal(self._fail_internal, self.fail) # type: ignore
98
- self.main = wrap_internal(self._main_internal, self.main) # type: ignore
99
- self.new_client = wrap_internal(self._new_client_internal, self.new_client) # type: ignore
100
-
101
- self.open_dataset = wrap_internal(self._open_dataset_internal, self.open_dataset) # type: ignore
102
- self.open_key_value_store = wrap_internal(self._open_key_value_store_internal, self.open_key_value_store) # type: ignore
103
- self.open_request_queue = wrap_internal(self._open_request_queue_internal, self.open_request_queue) # type: ignore
104
- self.push_data = wrap_internal(self._push_data_internal, self.push_data) # type: ignore
105
- self.get_input = wrap_internal(self._get_input_internal, self.get_input) # type: ignore
106
- self.get_value = wrap_internal(self._get_value_internal, self.get_value) # type: ignore
107
- self.set_value = wrap_internal(self._set_value_internal, self.set_value) # type: ignore
108
-
109
- self.on = wrap_internal(self._on_internal, self.on) # type: ignore
110
- self.off = wrap_internal(self._off_internal, self.off) # type: ignore
111
-
112
- self.is_at_home = wrap_internal(self._is_at_home_internal, self.is_at_home) # type: ignore
113
- self.get_env = wrap_internal(self._get_env_internal, self.get_env) # type: ignore
114
-
115
- self.start = wrap_internal(self._start_internal, self.start) # type: ignore
116
- self.call = wrap_internal(self._call_internal, self.call) # type: ignore
117
- self.call_task = wrap_internal(self._call_task_internal, self.call_task) # type: ignore
118
- self.abort = wrap_internal(self._abort_internal, self.abort) # type: ignore
119
- self.metamorph = wrap_internal(self._metamorph_internal, self.metamorph) # type: ignore
120
- self.reboot = wrap_internal(self._reboot_internal, self.reboot) # type: ignore
121
- self.add_webhook = wrap_internal(self._add_webhook_internal, self.add_webhook) # type: ignore
122
- self.set_status_message = wrap_internal(self._set_status_message_internal, self.set_status_message) # type: ignore
123
- self.create_proxy_configuration = wrap_internal(self._create_proxy_configuration_internal, self.create_proxy_configuration) # type: ignore
124
-
125
- self._config: Configuration = config or Configuration()
126
- self._apify_client = self.new_client()
127
- self._event_manager = EventManager(config=self._config)
128
-
129
- self._is_initialized = False
130
-
131
- @ignore_docs
132
- async def __aenter__(self: Actor) -> Actor:
133
- """Initialize the Actor.
134
-
135
- Automatically initializes the Actor instance when you use it in an `async with ...` statement.
136
-
137
- When you exit the `async with` block, the `Actor.exit()` method is called,
138
- and if any exception happens while executing the block code,
139
- the `Actor.fail` method is called.
140
- """
141
- await self.init()
142
- return self
143
-
144
- @ignore_docs
145
- async def __aexit__(
146
- self: Actor,
147
- _exc_type: type[BaseException] | None,
148
- exc_value: BaseException | None,
149
- _exc_traceback: TracebackType | None,
150
- ) -> None:
151
- """Exit the Actor, handling any exceptions properly.
152
-
153
- When you exit the `async with` block, the `Actor.exit()` method is called,
154
- and if any exception happens while executing the block code,
155
- the `Actor.fail` method is called.
156
- """
157
- if not self._is_exiting:
158
- if exc_value:
159
- await self.fail(
160
- exit_code=ActorExitCodes.ERROR_USER_FUNCTION_THREW.value,
161
- exception=exc_value,
162
- )
163
- else:
164
- await self.exit()
165
-
166
- @classmethod
167
- def _get_default_instance(cls: type[Actor]) -> Actor:
168
- if not cls._default_instance:
169
- cls._default_instance = cls(config=Configuration.get_global_configuration())
170
-
171
- return cls._default_instance
172
-
173
- @dualproperty
174
- def apify_client(self_or_cls: type[Actor] | Actor) -> ApifyClientAsync: # noqa: N805
175
- """The ApifyClientAsync instance the Actor instance uses."""
176
- if isinstance(self_or_cls, type):
177
- return self_or_cls._get_default_instance()._apify_client
178
- return self_or_cls._apify_client
179
-
180
- @dualproperty
181
- def config(self_or_cls: type[Actor] | Actor) -> Configuration: # noqa: N805
182
- """The Configuration instance the Actor instance uses."""
183
- if isinstance(self_or_cls, type):
184
- return self_or_cls._get_default_instance()._config
185
- return self_or_cls._config
186
-
187
- @dualproperty
188
- def event_manager(self_or_cls: type[Actor] | Actor) -> EventManager: # noqa: N805
189
- """The EventManager instance the Actor instance uses."""
190
- if isinstance(self_or_cls, type):
191
- return self_or_cls._get_default_instance()._event_manager
192
-
193
- return self_or_cls._event_manager
194
-
195
- @dualproperty
196
- def log(_self_or_cls: type[Actor] | Actor) -> logging.Logger: # noqa: N805
197
- """The logging.Logger instance the Actor uses."""
198
- return logger
199
-
200
- def _raise_if_not_initialized(self: Actor) -> None:
201
- if not self._is_initialized:
202
- raise RuntimeError('The actor was not initialized!')
203
-
204
- @classmethod
205
- async def init(cls: type[Actor]) -> None:
206
- """Initialize the actor instance.
207
-
208
- This initializes the Actor instance.
209
- It configures the right storage client based on whether the actor is running locally or on the Apify platform,
210
- it initializes the event manager for processing actor events,
211
- and starts an interval for regularly sending `PERSIST_STATE` events,
212
- so that the actor can regularly persist its state in response to these events.
213
-
214
- This method should be called immediately before performing any additional actor actions,
215
- and it should be called only once.
216
- """
217
- return await cls._get_default_instance().init()
218
-
219
- async def _init_internal(self: Actor) -> None:
220
- if self._is_initialized:
221
- raise RuntimeError('The actor was already initialized!')
222
-
223
- self._is_exiting = False
224
- self._was_final_persist_state_emitted = False
225
-
226
- self.log.info('Initializing actor...')
227
- self.log.info('System info', extra=get_system_info())
228
-
229
- # TODO: Print outdated SDK version warning (we need a new env var for this)
230
- # https://github.com/apify/apify-sdk-python/issues/146
231
-
232
- StorageClientManager.set_config(self._config)
233
- if self._config.token:
234
- StorageClientManager.set_cloud_client(self._apify_client)
235
-
236
- await self._event_manager.init()
237
-
238
- self._send_persist_state_interval_task = asyncio.create_task(
239
- run_func_at_interval_async(
240
- lambda: self._event_manager.emit(ActorEventTypes.PERSIST_STATE, {'isMigrating': False}),
241
- self._config.persist_state_interval_millis / 1000,
242
- ),
243
- )
244
-
245
- if not self.is_at_home():
246
- self._send_system_info_interval_task = asyncio.create_task(
247
- run_func_at_interval_async(
248
- lambda: self._event_manager.emit(ActorEventTypes.SYSTEM_INFO, self.get_system_info()),
249
- self._config.system_info_interval_millis / 1000,
250
- ),
251
- )
252
-
253
- self._event_manager.on(ActorEventTypes.MIGRATING, self._respond_to_migrating_event)
254
-
255
- # The CPU usage is calculated as an average between two last calls to psutil
256
- # We need to make a first, dummy call, so the next calls have something to compare itself agains
257
- get_cpu_usage_percent()
258
-
259
- self._is_initialized = True
260
-
261
- def get_system_info(self: Actor) -> dict:
262
- """Get the current system info."""
263
- cpu_usage_percent = get_cpu_usage_percent()
264
- memory_usage_bytes = get_memory_usage_bytes()
265
- # This is in camel case to be compatible with the events from the platform
266
- result = {
267
- 'createdAt': datetime.now(timezone.utc),
268
- 'cpuCurrentUsage': cpu_usage_percent,
269
- 'memCurrentBytes': memory_usage_bytes,
270
- }
271
- if self._config.max_used_cpu_ratio:
272
- result['isCpuOverloaded'] = cpu_usage_percent > 100 * self._config.max_used_cpu_ratio
273
-
274
- return result
275
-
276
- async def _respond_to_migrating_event(self: Actor, _event_data: Any) -> None:
277
- # Don't emit any more regular persist state events
278
- if self._send_persist_state_interval_task and not self._send_persist_state_interval_task.cancelled():
279
- self._send_persist_state_interval_task.cancel()
280
- with contextlib.suppress(asyncio.CancelledError):
281
- await self._send_persist_state_interval_task
282
-
283
- self._event_manager.emit(ActorEventTypes.PERSIST_STATE, {'isMigrating': True})
284
- self._was_final_persist_state_emitted = True
285
-
286
- async def _cancel_event_emitting_intervals(self: Actor) -> None:
287
- if self._send_persist_state_interval_task and not self._send_persist_state_interval_task.cancelled():
288
- self._send_persist_state_interval_task.cancel()
289
- with contextlib.suppress(asyncio.CancelledError):
290
- await self._send_persist_state_interval_task
291
-
292
- if self._send_system_info_interval_task and not self._send_system_info_interval_task.cancelled():
293
- self._send_system_info_interval_task.cancel()
294
- with contextlib.suppress(asyncio.CancelledError):
295
- await self._send_system_info_interval_task
296
-
297
- @classmethod
298
- async def exit(
299
- cls: type[Actor],
300
- *,
301
- exit_code: int = 0,
302
- event_listeners_timeout_secs: float | None = EVENT_LISTENERS_TIMEOUT_SECS,
303
- status_message: str | None = None,
304
- cleanup_timeout: timedelta = timedelta(seconds=30),
305
- ) -> None:
306
- """Exit the actor instance.
307
-
308
- This stops the Actor instance.
309
- It cancels all the intervals for regularly sending `PERSIST_STATE` events,
310
- sends a final `PERSIST_STATE` event,
311
- waits for all the event listeners to finish,
312
- and stops the event manager.
313
-
314
- Args:
315
- exit_code (int, optional): The exit code with which the actor should fail (defaults to `0`).
316
- event_listeners_timeout_secs (float, optional): How long should the actor wait for actor event listeners to finish before exiting.
317
- status_message (str, optional): The final status message that the actor should display.
318
- cleanup_timeout (timedelta, optional): How long we should wait for event listeners.
319
- """
320
- return await cls._get_default_instance().exit(
321
- exit_code=exit_code,
322
- event_listeners_timeout_secs=event_listeners_timeout_secs,
323
- status_message=status_message,
324
- cleanup_timeout=cleanup_timeout,
325
- )
326
-
327
- async def _exit_internal(
328
- self: Actor,
329
- *,
330
- exit_code: int = 0,
331
- event_listeners_timeout_secs: float | None = EVENT_LISTENERS_TIMEOUT_SECS,
332
- status_message: str | None = None,
333
- cleanup_timeout: timedelta = timedelta(seconds=30),
334
- ) -> None:
335
- self._raise_if_not_initialized()
336
-
337
- self._is_exiting = True
338
-
339
- exit_code = maybe_extract_enum_member_value(exit_code)
340
-
341
- self.log.info('Exiting actor', extra={'exit_code': exit_code})
342
-
343
- async def finalize() -> None:
344
- await self._cancel_event_emitting_intervals()
345
-
346
- # Send final persist state event
347
- if not self._was_final_persist_state_emitted:
348
- self._event_manager.emit(ActorEventTypes.PERSIST_STATE, {'isMigrating': False})
349
- self._was_final_persist_state_emitted = True
350
-
351
- if status_message is not None:
352
- await self.set_status_message(status_message, is_terminal=True)
353
-
354
- # Sleep for a bit so that the listeners have a chance to trigger
355
- await asyncio.sleep(0.1)
356
-
357
- await self._event_manager.close(event_listeners_timeout_secs=event_listeners_timeout_secs)
358
-
359
- await asyncio.wait_for(finalize(), cleanup_timeout.total_seconds())
360
- self._is_initialized = False
361
-
362
- if is_running_in_ipython():
363
- self.log.debug(f'Not calling sys.exit({exit_code}) because actor is running in IPython')
364
- elif os.getenv('PYTEST_CURRENT_TEST', default=False): # noqa: PLW1508
365
- self.log.debug(f'Not calling sys.exit({exit_code}) because actor is running in an unit test')
366
- elif hasattr(asyncio, '_nest_patched'):
367
- self.log.debug(f'Not calling sys.exit({exit_code}) because actor is running in a nested event loop')
368
- else:
369
- sys.exit(exit_code)
370
-
371
- @classmethod
372
- async def fail(
373
- cls: type[Actor],
374
- *,
375
- exit_code: int = 1,
376
- exception: BaseException | None = None,
377
- status_message: str | None = None,
378
- ) -> None:
379
- """Fail the actor instance.
380
-
381
- This performs all the same steps as Actor.exit(),
382
- but it additionally sets the exit code to `1` (by default).
383
-
384
- Args:
385
- exit_code (int, optional): The exit code with which the actor should fail (defaults to `1`).
386
- exception (BaseException, optional): The exception with which the actor failed.
387
- status_message (str, optional): The final status message that the actor should display.
388
- """
389
- return await cls._get_default_instance().fail(
390
- exit_code=exit_code,
391
- exception=exception,
392
- status_message=status_message,
393
- )
394
-
395
- async def _fail_internal(
396
- self: Actor,
397
- *,
398
- exit_code: int = 1,
399
- exception: BaseException | None = None,
400
- status_message: str | None = None,
401
- ) -> None:
402
- self._raise_if_not_initialized()
403
-
404
- # In IPython, we don't run `sys.exit()` during actor exits,
405
- # so the exception traceback will be printed on its own
406
- if exception and not is_running_in_ipython():
407
- self.log.exception('Actor failed with an exception', exc_info=exception)
408
-
409
- await self.exit(exit_code=exit_code, status_message=status_message)
410
-
411
- @classmethod
412
- async def main(cls: type[Actor], main_actor_function: Callable[[], MainReturnType]) -> MainReturnType | None:
413
- """Initialize the actor, run the passed function and finish the actor cleanly.
414
-
415
- **The `Actor.main()` function is optional** and is provided merely for your convenience.
416
- It is mainly useful when you're running your code as an actor on the [Apify platform](https://apify.com/actors).
417
-
418
- The `Actor.main()` function performs the following actions:
419
-
420
- - When running on the Apify platform (i.e. `APIFY_IS_AT_HOME` environment variable is set),
421
- it sets up a connection to listen for platform events.
422
- For example, to get a notification about an imminent migration to another server.
423
- - It invokes the user function passed as the `main_actor_function` parameter.
424
- - If the user function was an async function, it awaits it.
425
- - If the user function throws an exception or some other error is encountered,
426
- it prints error details to console so that they are stored to the log,
427
- and finishes the actor cleanly.
428
- - Finally, it exits the Python process, with zero exit code on success and non-zero on errors.
429
-
430
- Args:
431
- main_actor_function (Callable): The user function which should be run in the actor
432
- """
433
- return await cls._get_default_instance().main(
434
- main_actor_function=main_actor_function,
435
- )
436
-
437
- async def _main_internal(self: Actor, main_actor_function: Callable[[], MainReturnType]) -> MainReturnType | None:
438
- if not inspect.isfunction(main_actor_function):
439
- raise TypeError(f'First argument passed to Actor.main() must be a function, but instead it was {type(main_actor_function)}')
440
-
441
- await self.init()
442
- try:
443
- if inspect.iscoroutinefunction(main_actor_function):
444
- res = await main_actor_function()
445
- else:
446
- res = main_actor_function()
447
- await self.exit()
448
- return cast(MainReturnType, res)
449
- except Exception as exc:
450
- await self.fail(
451
- exit_code=ActorExitCodes.ERROR_USER_FUNCTION_THREW.value,
452
- exception=exc,
453
- )
454
- return None
455
-
456
- @classmethod
457
- def new_client(
458
- cls: type[Actor],
459
- *,
460
- token: str | None = None,
461
- api_url: str | None = None,
462
- max_retries: int | None = None,
463
- min_delay_between_retries_millis: int | None = None,
464
- timeout_secs: int | None = None,
465
- ) -> ApifyClientAsync:
466
- """Return a new instance of the Apify API client.
467
-
468
- The `ApifyClientAsync` class is provided by the [apify-client](https://github.com/apify/apify-client-python) package,
469
- and it is automatically configured using the `APIFY_API_BASE_URL` and `APIFY_TOKEN` environment variables.
470
-
471
- You can override the token via the available options.
472
- That's useful if you want to use the client as a different Apify user than the SDK internals are using.
473
-
474
- Args:
475
- token (str, optional): The Apify API token
476
- api_url (str, optional): The URL of the Apify API server to which to connect to. Defaults to https://api.apify.com
477
- max_retries (int, optional): How many times to retry a failed request at most
478
- min_delay_between_retries_millis (int, optional): How long will the client wait between retrying requests
479
- (increases exponentially from this value)
480
- timeout_secs (int, optional): The socket timeout of the HTTP requests sent to the Apify API
481
- """
482
- return cls._get_default_instance().new_client(
483
- token=token,
484
- api_url=api_url,
485
- max_retries=max_retries,
486
- min_delay_between_retries_millis=min_delay_between_retries_millis,
487
- timeout_secs=timeout_secs,
488
- )
489
-
490
- def _new_client_internal(
491
- self: Actor,
492
- *,
493
- token: str | None = None,
494
- api_url: str | None = None,
495
- max_retries: int | None = None,
496
- min_delay_between_retries_millis: int | None = None,
497
- timeout_secs: int | None = None,
498
- ) -> ApifyClientAsync:
499
- token = token or self._config.token
500
- api_url = api_url or self._config.api_base_url
501
- return ApifyClientAsync(
502
- token=token,
503
- api_url=api_url,
504
- max_retries=max_retries,
505
- min_delay_between_retries_millis=min_delay_between_retries_millis,
506
- timeout_secs=timeout_secs,
507
- )
508
-
509
- def _get_storage_client(self: Actor, force_cloud: bool) -> ApifyClientAsync | None: # noqa: FBT001
510
- return self._apify_client if force_cloud else None
511
-
512
- @classmethod
513
- async def open_dataset(
514
- cls: type[Actor],
515
- *,
516
- id: str | None = None, # noqa: A002
517
- name: str | None = None,
518
- force_cloud: bool = False,
519
- ) -> Dataset:
520
- """Open a dataset.
521
-
522
- Datasets are used to store structured data where each object stored has the same attributes,
523
- such as online store products or real estate offers.
524
- The actual data is stored either on the local filesystem or in the Apify cloud.
525
-
526
- Args:
527
- id (str, optional): ID of the dataset to be opened.
528
- If neither `id` nor `name` are provided, the method returns the default dataset associated with the actor run.
529
- name (str, optional): Name of the dataset to be opened.
530
- If neither `id` nor `name` are provided, the method returns the default dataset associated with the actor run.
531
- force_cloud (bool, optional): If set to `True` then the Apify cloud storage is always used.
532
- This way it is possible to combine local and cloud storage.
533
-
534
- Returns:
535
- Dataset: An instance of the `Dataset` class for the given ID or name.
536
-
537
- """
538
- return await cls._get_default_instance().open_dataset(id=id, name=name, force_cloud=force_cloud)
539
-
540
- async def _open_dataset_internal(
541
- self: Actor,
542
- *,
543
- id: str | None = None, # noqa: A002
544
- name: str | None = None,
545
- force_cloud: bool = False,
546
- ) -> Dataset:
547
- self._raise_if_not_initialized()
548
-
549
- return await Dataset.open(id=id, name=name, force_cloud=force_cloud, config=self._config)
550
-
551
- @classmethod
552
- async def open_key_value_store(
553
- cls: type[Actor],
554
- *,
555
- id: str | None = None, # noqa: A002
556
- name: str | None = None,
557
- force_cloud: bool = False,
558
- ) -> KeyValueStore:
559
- """Open a key-value store.
560
-
561
- Key-value stores are used to store records or files, along with their MIME content type.
562
- The records are stored and retrieved using a unique key.
563
- The actual data is stored either on a local filesystem or in the Apify cloud.
564
-
565
- Args:
566
- id (str, optional): ID of the key-value store to be opened.
567
- If neither `id` nor `name` are provided, the method returns the default key-value store associated with the actor run.
568
- name (str, optional): Name of the key-value store to be opened.
569
- If neither `id` nor `name` are provided, the method returns the default key-value store associated with the actor run.
570
- force_cloud (bool, optional): If set to `True` then the Apify cloud storage is always used.
571
- This way it is possible to combine local and cloud storage.
572
-
573
- Returns:
574
- KeyValueStore: An instance of the `KeyValueStore` class for the given ID or name.
575
- """
576
- return await cls._get_default_instance().open_key_value_store(id=id, name=name, force_cloud=force_cloud)
577
-
578
- async def _open_key_value_store_internal(
579
- self: Actor,
580
- *,
581
- id: str | None = None, # noqa: A002
582
- name: str | None = None,
583
- force_cloud: bool = False,
584
- ) -> KeyValueStore:
585
- self._raise_if_not_initialized()
586
-
587
- return await KeyValueStore.open(id=id, name=name, force_cloud=force_cloud, config=self._config)
588
-
589
- @classmethod
590
- async def open_request_queue(
591
- cls: type[Actor],
592
- *,
593
- id: str | None = None, # noqa: A002
594
- name: str | None = None,
595
- force_cloud: bool = False,
596
- ) -> RequestQueue:
597
- """Open a request queue.
598
-
599
- Request queue represents a queue of URLs to crawl, which is stored either on local filesystem or in the Apify cloud.
600
- The queue is used for deep crawling of websites, where you start with several URLs and then
601
- recursively follow links to other pages. The data structure supports both breadth-first
602
- and depth-first crawling orders.
603
-
604
- Args:
605
- id (str, optional): ID of the request queue to be opened.
606
- If neither `id` nor `name` are provided, the method returns the default request queue associated with the actor run.
607
- name (str, optional): Name of the request queue to be opened.
608
- If neither `id` nor `name` are provided, the method returns the default request queue associated with the actor run.
609
- force_cloud (bool, optional): If set to `True` then the Apify cloud storage is always used.
610
- This way it is possible to combine local and cloud storage.
611
-
612
- Returns:
613
- RequestQueue: An instance of the `RequestQueue` class for the given ID or name.
614
- """
615
- return await cls._get_default_instance().open_request_queue(id=id, name=name, force_cloud=force_cloud)
616
-
617
- async def _open_request_queue_internal(
618
- self: Actor,
619
- *,
620
- id: str | None = None, # noqa: A002
621
- name: str | None = None,
622
- force_cloud: bool = False,
623
- ) -> RequestQueue:
624
- self._raise_if_not_initialized()
625
-
626
- return await RequestQueue.open(id=id, name=name, force_cloud=force_cloud, config=self._config)
627
-
628
- @classmethod
629
- async def push_data(cls: type[Actor], data: Any) -> None:
630
- """Store an object or a list of objects to the default dataset of the current actor run.
631
-
632
- Args:
633
- data (object or list of objects, optional): The data to push to the default dataset.
634
- """
635
- return await cls._get_default_instance().push_data(data=data)
636
-
637
- async def _push_data_internal(self: Actor, data: Any) -> None:
638
- self._raise_if_not_initialized()
639
-
640
- if not data:
641
- return
642
-
643
- dataset = await self.open_dataset()
644
- await dataset.push_data(data)
645
-
646
- @classmethod
647
- async def get_input(cls: type[Actor]) -> Any:
648
- """Get the actor input value from the default key-value store associated with the current actor run."""
649
- return await cls._get_default_instance().get_input()
650
-
651
- async def _get_input_internal(self: Actor) -> Any:
652
- self._raise_if_not_initialized()
653
-
654
- input_value = await self.get_value(self._config.input_key)
655
- input_secrets_private_key = self._config.input_secrets_private_key_file
656
- input_secrets_key_passphrase = self._config.input_secrets_private_key_passphrase
657
- if input_secrets_private_key and input_secrets_key_passphrase:
658
- private_key = load_private_key(
659
- input_secrets_private_key,
660
- input_secrets_key_passphrase,
661
- )
662
- input_value = decrypt_input_secrets(private_key, input_value)
663
-
664
- return input_value
665
-
666
- @classmethod
667
- async def get_value(cls: type[Actor], key: str, default_value: Any = None) -> Any:
668
- """Get a value from the default key-value store associated with the current actor run.
669
-
670
- Args:
671
- key (str): The key of the record which to retrieve.
672
- default_value (Any, optional): Default value returned in case the record does not exist.
673
- """
674
- return await cls._get_default_instance().get_value(key=key, default_value=default_value)
675
-
676
- async def _get_value_internal(self: Actor, key: str, default_value: Any = None) -> Any:
677
- self._raise_if_not_initialized()
678
-
679
- key_value_store = await self.open_key_value_store()
680
- return await key_value_store.get_value(key, default_value)
681
-
682
- @classmethod
683
- async def set_value(
684
- cls: type[Actor],
685
- key: str,
686
- value: Any,
687
- *,
688
- content_type: str | None = None,
689
- ) -> None:
690
- """Set or delete a value in the default key-value store associated with the current actor run.
691
-
692
- Args:
693
- key (str): The key of the record which to set.
694
- value (any): The value of the record which to set, or None, if the record should be deleted.
695
- content_type (str, optional): The content type which should be set to the value.
696
- """
697
- return await cls._get_default_instance().set_value(
698
- key=key,
699
- value=value,
700
- content_type=content_type,
701
- )
702
-
703
- async def _set_value_internal(
704
- self: Actor,
705
- key: str,
706
- value: Any,
707
- *,
708
- content_type: str | None = None,
709
- ) -> None:
710
- self._raise_if_not_initialized()
711
-
712
- key_value_store = await self.open_key_value_store()
713
- return await key_value_store.set_value(key, value, content_type=content_type)
714
-
715
- @classmethod
716
- def on(cls: type[Actor], event_name: ActorEventTypes, listener: Callable) -> Callable:
717
- """Add an event listener to the actor's event manager.
718
-
719
- The following events can be emitted:
720
- - `ActorEventTypes.SYSTEM_INFO`:
721
- Emitted every minute, the event data contains info about the resource usage of the actor.
722
- - `ActorEventTypes.MIGRATING`:
723
- Emitted when the actor running on the Apify platform is going to be migrated to another worker server soon.
724
- You can use it to persist the state of the actor and gracefully stop your in-progress tasks,
725
- so that they are not interrupted by the migration..
726
- - `ActorEventTypes.PERSIST_STATE`:
727
- Emitted in regular intervals (by default 60 seconds) to notify the actor that it should persist its state,
728
- in order to avoid repeating all work when the actor restarts.
729
- This event is automatically emitted together with the migrating event,
730
- in which case the `isMigrating` flag in the event data is set to True, otherwise the flag is False.
731
- Note that this event is provided merely for your convenience,
732
- you can achieve the same effect using an interval and listening for the migrating event.
733
- - `ActorEventTypes.ABORTING`:
734
- When a user aborts an actor run on the Apify platform,
735
- they can choose to abort it gracefully, to allow the actor some time before getting terminated.
736
- This graceful abort emits the aborting event, which you can use to clean up the actor state.
737
-
738
- Args:
739
- event_name (ActorEventTypes): The actor event for which to listen to.
740
- listener (Callable): The function which is to be called when the event is emitted (can be async).
741
- """
742
- return cls._get_default_instance().on(event_name, listener)
743
-
744
- def _on_internal(self: Actor, event_name: ActorEventTypes, listener: Callable) -> Callable:
745
- self._raise_if_not_initialized()
746
-
747
- return self._event_manager.on(event_name, listener)
748
-
749
- @classmethod
750
- def off(cls: type[Actor], event_name: ActorEventTypes, listener: Callable | None = None) -> None:
751
- """Remove a listener, or all listeners, from an actor event.
752
-
753
- Args:
754
- event_name (ActorEventTypes): The actor event for which to remove listeners.
755
- listener (Callable, optional): The listener which is supposed to be removed. If not passed, all listeners of this event are removed.
756
- """
757
- return cls._get_default_instance().off(event_name, listener)
758
-
759
- def _off_internal(self: Actor, event_name: ActorEventTypes, listener: Callable | None = None) -> None:
760
- self._raise_if_not_initialized()
761
-
762
- return self._event_manager.off(event_name, listener)
763
-
764
- @classmethod
765
- def is_at_home(cls: type[Actor]) -> bool:
766
- """Return `True` when the actor is running on the Apify platform, and `False` otherwise (for example when running locally)."""
767
- return cls._get_default_instance().is_at_home()
768
-
769
- def _is_at_home_internal(self: Actor) -> bool:
770
- return self._config.is_at_home
771
-
772
- @classmethod
773
- def get_env(cls: type[Actor]) -> dict:
774
- """Return a dictionary with information parsed from all the `APIFY_XXX` environment variables.
775
-
776
- For a list of all the environment variables,
777
- see the [Actor documentation](https://docs.apify.com/actors/development/environment-variables).
778
- If some variables are not defined or are invalid, the corresponding value in the resulting dictionary will be None.
779
- """
780
- return cls._get_default_instance().get_env()
781
-
782
- def _get_env_internal(self: Actor) -> dict:
783
- self._raise_if_not_initialized()
784
-
785
- return {env_var.name.lower(): fetch_and_parse_env_var(env_var) for env_var in [*ActorEnvVars, *ApifyEnvVars]}
786
-
787
- @classmethod
788
- async def start(
789
- cls: type[Actor],
790
- actor_id: str,
791
- run_input: Any = None,
792
- *,
793
- token: str | None = None,
794
- content_type: str | None = None,
795
- build: str | None = None,
796
- memory_mbytes: int | None = None,
797
- timeout_secs: int | None = None,
798
- wait_for_finish: int | None = None,
799
- webhooks: list[dict] | None = None,
800
- ) -> dict:
801
- """Run an actor on the Apify platform.
802
-
803
- Unlike `Actor.call`, this method just starts the run without waiting for finish.
804
-
805
- Args:
806
- actor_id (str): The ID of the actor to be run.
807
- run_input (Any, optional): The input to pass to the actor run.
808
- token (str, optional): The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
809
- content_type (str, optional): The content type of the input.
810
- build (str, optional): Specifies the actor build to run. It can be either a build tag or build number.
811
- By default, the run uses the build specified in the default run configuration for the actor (typically latest).
812
- memory_mbytes (int, optional): Memory limit for the run, in megabytes.
813
- By default, the run uses a memory limit specified in the default run configuration for the actor.
814
- timeout_secs (int, optional): Optional timeout for the run, in seconds.
815
- By default, the run uses timeout specified in the default run configuration for the actor.
816
- wait_for_finish (int, optional): The maximum number of seconds the server waits for the run to finish.
817
- By default, it is 0, the maximum value is 300.
818
- webhooks (list of dict, optional): Optional ad-hoc webhooks (https://docs.apify.com/webhooks/ad-hoc-webhooks)
819
- associated with the actor run which can be used to receive a notification,
820
- e.g. when the actor finished or failed.
821
- If you already have a webhook set up for the actor or task, you do not have to add it again here.
822
- Each webhook is represented by a dictionary containing these items:
823
- * ``event_types``: list of ``WebhookEventType`` values which trigger the webhook
824
- * ``request_url``: URL to which to send the webhook HTTP request
825
- * ``payload_template`` (optional): Optional template for the request payload
826
-
827
- Returns:
828
- dict: Info about the started actor run
829
- """
830
- return await cls._get_default_instance().start(
831
- actor_id=actor_id,
832
- run_input=run_input,
833
- token=token,
834
- content_type=content_type,
835
- build=build,
836
- memory_mbytes=memory_mbytes,
837
- timeout_secs=timeout_secs,
838
- wait_for_finish=wait_for_finish,
839
- webhooks=webhooks,
840
- )
841
-
842
- async def _start_internal(
843
- self: Actor,
844
- actor_id: str,
845
- run_input: Any = None,
846
- *,
847
- token: str | None = None,
848
- content_type: str | None = None,
849
- build: str | None = None,
850
- memory_mbytes: int | None = None,
851
- timeout_secs: int | None = None,
852
- wait_for_finish: int | None = None,
853
- webhooks: list[dict] | None = None,
854
- ) -> dict:
855
- self._raise_if_not_initialized()
856
-
857
- client = self.new_client(token=token) if token else self._apify_client
858
-
859
- return await client.actor(actor_id).start(
860
- run_input=run_input,
861
- content_type=content_type,
862
- build=build,
863
- memory_mbytes=memory_mbytes,
864
- timeout_secs=timeout_secs,
865
- wait_for_finish=wait_for_finish,
866
- webhooks=webhooks,
867
- )
868
-
869
- @classmethod
870
- async def abort(
871
- cls: type[Actor],
872
- run_id: str,
873
- *,
874
- token: str | None = None,
875
- gracefully: bool | None = None,
876
- ) -> dict:
877
- """Abort given actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
878
-
879
- Args:
880
- run_id (str): The ID of the actor run to be aborted.
881
- token (str, optional): The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
882
- gracefully (bool, optional): If True, the actor run will abort gracefully.
883
- It will send ``aborting`` and ``persistStates`` events into the run and force-stop the run after 30 seconds.
884
- It is helpful in cases where you plan to resurrect the run later.
885
-
886
- Returns:
887
- dict: Info about the aborted actor run
888
- """
889
- return await cls._get_default_instance().abort(
890
- run_id=run_id,
891
- token=token,
892
- gracefully=gracefully,
893
- )
894
-
895
- async def _abort_internal(
896
- self: Actor,
897
- run_id: str,
898
- *,
899
- token: str | None = None,
900
- status_message: str | None = None,
901
- gracefully: bool | None = None,
902
- ) -> dict:
903
- self._raise_if_not_initialized()
904
-
905
- client = self.new_client(token=token) if token else self._apify_client
906
-
907
- if status_message:
908
- await client.run(run_id).update(status_message=status_message)
909
-
910
- return await client.run(run_id).abort(gracefully=gracefully)
911
-
912
- @classmethod
913
- async def call(
914
- cls: type[Actor],
915
- actor_id: str,
916
- run_input: Any = None,
917
- *,
918
- token: str | None = None,
919
- content_type: str | None = None,
920
- build: str | None = None,
921
- memory_mbytes: int | None = None,
922
- timeout_secs: int | None = None,
923
- webhooks: list[dict] | None = None,
924
- wait_secs: int | None = None,
925
- ) -> dict | None:
926
- """Start an actor on the Apify Platform and wait for it to finish before returning.
927
-
928
- It waits indefinitely, unless the wait_secs argument is provided.
929
-
930
- Args:
931
- actor_id (str): The ID of the actor to be run.
932
- run_input (Any, optional): The input to pass to the actor run.
933
- token (str, optional): The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
934
- content_type (str, optional): The content type of the input.
935
- build (str, optional): Specifies the actor build to run. It can be either a build tag or build number.
936
- By default, the run uses the build specified in the default run configuration for the actor (typically latest).
937
- memory_mbytes (int, optional): Memory limit for the run, in megabytes.
938
- By default, the run uses a memory limit specified in the default run configuration for the actor.
939
- timeout_secs (int, optional): Optional timeout for the run, in seconds.
940
- By default, the run uses timeout specified in the default run configuration for the actor.
941
- webhooks (list, optional): Optional webhooks (https://docs.apify.com/webhooks) associated with the actor run,
942
- which can be used to receive a notification, e.g. when the actor finished or failed.
943
- If you already have a webhook set up for the actor, you do not have to add it again here.
944
- wait_secs (int, optional): The maximum number of seconds the server waits for the run to finish. If not provided, waits indefinitely.
945
-
946
- Returns:
947
- dict: Info about the started actor run
948
- """
949
- return await cls._get_default_instance().call(
950
- actor_id=actor_id,
951
- token=token,
952
- run_input=run_input,
953
- content_type=content_type,
954
- build=build,
955
- memory_mbytes=memory_mbytes,
956
- timeout_secs=timeout_secs,
957
- webhooks=webhooks,
958
- wait_secs=wait_secs,
959
- )
960
-
961
- async def _call_internal(
962
- self: Actor,
963
- actor_id: str,
964
- run_input: Any = None,
965
- *,
966
- token: str | None = None,
967
- content_type: str | None = None,
968
- build: str | None = None,
969
- memory_mbytes: int | None = None,
970
- timeout_secs: int | None = None,
971
- webhooks: list[dict] | None = None,
972
- wait_secs: int | None = None,
973
- ) -> dict | None:
974
- self._raise_if_not_initialized()
975
-
976
- client = self.new_client(token=token) if token else self._apify_client
977
-
978
- return await client.actor(actor_id).call(
979
- run_input=run_input,
980
- content_type=content_type,
981
- build=build,
982
- memory_mbytes=memory_mbytes,
983
- timeout_secs=timeout_secs,
984
- webhooks=webhooks,
985
- wait_secs=wait_secs,
986
- )
987
-
988
- @classmethod
989
- async def call_task(
990
- cls: type[Actor],
991
- task_id: str,
992
- task_input: dict | None = None,
993
- *,
994
- build: str | None = None,
995
- memory_mbytes: int | None = None,
996
- timeout_secs: int | None = None,
997
- webhooks: list[dict] | None = None,
998
- wait_secs: int | None = None,
999
- token: str | None = None,
1000
- ) -> dict | None:
1001
- """Start an actor task on the Apify Platform and wait for it to finish before returning.
1002
-
1003
- It waits indefinitely, unless the wait_secs argument is provided.
1004
-
1005
- Note that an actor task is a saved input configuration and options for an actor.
1006
- If you want to run an actor directly rather than an actor task, please use the `Actor.call`
1007
-
1008
- Args:
1009
- task_id (str): The ID of the actor to be run.
1010
- task_input (Any, optional): Overrides the input to pass to the actor run.
1011
- token (str, optional): The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
1012
- content_type (str, optional): The content type of the input.
1013
- build (str, optional): Specifies the actor build to run. It can be either a build tag or build number.
1014
- By default, the run uses the build specified in the default run configuration for the actor (typically latest).
1015
- memory_mbytes (int, optional): Memory limit for the run, in megabytes.
1016
- By default, the run uses a memory limit specified in the default run configuration for the actor.
1017
- timeout_secs (int, optional): Optional timeout for the run, in seconds.
1018
- By default, the run uses timeout specified in the default run configuration for the actor.
1019
- webhooks (list, optional): Optional webhooks (https://docs.apify.com/webhooks) associated with the actor run,
1020
- which can be used to receive a notification, e.g. when the actor finished or failed.
1021
- If you already have a webhook set up for the actor, you do not have to add it again here.
1022
- wait_secs (int, optional): The maximum number of seconds the server waits for the run to finish. If not provided, waits indefinitely.
1023
-
1024
- Returns:
1025
- dict: Info about the started actor run
1026
- """
1027
- return await cls._get_default_instance().call_task(
1028
- task_id=task_id,
1029
- task_input=task_input,
1030
- token=token,
1031
- build=build,
1032
- memory_mbytes=memory_mbytes,
1033
- timeout_secs=timeout_secs,
1034
- webhooks=webhooks,
1035
- wait_secs=wait_secs,
1036
- )
1037
-
1038
- async def _call_task_internal(
1039
- self: Actor,
1040
- task_id: str,
1041
- task_input: dict | None = None,
1042
- *,
1043
- build: str | None = None,
1044
- memory_mbytes: int | None = None,
1045
- timeout_secs: int | None = None,
1046
- webhooks: list[dict] | None = None,
1047
- wait_secs: int | None = None,
1048
- token: str | None = None,
1049
- ) -> dict | None:
1050
- self._raise_if_not_initialized()
1051
-
1052
- client = self.new_client(token=token) if token else self._apify_client
1053
-
1054
- return await client.task(task_id).call(
1055
- task_input=task_input,
1056
- build=build,
1057
- memory_mbytes=memory_mbytes,
1058
- timeout_secs=timeout_secs,
1059
- webhooks=webhooks,
1060
- wait_secs=wait_secs,
1061
- )
1062
-
1063
- @classmethod
1064
- async def metamorph(
1065
- cls: type[Actor],
1066
- target_actor_id: str,
1067
- run_input: Any = None,
1068
- *,
1069
- target_actor_build: str | None = None,
1070
- content_type: str | None = None,
1071
- custom_after_sleep_millis: int | None = None,
1072
- ) -> None:
1073
- """Transform this actor run to an actor run of a different actor.
1074
-
1075
- The platform stops the current actor container and starts a new container with the new actor instead.
1076
- All the default storages are preserved,
1077
- and the new input is stored under the `INPUT-METAMORPH-1` key in the same default key-value store.
1078
-
1079
- Args:
1080
- target_actor_id (str): ID of the target actor that the run should be transformed into
1081
- run_input (Any, optional): The input to pass to the new run.
1082
- target_actor_build (str, optional): The build of the target actor. It can be either a build tag or build number.
1083
- By default, the run uses the build specified in the default run configuration for the target actor (typically the latest build).
1084
- content_type (str, optional): The content type of the input.
1085
- custom_after_sleep_millis (int, optional): How long to sleep for after the metamorph, to wait for the container to be stopped.
1086
-
1087
- Returns:
1088
- dict: The actor run data.
1089
- """
1090
- return await cls._get_default_instance().metamorph(
1091
- target_actor_id=target_actor_id,
1092
- target_actor_build=target_actor_build,
1093
- run_input=run_input,
1094
- content_type=content_type,
1095
- custom_after_sleep_millis=custom_after_sleep_millis,
1096
- )
1097
-
1098
- async def _metamorph_internal(
1099
- self: Actor,
1100
- target_actor_id: str,
1101
- run_input: Any = None,
1102
- *,
1103
- target_actor_build: str | None = None,
1104
- content_type: str | None = None,
1105
- custom_after_sleep_millis: int | None = None,
1106
- ) -> None:
1107
- self._raise_if_not_initialized()
1108
-
1109
- if not self.is_at_home():
1110
- self.log.error('Actor.metamorph() is only supported when running on the Apify platform.')
1111
- return
1112
-
1113
- if not custom_after_sleep_millis:
1114
- custom_after_sleep_millis = self._config.metamorph_after_sleep_millis
1115
-
1116
- # If is_at_home() is True, config.actor_run_id is always set
1117
- assert self._config.actor_run_id is not None # noqa: S101
1118
-
1119
- await self._apify_client.run(self._config.actor_run_id).metamorph(
1120
- target_actor_id=target_actor_id,
1121
- run_input=run_input,
1122
- target_actor_build=target_actor_build,
1123
- content_type=content_type,
1124
- )
1125
-
1126
- if custom_after_sleep_millis:
1127
- await asyncio.sleep(custom_after_sleep_millis / 1000)
1128
-
1129
- @classmethod
1130
- async def reboot(
1131
- cls: type[Actor],
1132
- *,
1133
- event_listeners_timeout_secs: int | None = EVENT_LISTENERS_TIMEOUT_SECS,
1134
- custom_after_sleep_millis: int | None = None,
1135
- ) -> None:
1136
- """Internally reboot this actor.
1137
-
1138
- The system stops the current container and starts a new one, with the same run ID and default storages.
1139
-
1140
- Args:
1141
- event_listeners_timeout_secs (int, optional): How long should the actor wait for actor event listeners to finish before exiting
1142
- custom_after_sleep_millis (int, optional): How long to sleep for after the reboot, to wait for the container to be stopped.
1143
- """
1144
- return await cls._get_default_instance().reboot(
1145
- event_listeners_timeout_secs=event_listeners_timeout_secs,
1146
- custom_after_sleep_millis=custom_after_sleep_millis,
1147
- )
1148
-
1149
- async def _reboot_internal(
1150
- self: Actor,
1151
- *,
1152
- event_listeners_timeout_secs: int | None = EVENT_LISTENERS_TIMEOUT_SECS,
1153
- custom_after_sleep_millis: int | None = None,
1154
- ) -> None:
1155
- self._raise_if_not_initialized()
1156
-
1157
- if not self.is_at_home():
1158
- self.log.error('Actor.reboot() is only supported when running on the Apify platform.')
1159
- return
1160
-
1161
- if not custom_after_sleep_millis:
1162
- custom_after_sleep_millis = self._config.metamorph_after_sleep_millis
1163
-
1164
- await self._cancel_event_emitting_intervals()
1165
-
1166
- self._event_manager.emit(ActorEventTypes.PERSIST_STATE, {'isMigrating': True})
1167
- self._was_final_persist_state_emitted = True
1168
-
1169
- await self._event_manager.close(event_listeners_timeout_secs=event_listeners_timeout_secs)
1170
-
1171
- assert self._config.actor_run_id is not None # noqa: S101
1172
- await self._apify_client.run(self._config.actor_run_id).reboot()
1173
-
1174
- if custom_after_sleep_millis:
1175
- await asyncio.sleep(custom_after_sleep_millis / 1000)
1176
-
1177
- @classmethod
1178
- async def add_webhook(
1179
- cls: type[Actor],
1180
- *,
1181
- event_types: list[WebhookEventType],
1182
- request_url: str,
1183
- payload_template: str | None = None,
1184
- ignore_ssl_errors: bool | None = None,
1185
- do_not_retry: bool | None = None,
1186
- idempotency_key: str | None = None,
1187
- ) -> dict:
1188
- """Create an ad-hoc webhook for the current actor run.
1189
-
1190
- This webhook lets you receive a notification when the actor run finished or failed.
1191
-
1192
- Note that webhooks are only supported for actors running on the Apify platform.
1193
- When running the actor locally, the function will print a warning and have no effect.
1194
-
1195
- For more information about Apify actor webhooks, please see the [documentation](https://docs.apify.com/webhooks).
1196
-
1197
- Args:
1198
- event_types (list of WebhookEventType): List of event types that should trigger the webhook. At least one is required.
1199
- request_url (str): URL that will be invoked once the webhook is triggered.
1200
- payload_template (str, optional): Specification of the payload that will be sent to request_url
1201
- ignore_ssl_errors (bool, optional): Whether the webhook should ignore SSL errors returned by request_url
1202
- do_not_retry (bool, optional): Whether the webhook should retry sending the payload to request_url upon
1203
- failure.
1204
- idempotency_key (str, optional): A unique identifier of a webhook. You can use it to ensure that you won't
1205
- create the same webhook multiple times.
1206
-
1207
- Returns:
1208
- dict: The created webhook
1209
- """
1210
- return await cls._get_default_instance().add_webhook(
1211
- event_types=event_types,
1212
- request_url=request_url,
1213
- payload_template=payload_template,
1214
- ignore_ssl_errors=ignore_ssl_errors,
1215
- do_not_retry=do_not_retry,
1216
- idempotency_key=idempotency_key,
1217
- )
1218
-
1219
- async def _add_webhook_internal(
1220
- self: Actor,
1221
- *,
1222
- event_types: list[WebhookEventType],
1223
- request_url: str,
1224
- payload_template: str | None = None,
1225
- ignore_ssl_errors: bool | None = None,
1226
- do_not_retry: bool | None = None,
1227
- idempotency_key: str | None = None,
1228
- ) -> dict | None:
1229
- self._raise_if_not_initialized()
1230
-
1231
- if not self.is_at_home():
1232
- self.log.error('Actor.add_webhook() is only supported when running on the Apify platform.')
1233
- return None
1234
-
1235
- # If is_at_home() is True, config.actor_run_id is always set
1236
- assert self._config.actor_run_id is not None # noqa: S101
1237
-
1238
- return await self._apify_client.webhooks().create(
1239
- actor_run_id=self._config.actor_run_id,
1240
- event_types=event_types,
1241
- request_url=request_url,
1242
- payload_template=payload_template,
1243
- ignore_ssl_errors=ignore_ssl_errors,
1244
- do_not_retry=do_not_retry,
1245
- idempotency_key=idempotency_key,
1246
- )
1247
-
1248
- @classmethod
1249
- async def set_status_message(
1250
- cls: type[Actor],
1251
- status_message: str,
1252
- *,
1253
- is_terminal: bool | None = None,
1254
- ) -> dict | None:
1255
- """Set the status message for the current actor run.
1256
-
1257
- Args:
1258
- status_message (str): The status message to set to the run.
1259
- is_terminal (bool, optional): Set this flag to True if this is the final status message of the Actor run.
1260
-
1261
- Returns:
1262
- dict: The updated actor run object
1263
- """
1264
- return await cls._get_default_instance().set_status_message(status_message=status_message, is_terminal=is_terminal)
1265
-
1266
- async def _set_status_message_internal(
1267
- self: Actor,
1268
- status_message: str,
1269
- *,
1270
- is_terminal: bool | None = None,
1271
- ) -> dict | None:
1272
- self._raise_if_not_initialized()
1273
-
1274
- if not self.is_at_home():
1275
- title = 'Terminal status message' if is_terminal else 'Status message'
1276
- self.log.info(f'[{title}]: {status_message}')
1277
- return None
1278
-
1279
- # If is_at_home() is True, config.actor_run_id is always set
1280
- assert self._config.actor_run_id is not None # noqa: S101
1281
-
1282
- return await self._apify_client.run(self._config.actor_run_id).update(status_message=status_message, is_status_message_terminal=is_terminal)
1283
-
1284
- @classmethod
1285
- async def create_proxy_configuration(
1286
- cls: type[Actor],
1287
- *,
1288
- actor_proxy_input: dict | None = None, # this is the raw proxy input from the actor run input, it is not spread or snake_cased in here
1289
- password: str | None = None,
1290
- groups: list[str] | None = None,
1291
- country_code: str | None = None,
1292
- proxy_urls: list[str] | None = None,
1293
- new_url_function: Callable[[str | None], str] | Callable[[str | None], Awaitable[str]] | None = None,
1294
- ) -> ProxyConfiguration | None:
1295
- """Create a ProxyConfiguration object with the passed proxy configuration.
1296
-
1297
- Configures connection to a proxy server with the provided options.
1298
- Proxy servers are used to prevent target websites from blocking your crawlers based on IP address rate limits or blacklists.
1299
-
1300
- For more details and code examples, see the `ProxyConfiguration` class.
1301
-
1302
- Args:
1303
- actor_proxy_input (dict, optional): Proxy configuration field from the actor input, if actor has such input field.
1304
- If you pass this argument, all the other arguments will be inferred from it.
1305
- password (str, optional): Password for the Apify Proxy. If not provided, will use os.environ['APIFY_PROXY_PASSWORD'], if available.
1306
- groups (list of str, optional): Proxy groups which the Apify Proxy should use, if provided.
1307
- country_code (str, optional): Country which the Apify Proxy should use, if provided.
1308
- proxy_urls (list of str, optional): Custom proxy server URLs which should be rotated through.
1309
- new_url_function (Callable, optional): Function which returns a custom proxy URL to be used.
1310
-
1311
- Returns:
1312
- ProxyConfiguration, optional: ProxyConfiguration object with the passed configuration,
1313
- or None, if no proxy should be used based on the configuration.
1314
- """
1315
- return await cls._get_default_instance().create_proxy_configuration(
1316
- password=password,
1317
- groups=groups,
1318
- country_code=country_code,
1319
- proxy_urls=proxy_urls,
1320
- new_url_function=new_url_function,
1321
- actor_proxy_input=actor_proxy_input,
1322
- )
1323
-
1324
- async def _create_proxy_configuration_internal(
1325
- self: Actor,
1326
- *,
1327
- actor_proxy_input: dict | None = None, # this is the raw proxy input from the actor run input, it is not spread or snake_cased in here
1328
- password: str | None = None,
1329
- groups: list[str] | None = None,
1330
- country_code: str | None = None,
1331
- proxy_urls: list[str] | None = None,
1332
- new_url_function: Callable[[str | None], str] | Callable[[str | None], Awaitable[str]] | None = None,
1333
- ) -> ProxyConfiguration | None:
1334
- self._raise_if_not_initialized()
1335
-
1336
- if actor_proxy_input is not None:
1337
- if actor_proxy_input.get('useApifyProxy', False):
1338
- country_code = country_code or actor_proxy_input.get('apifyProxyCountry')
1339
- groups = groups or actor_proxy_input.get('apifyProxyGroups')
1340
- else:
1341
- proxy_urls = actor_proxy_input.get('proxyUrls', [])
1342
- if not proxy_urls:
1343
- return None
1344
-
1345
- proxy_configuration = ProxyConfiguration(
1346
- password=password,
1347
- groups=groups,
1348
- country_code=country_code,
1349
- proxy_urls=proxy_urls,
1350
- new_url_function=new_url_function,
1351
- _actor_config=self._config,
1352
- _apify_client=self._apify_client,
1353
- )
1354
-
1355
- await proxy_configuration.initialize()
1356
-
1357
- return proxy_configuration