apify 1.7.0b1__py3-none-any.whl → 2.2.0b14__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 (62) hide show
  1. apify/__init__.py +19 -4
  2. apify/_actor.py +1030 -0
  3. apify/_configuration.py +370 -0
  4. apify/_consts.py +10 -0
  5. apify/_crypto.py +31 -27
  6. apify/_models.py +117 -0
  7. apify/_platform_event_manager.py +231 -0
  8. apify/_proxy_configuration.py +320 -0
  9. apify/_utils.py +18 -484
  10. apify/apify_storage_client/__init__.py +3 -0
  11. apify/apify_storage_client/_apify_storage_client.py +68 -0
  12. apify/apify_storage_client/_dataset_client.py +190 -0
  13. apify/apify_storage_client/_dataset_collection_client.py +51 -0
  14. apify/apify_storage_client/_key_value_store_client.py +94 -0
  15. apify/apify_storage_client/_key_value_store_collection_client.py +51 -0
  16. apify/apify_storage_client/_request_queue_client.py +176 -0
  17. apify/apify_storage_client/_request_queue_collection_client.py +51 -0
  18. apify/apify_storage_client/py.typed +0 -0
  19. apify/log.py +22 -105
  20. apify/scrapy/__init__.py +11 -3
  21. apify/scrapy/middlewares/__init__.py +3 -1
  22. apify/scrapy/middlewares/apify_proxy.py +29 -27
  23. apify/scrapy/middlewares/py.typed +0 -0
  24. apify/scrapy/pipelines/__init__.py +3 -1
  25. apify/scrapy/pipelines/actor_dataset_push.py +6 -3
  26. apify/scrapy/pipelines/py.typed +0 -0
  27. apify/scrapy/py.typed +0 -0
  28. apify/scrapy/requests.py +60 -58
  29. apify/scrapy/scheduler.py +28 -19
  30. apify/scrapy/utils.py +10 -32
  31. apify/storages/__init__.py +4 -10
  32. apify/storages/_request_list.py +150 -0
  33. apify/storages/py.typed +0 -0
  34. apify-2.2.0b14.dist-info/METADATA +211 -0
  35. apify-2.2.0b14.dist-info/RECORD +38 -0
  36. {apify-1.7.0b1.dist-info → apify-2.2.0b14.dist-info}/WHEEL +1 -2
  37. apify/_memory_storage/__init__.py +0 -3
  38. apify/_memory_storage/file_storage_utils.py +0 -71
  39. apify/_memory_storage/memory_storage_client.py +0 -219
  40. apify/_memory_storage/resource_clients/__init__.py +0 -19
  41. apify/_memory_storage/resource_clients/base_resource_client.py +0 -141
  42. apify/_memory_storage/resource_clients/base_resource_collection_client.py +0 -114
  43. apify/_memory_storage/resource_clients/dataset.py +0 -452
  44. apify/_memory_storage/resource_clients/dataset_collection.py +0 -48
  45. apify/_memory_storage/resource_clients/key_value_store.py +0 -533
  46. apify/_memory_storage/resource_clients/key_value_store_collection.py +0 -48
  47. apify/_memory_storage/resource_clients/request_queue.py +0 -466
  48. apify/_memory_storage/resource_clients/request_queue_collection.py +0 -48
  49. apify/actor.py +0 -1351
  50. apify/config.py +0 -127
  51. apify/consts.py +0 -67
  52. apify/event_manager.py +0 -236
  53. apify/proxy_configuration.py +0 -365
  54. apify/storages/base_storage.py +0 -181
  55. apify/storages/dataset.py +0 -494
  56. apify/storages/key_value_store.py +0 -257
  57. apify/storages/request_queue.py +0 -602
  58. apify/storages/storage_client_manager.py +0 -72
  59. apify-1.7.0b1.dist-info/METADATA +0 -149
  60. apify-1.7.0b1.dist-info/RECORD +0 -41
  61. apify-1.7.0b1.dist-info/top_level.txt +0 -1
  62. {apify-1.7.0b1.dist-info → apify-2.2.0b14.dist-info}/LICENSE +0 -0
apify/_actor.py ADDED
@@ -0,0 +1,1030 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+ import sys
6
+ from datetime import timedelta
7
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
8
+
9
+ from lazy_object_proxy import Proxy
10
+ from more_itertools import flatten
11
+ from pydantic import AliasChoices
12
+
13
+ from apify_client import ApifyClientAsync
14
+ from apify_shared.consts import ActorEnvVars, ActorExitCodes, ApifyEnvVars
15
+ from apify_shared.utils import ignore_docs, maybe_extract_enum_member_value
16
+ from crawlee import service_locator
17
+ from crawlee.events._types import Event, EventMigratingData, EventPersistStateData
18
+
19
+ from apify._configuration import Configuration
20
+ from apify._consts import EVENT_LISTENERS_TIMEOUT
21
+ from apify._crypto import decrypt_input_secrets, load_private_key
22
+ from apify._models import ActorRun
23
+ from apify._platform_event_manager import EventManager, LocalEventManager, PlatformEventManager
24
+ from apify._proxy_configuration import ProxyConfiguration
25
+ from apify._utils import docs_group, docs_name, get_system_info, is_running_in_ipython
26
+ from apify.apify_storage_client import ApifyStorageClient
27
+ from apify.log import _configure_logging, logger
28
+ from apify.storages import Dataset, KeyValueStore, RequestQueue
29
+
30
+ if TYPE_CHECKING:
31
+ import logging
32
+ from types import TracebackType
33
+
34
+ from typing_extensions import Self
35
+
36
+ from crawlee.proxy_configuration import _NewUrlFunction
37
+ from crawlee.storage_clients import BaseStorageClient
38
+
39
+ from apify._models import Webhook
40
+
41
+
42
+ MainReturnType = TypeVar('MainReturnType')
43
+
44
+
45
+ @docs_name('Actor')
46
+ @docs_group('Classes')
47
+ class _ActorType:
48
+ """The class of `Actor`. Only make a new instance if you're absolutely sure you need to."""
49
+
50
+ _apify_client: ApifyClientAsync
51
+ _configuration: Configuration
52
+ _is_exiting = False
53
+ _is_rebooting = False
54
+
55
+ def __init__(
56
+ self,
57
+ configuration: Configuration | None = None,
58
+ *,
59
+ configure_logging: bool = True,
60
+ ) -> None:
61
+ """Create an Actor instance.
62
+
63
+ Note that you don't have to do this, all the functionality is accessible using the default instance
64
+ (e.g. `Actor.open_dataset()`).
65
+
66
+ Args:
67
+ configuration: The Actor configuration to be used. If not passed, a new Configuration instance will
68
+ be created.
69
+ configure_logging: Should the default logging configuration be configured?
70
+ """
71
+ self._configuration = configuration or Configuration.get_global_configuration()
72
+ self._configure_logging = configure_logging
73
+ self._apify_client = self.new_client()
74
+
75
+ # Create an instance of the cloud storage client, the local storage client is obtained
76
+ # from the service locator.
77
+ self._cloud_storage_client = ApifyStorageClient.from_config(config=self._configuration)
78
+
79
+ # Set the event manager based on whether the Actor is running on the platform or locally.
80
+ self._event_manager = (
81
+ PlatformEventManager(
82
+ config=self._configuration,
83
+ persist_state_interval=self._configuration.persist_state_interval,
84
+ )
85
+ if self.is_at_home()
86
+ else LocalEventManager(
87
+ system_info_interval=self._configuration.system_info_interval,
88
+ persist_state_interval=self._configuration.persist_state_interval,
89
+ )
90
+ )
91
+
92
+ self._is_initialized = False
93
+
94
+ @ignore_docs
95
+ async def __aenter__(self) -> Self:
96
+ """Initialize the Actor.
97
+
98
+ Automatically initializes the Actor instance when you use it in an `async with ...` statement.
99
+
100
+ When you exit the `async with` block, the `Actor.exit()` method is called, and if any exception happens while
101
+ executing the block code, the `Actor.fail` method is called.
102
+ """
103
+ await self.init()
104
+ return self
105
+
106
+ @ignore_docs
107
+ async def __aexit__(
108
+ self,
109
+ _exc_type: type[BaseException] | None,
110
+ exc_value: BaseException | None,
111
+ _exc_traceback: TracebackType | None,
112
+ ) -> None:
113
+ """Exit the Actor, handling any exceptions properly.
114
+
115
+ When you exit the `async with` block, the `Actor.exit()` method is called, and if any exception happens while
116
+ executing the block code, the `Actor.fail` method is called.
117
+ """
118
+ if not self._is_exiting:
119
+ if exc_value:
120
+ await self.fail(
121
+ exit_code=ActorExitCodes.ERROR_USER_FUNCTION_THREW.value,
122
+ exception=exc_value,
123
+ )
124
+ else:
125
+ await self.exit()
126
+
127
+ def __repr__(self) -> str:
128
+ if self is cast(Proxy, Actor).__wrapped__:
129
+ return '<apify.Actor>'
130
+
131
+ return super().__repr__()
132
+
133
+ def __call__(self, configuration: Configuration | None = None, *, configure_logging: bool = True) -> Self:
134
+ """Make a new Actor instance with a non-default configuration."""
135
+ return self.__class__(configuration=configuration, configure_logging=configure_logging)
136
+
137
+ @property
138
+ def apify_client(self) -> ApifyClientAsync:
139
+ """The ApifyClientAsync instance the Actor instance uses."""
140
+ return self._apify_client
141
+
142
+ @property
143
+ def configuration(self) -> Configuration:
144
+ """The Configuration instance the Actor instance uses."""
145
+ return self._configuration
146
+
147
+ @property
148
+ def config(self) -> Configuration:
149
+ """The Configuration instance the Actor instance uses."""
150
+ return self._configuration
151
+
152
+ @property
153
+ def event_manager(self) -> EventManager:
154
+ """The EventManager instance the Actor instance uses."""
155
+ return self._event_manager
156
+
157
+ @property
158
+ def log(self) -> logging.Logger:
159
+ """The logging.Logger instance the Actor uses."""
160
+ return logger
161
+
162
+ @property
163
+ def _local_storage_client(self) -> BaseStorageClient:
164
+ """The local storage client the Actor instance uses."""
165
+ return service_locator.get_storage_client()
166
+
167
+ def _raise_if_not_initialized(self) -> None:
168
+ if not self._is_initialized:
169
+ raise RuntimeError('The Actor was not initialized!')
170
+
171
+ def _raise_if_cloud_requested_but_not_configured(self, *, force_cloud: bool) -> None:
172
+ if not force_cloud:
173
+ return
174
+
175
+ if not self.is_at_home() and self.config.token is None:
176
+ raise RuntimeError(
177
+ 'In order to use the Apify cloud storage from your computer, '
178
+ 'you need to provide an Apify token using the APIFY_TOKEN environment variable.'
179
+ )
180
+
181
+ async def init(self) -> None:
182
+ """Initialize the Actor instance.
183
+
184
+ This initializes the Actor instance. It configures the right storage client based on whether the Actor is
185
+ running locally or on the Apify platform, it initializes the event manager for processing Actor events,
186
+ and starts an interval for regularly sending `PERSIST_STATE` events, so that the Actor can regularly persist
187
+ its state in response to these events.
188
+
189
+ This method should be called immediately before performing any additional Actor actions, and it should be
190
+ called only once.
191
+ """
192
+ if self._is_initialized:
193
+ raise RuntimeError('The Actor was already initialized!')
194
+
195
+ self._is_exiting = False
196
+ self._was_final_persist_state_emitted = False
197
+
198
+ # If the Actor is running on the Apify platform, we set the cloud storage client.
199
+ if self.is_at_home():
200
+ service_locator.set_storage_client(self._cloud_storage_client)
201
+
202
+ service_locator.set_event_manager(self.event_manager)
203
+ service_locator.set_configuration(self.configuration)
204
+
205
+ # The logging configuration has to be called after all service_locator set methods.
206
+ if self._configure_logging:
207
+ _configure_logging()
208
+
209
+ self.log.info('Initializing Actor...')
210
+ self.log.info('System info', extra=get_system_info())
211
+
212
+ # TODO: Print outdated SDK version warning (we need a new env var for this)
213
+ # https://github.com/apify/apify-sdk-python/issues/146
214
+
215
+ await self._event_manager.__aenter__()
216
+
217
+ self._is_initialized = True
218
+
219
+ async def exit(
220
+ self,
221
+ *,
222
+ exit_code: int = 0,
223
+ event_listeners_timeout: timedelta | None = EVENT_LISTENERS_TIMEOUT,
224
+ status_message: str | None = None,
225
+ cleanup_timeout: timedelta = timedelta(seconds=30),
226
+ ) -> None:
227
+ """Exit the Actor instance.
228
+
229
+ This stops the Actor instance. It cancels all the intervals for regularly sending `PERSIST_STATE` events,
230
+ sends a final `PERSIST_STATE` event, waits for all the event listeners to finish, and stops the event manager.
231
+
232
+ Args:
233
+ exit_code: The exit code with which the Actor should fail (defaults to `0`).
234
+ event_listeners_timeout: How long should the Actor wait for Actor event listeners to finish before exiting.
235
+ status_message: The final status message that the Actor should display.
236
+ cleanup_timeout: How long we should wait for event listeners.
237
+ """
238
+ self._raise_if_not_initialized()
239
+
240
+ self._is_exiting = True
241
+
242
+ exit_code = maybe_extract_enum_member_value(exit_code)
243
+
244
+ self.log.info('Exiting Actor', extra={'exit_code': exit_code})
245
+
246
+ async def finalize() -> None:
247
+ if status_message is not None:
248
+ await self.set_status_message(status_message, is_terminal=True)
249
+
250
+ # Sleep for a bit so that the listeners have a chance to trigger
251
+ await asyncio.sleep(0.1)
252
+
253
+ if event_listeners_timeout:
254
+ await self._event_manager.wait_for_all_listeners_to_complete(timeout=event_listeners_timeout)
255
+
256
+ await self._event_manager.__aexit__(None, None, None)
257
+
258
+ await asyncio.wait_for(finalize(), cleanup_timeout.total_seconds())
259
+ self._is_initialized = False
260
+
261
+ if is_running_in_ipython():
262
+ self.log.debug(f'Not calling sys.exit({exit_code}) because Actor is running in IPython')
263
+ elif os.getenv('PYTEST_CURRENT_TEST', default=False): # noqa: PLW1508
264
+ self.log.debug(f'Not calling sys.exit({exit_code}) because Actor is running in an unit test')
265
+ elif hasattr(asyncio, '_nest_patched'):
266
+ self.log.debug(f'Not calling sys.exit({exit_code}) because Actor is running in a nested event loop')
267
+ else:
268
+ sys.exit(exit_code)
269
+
270
+ async def fail(
271
+ self,
272
+ *,
273
+ exit_code: int = 1,
274
+ exception: BaseException | None = None,
275
+ status_message: str | None = None,
276
+ ) -> None:
277
+ """Fail the Actor instance.
278
+
279
+ This performs all the same steps as Actor.exit(), but it additionally sets the exit code to `1` (by default).
280
+
281
+ Args:
282
+ exit_code: The exit code with which the Actor should fail (defaults to `1`).
283
+ exception: The exception with which the Actor failed.
284
+ status_message: The final status message that the Actor should display.
285
+ """
286
+ self._raise_if_not_initialized()
287
+
288
+ # In IPython, we don't run `sys.exit()` during Actor exits,
289
+ # so the exception traceback will be printed on its own
290
+ if exception and not is_running_in_ipython():
291
+ self.log.exception('Actor failed with an exception', exc_info=exception)
292
+
293
+ await self.exit(exit_code=exit_code, status_message=status_message)
294
+
295
+ def new_client(
296
+ self,
297
+ *,
298
+ token: str | None = None,
299
+ api_url: str | None = None,
300
+ max_retries: int | None = None,
301
+ min_delay_between_retries: timedelta | None = None,
302
+ timeout: timedelta | None = None,
303
+ ) -> ApifyClientAsync:
304
+ """Return a new instance of the Apify API client.
305
+
306
+ The `ApifyClientAsync` class is provided by the [apify-client](https://github.com/apify/apify-client-python)
307
+ package, and it is automatically configured using the `APIFY_API_BASE_URL` and `APIFY_TOKEN` environment
308
+ variables.
309
+
310
+ You can override the token via the available options. That's useful if you want to use the client
311
+ as a different Apify user than the SDK internals are using.
312
+
313
+ Args:
314
+ token: The Apify API token.
315
+ api_url: The URL of the Apify API server to which to connect to. Defaults to https://api.apify.com.
316
+ max_retries: How many times to retry a failed request at most.
317
+ min_delay_between_retries: How long will the client wait between retrying requests
318
+ (increases exponentially from this value).
319
+ timeout: The socket timeout of the HTTP requests sent to the Apify API.
320
+ """
321
+ token = token or self._configuration.token
322
+ api_url = api_url or self._configuration.api_base_url
323
+ return ApifyClientAsync(
324
+ token=token,
325
+ api_url=api_url,
326
+ max_retries=max_retries,
327
+ min_delay_between_retries_millis=int(min_delay_between_retries.total_seconds() * 1000)
328
+ if min_delay_between_retries is not None
329
+ else None,
330
+ timeout_secs=int(timeout.total_seconds()) if timeout else None,
331
+ )
332
+
333
+ async def open_dataset(
334
+ self,
335
+ *,
336
+ id: str | None = None,
337
+ name: str | None = None,
338
+ force_cloud: bool = False,
339
+ ) -> Dataset:
340
+ """Open a dataset.
341
+
342
+ Datasets are used to store structured data where each object stored has the same attributes, such as online
343
+ store products or real estate offers. The actual data is stored either on the local filesystem or in
344
+ the Apify cloud.
345
+
346
+ Args:
347
+ id: ID of the dataset to be opened. If neither `id` nor `name` are provided, the method returns
348
+ the default dataset associated with the Actor run.
349
+ name: Name of the dataset to be opened. If neither `id` nor `name` are provided, the method returns
350
+ the default dataset associated with the Actor run.
351
+ force_cloud: If set to `True` then the Apify cloud storage is always used. This way it is possible
352
+ to combine local and cloud storage.
353
+
354
+ Returns:
355
+ An instance of the `Dataset` class for the given ID or name.
356
+ """
357
+ self._raise_if_not_initialized()
358
+ self._raise_if_cloud_requested_but_not_configured(force_cloud=force_cloud)
359
+
360
+ storage_client = self._cloud_storage_client if force_cloud else self._local_storage_client
361
+
362
+ return await Dataset.open(
363
+ id=id,
364
+ name=name,
365
+ configuration=self._configuration,
366
+ storage_client=storage_client,
367
+ )
368
+
369
+ async def open_key_value_store(
370
+ self,
371
+ *,
372
+ id: str | None = None,
373
+ name: str | None = None,
374
+ force_cloud: bool = False,
375
+ ) -> KeyValueStore:
376
+ """Open a key-value store.
377
+
378
+ Key-value stores are used to store records or files, along with their MIME content type. The records are stored
379
+ and retrieved using a unique key. The actual data is stored either on a local filesystem or in the Apify cloud.
380
+
381
+ Args:
382
+ id: ID of the key-value store to be opened. If neither `id` nor `name` are provided, the method returns
383
+ the default key-value store associated with the Actor run.
384
+ name: Name of the key-value store to be opened. If neither `id` nor `name` are provided, the method
385
+ returns the default key-value store associated with the Actor run.
386
+ force_cloud: If set to `True` then the Apify cloud storage is always used. This way it is possible
387
+ to combine local and cloud storage.
388
+
389
+ Returns:
390
+ An instance of the `KeyValueStore` class for the given ID or name.
391
+ """
392
+ self._raise_if_not_initialized()
393
+ self._raise_if_cloud_requested_but_not_configured(force_cloud=force_cloud)
394
+ storage_client = self._cloud_storage_client if force_cloud else self._local_storage_client
395
+
396
+ return await KeyValueStore.open(
397
+ id=id,
398
+ name=name,
399
+ configuration=self._configuration,
400
+ storage_client=storage_client,
401
+ )
402
+
403
+ async def open_request_queue(
404
+ self,
405
+ *,
406
+ id: str | None = None,
407
+ name: str | None = None,
408
+ force_cloud: bool = False,
409
+ ) -> RequestQueue:
410
+ """Open a request queue.
411
+
412
+ Request queue represents a queue of URLs to crawl, which is stored either on local filesystem or in
413
+ the Apify cloud. The queue is used for deep crawling of websites, where you start with several URLs and then
414
+ recursively follow links to other pages. The data structure supports both breadth-first and depth-first
415
+ crawling orders.
416
+
417
+ Args:
418
+ id: ID of the request queue to be opened. If neither `id` nor `name` are provided, the method returns
419
+ the default request queue associated with the Actor run.
420
+ name: Name of the request queue to be opened. If neither `id` nor `name` are provided, the method returns
421
+ the default request queue associated with the Actor run.
422
+ force_cloud: If set to `True` then the Apify cloud storage is always used. This way it is possible
423
+ to combine local and cloud storage.
424
+
425
+ Returns:
426
+ An instance of the `RequestQueue` class for the given ID or name.
427
+ """
428
+ self._raise_if_not_initialized()
429
+ self._raise_if_cloud_requested_but_not_configured(force_cloud=force_cloud)
430
+
431
+ storage_client = self._cloud_storage_client if force_cloud else self._local_storage_client
432
+
433
+ return await RequestQueue.open(
434
+ id=id,
435
+ name=name,
436
+ configuration=self._configuration,
437
+ storage_client=storage_client,
438
+ )
439
+
440
+ async def push_data(self, data: dict | list[dict]) -> None:
441
+ """Store an object or a list of objects to the default dataset of the current Actor run.
442
+
443
+ Args:
444
+ data: The data to push to the default dataset.
445
+ """
446
+ self._raise_if_not_initialized()
447
+
448
+ if not data:
449
+ return
450
+
451
+ dataset = await self.open_dataset()
452
+ await dataset.push_data(data)
453
+
454
+ async def get_input(self) -> Any:
455
+ """Get the Actor input value from the default key-value store associated with the current Actor run."""
456
+ self._raise_if_not_initialized()
457
+
458
+ input_value = await self.get_value(self._configuration.input_key)
459
+ input_secrets_private_key = self._configuration.input_secrets_private_key_file
460
+ input_secrets_key_passphrase = self._configuration.input_secrets_private_key_passphrase
461
+ if input_secrets_private_key and input_secrets_key_passphrase:
462
+ private_key = load_private_key(
463
+ input_secrets_private_key,
464
+ input_secrets_key_passphrase,
465
+ )
466
+ input_value = decrypt_input_secrets(private_key, input_value)
467
+
468
+ return input_value
469
+
470
+ async def get_value(self, key: str, default_value: Any = None) -> Any:
471
+ """Get a value from the default key-value store associated with the current Actor run.
472
+
473
+ Args:
474
+ key: The key of the record which to retrieve.
475
+ default_value: Default value returned in case the record does not exist.
476
+ """
477
+ self._raise_if_not_initialized()
478
+
479
+ key_value_store = await self.open_key_value_store()
480
+ return await key_value_store.get_value(key, default_value)
481
+
482
+ async def set_value(
483
+ self,
484
+ key: str,
485
+ value: Any,
486
+ *,
487
+ content_type: str | None = None,
488
+ ) -> None:
489
+ """Set or delete a value in the default key-value store associated with the current Actor run.
490
+
491
+ Args:
492
+ key: The key of the record which to set.
493
+ value: The value of the record which to set, or None, if the record should be deleted.
494
+ content_type: The content type which should be set to the value.
495
+ """
496
+ self._raise_if_not_initialized()
497
+
498
+ key_value_store = await self.open_key_value_store()
499
+ return await key_value_store.set_value(key, value, content_type=content_type)
500
+
501
+ def on(self, event_name: Event, listener: Callable) -> Callable:
502
+ """Add an event listener to the Actor's event manager.
503
+
504
+ The following events can be emitted:
505
+
506
+ - `Event.SYSTEM_INFO`: Emitted every minute; the event data contains information about the Actor's resource
507
+ usage.
508
+
509
+ - `Event.MIGRATING`: Emitted when the Actor on the Apify platform is about to be migrated to another worker
510
+ server. Use this event to persist the Actor's state and gracefully stop in-progress tasks, preventing
511
+ disruption.
512
+
513
+ - `Event.PERSIST_STATE`: Emitted regularly (default: 60 seconds) to notify the Actor to persist its state,
514
+ preventing work repetition after a restart. This event is emitted together with the `MIGRATING` event, where
515
+ the `isMigrating` flag in the event data is `True`; otherwise, the flag is `False`. This event is for
516
+ convenience; the same effect can be achieved by setting an interval and listening for the `MIGRATING` event.
517
+
518
+ - `Event.ABORTING`: Emitted when a user aborts an Actor run on the Apify platform, allowing the Actor time
519
+ to clean up its state if the abort is graceful.
520
+
521
+ Args:
522
+ event_name: The Actor event to listen for.
523
+ listener: The function to be called when the event is emitted (can be async).
524
+ """
525
+ self._raise_if_not_initialized()
526
+
527
+ self._event_manager.on(event=event_name, listener=listener)
528
+ return listener
529
+
530
+ def off(self, event_name: Event, listener: Callable | None = None) -> None:
531
+ """Remove a listener, or all listeners, from an Actor event.
532
+
533
+ Args:
534
+ event_name: The Actor event for which to remove listeners.
535
+ listener: The listener which is supposed to be removed. If not passed, all listeners of this event
536
+ are removed.
537
+ """
538
+ self._raise_if_not_initialized()
539
+
540
+ self._event_manager.off(event=event_name, listener=listener)
541
+
542
+ def is_at_home(self) -> bool:
543
+ """Return `True` when the Actor is running on the Apify platform, and `False` otherwise (e.g. local run)."""
544
+ return self._configuration.is_at_home
545
+
546
+ def get_env(self) -> dict:
547
+ """Return a dictionary with information parsed from all the `APIFY_XXX` environment variables.
548
+
549
+ For a list of all the environment variables, see the
550
+ [Actor documentation](https://docs.apify.com/actors/development/environment-variables). If some variables
551
+ are not defined or are invalid, the corresponding value in the resulting dictionary will be None.
552
+ """
553
+ self._raise_if_not_initialized()
554
+
555
+ config = dict[str, Any]()
556
+ for field_name, field in Configuration.model_fields.items():
557
+ if field.deprecated:
558
+ continue
559
+
560
+ if field.alias:
561
+ aliases = [field.alias]
562
+ elif isinstance(field.validation_alias, str):
563
+ aliases = [field.validation_alias]
564
+ elif isinstance(field.validation_alias, AliasChoices):
565
+ aliases = cast(list[str], field.validation_alias.choices)
566
+ else:
567
+ aliases = [field_name]
568
+
569
+ for alias in aliases:
570
+ config[alias] = getattr(self._configuration, field_name)
571
+
572
+ env_vars = {env_var.value.lower(): env_var.name.lower() for env_var in [*ActorEnvVars, *ApifyEnvVars]}
573
+ return {option_name: config[env_var] for env_var, option_name in env_vars.items() if env_var in config}
574
+
575
+ async def start(
576
+ self,
577
+ actor_id: str,
578
+ run_input: Any = None,
579
+ *,
580
+ token: str | None = None,
581
+ content_type: str | None = None,
582
+ build: str | None = None,
583
+ memory_mbytes: int | None = None,
584
+ timeout: timedelta | None = None,
585
+ wait_for_finish: int | None = None,
586
+ webhooks: list[Webhook] | None = None,
587
+ ) -> ActorRun:
588
+ """Run an Actor on the Apify platform.
589
+
590
+ Unlike `Actor.call`, this method just starts the run without waiting for finish.
591
+
592
+ Args:
593
+ actor_id: The ID of the Actor to be run.
594
+ run_input: The input to pass to the Actor run.
595
+ token: The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
596
+ content_type: The content type of the input.
597
+ build: Specifies the Actor build to run. It can be either a build tag or build number. By default,
598
+ the run uses the build specified in the default run configuration for the Actor (typically latest).
599
+ memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
600
+ in the default run configuration for the Actor.
601
+ timeout: Optional timeout for the run, in seconds. By default, the run uses timeout specified in
602
+ the default run configuration for the Actor.
603
+ wait_for_finish: The maximum number of seconds the server waits for the run to finish. By default,
604
+ it is 0, the maximum value is 300.
605
+ webhooks: Optional ad-hoc webhooks (https://docs.apify.com/webhooks/ad-hoc-webhooks) associated with
606
+ the Actor run which can be used to receive a notification, e.g. when the Actor finished or failed.
607
+ If you already have a webhook set up for the Actor or task, you do not have to add it again here.
608
+
609
+ Returns:
610
+ Info about the started Actor run
611
+ """
612
+ self._raise_if_not_initialized()
613
+
614
+ client = self.new_client(token=token) if token else self._apify_client
615
+
616
+ if webhooks:
617
+ serialized_webhooks = [
618
+ hook.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=True) for hook in webhooks
619
+ ]
620
+ else:
621
+ serialized_webhooks = None
622
+
623
+ api_result = await client.actor(actor_id).start(
624
+ run_input=run_input,
625
+ content_type=content_type,
626
+ build=build,
627
+ memory_mbytes=memory_mbytes,
628
+ timeout_secs=int(timeout.total_seconds()) if timeout is not None else None,
629
+ wait_for_finish=wait_for_finish,
630
+ webhooks=serialized_webhooks,
631
+ )
632
+
633
+ return ActorRun.model_validate(api_result)
634
+
635
+ async def abort(
636
+ self,
637
+ run_id: str,
638
+ *,
639
+ token: str | None = None,
640
+ status_message: str | None = None,
641
+ gracefully: bool | None = None,
642
+ ) -> ActorRun:
643
+ """Abort given Actor run on the Apify platform using the current user account.
644
+
645
+ The user account is determined by the `APIFY_TOKEN` environment variable.
646
+
647
+ Args:
648
+ run_id: The ID of the Actor run to be aborted.
649
+ token: The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
650
+ status_message: Status message of the Actor to be set on the platform.
651
+ gracefully: If True, the Actor run will abort gracefully. It will send `aborting` and `persistState`
652
+ events into the run and force-stop the run after 30 seconds. It is helpful in cases where you plan
653
+ to resurrect the run later.
654
+
655
+ Returns:
656
+ Info about the aborted Actor run.
657
+ """
658
+ self._raise_if_not_initialized()
659
+
660
+ client = self.new_client(token=token) if token else self._apify_client
661
+
662
+ if status_message:
663
+ await client.run(run_id).update(status_message=status_message)
664
+
665
+ api_result = await client.run(run_id).abort(gracefully=gracefully)
666
+
667
+ return ActorRun.model_validate(api_result)
668
+
669
+ async def call(
670
+ self,
671
+ actor_id: str,
672
+ run_input: Any = None,
673
+ *,
674
+ token: str | None = None,
675
+ content_type: str | None = None,
676
+ build: str | None = None,
677
+ memory_mbytes: int | None = None,
678
+ timeout: timedelta | None = None,
679
+ webhooks: list[Webhook] | None = None,
680
+ wait: timedelta | None = None,
681
+ ) -> ActorRun | None:
682
+ """Start an Actor on the Apify Platform and wait for it to finish before returning.
683
+
684
+ It waits indefinitely, unless the wait argument is provided.
685
+
686
+ Args:
687
+ actor_id: The ID of the Actor to be run.
688
+ run_input: The input to pass to the Actor run.
689
+ token: The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
690
+ content_type: The content type of the input.
691
+ build: Specifies the Actor build to run. It can be either a build tag or build number. By default,
692
+ the run uses the build specified in the default run configuration for the Actor (typically latest).
693
+ memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
694
+ in the default run configuration for the Actor.
695
+ timeout: Optional timeout for the run, in seconds. By default, the run uses timeout specified in
696
+ the default run configuration for the Actor.
697
+ webhooks: Optional webhooks (https://docs.apify.com/webhooks) associated with the Actor run, which can
698
+ be used to receive a notification, e.g. when the Actor finished or failed. If you already have
699
+ a webhook set up for the Actor, you do not have to add it again here.
700
+ wait: The maximum number of seconds the server waits for the run to finish. If not provided,
701
+ waits indefinitely.
702
+
703
+ Returns:
704
+ Info about the started Actor run.
705
+ """
706
+ self._raise_if_not_initialized()
707
+
708
+ client = self.new_client(token=token) if token else self._apify_client
709
+
710
+ if webhooks:
711
+ serialized_webhooks = [
712
+ hook.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=True) for hook in webhooks
713
+ ]
714
+ else:
715
+ serialized_webhooks = None
716
+
717
+ api_result = await client.actor(actor_id).call(
718
+ run_input=run_input,
719
+ content_type=content_type,
720
+ build=build,
721
+ memory_mbytes=memory_mbytes,
722
+ timeout_secs=int(timeout.total_seconds()) if timeout is not None else None,
723
+ webhooks=serialized_webhooks,
724
+ wait_secs=int(wait.total_seconds()) if wait is not None else None,
725
+ )
726
+
727
+ return ActorRun.model_validate(api_result)
728
+
729
+ async def call_task(
730
+ self,
731
+ task_id: str,
732
+ task_input: dict | None = None,
733
+ *,
734
+ build: str | None = None,
735
+ memory_mbytes: int | None = None,
736
+ timeout: timedelta | None = None,
737
+ webhooks: list[Webhook] | None = None,
738
+ wait: timedelta | None = None,
739
+ token: str | None = None,
740
+ ) -> ActorRun | None:
741
+ """Start an Actor task on the Apify Platform and wait for it to finish before returning.
742
+
743
+ It waits indefinitely, unless the wait argument is provided.
744
+
745
+ Note that an Actor task is a saved input configuration and options for an Actor. If you want to run an Actor
746
+ directly rather than an Actor task, please use the `Actor.call`
747
+
748
+ Args:
749
+ task_id: The ID of the Actor to be run.
750
+ task_input: Overrides the input to pass to the Actor run.
751
+ token: The Apify API token to use for this request (defaults to the `APIFY_TOKEN` environment variable).
752
+ content_type: The content type of the input.
753
+ build: Specifies the Actor build to run. It can be either a build tag or build number. By default,
754
+ the run uses the build specified in the default run configuration for the Actor (typically latest).
755
+ memory_mbytes: Memory limit for the run, in megabytes. By default, the run uses a memory limit specified
756
+ in the default run configuration for the Actor.
757
+ timeout: Optional timeout for the run, in seconds. By default, the run uses timeout specified in
758
+ the default run configuration for the Actor.
759
+ webhooks: Optional webhooks (https://docs.apify.com/webhooks) associated with the Actor run, which can
760
+ be used to receive a notification, e.g. when the Actor finished or failed. If you already have
761
+ a webhook set up for the Actor, you do not have to add it again here.
762
+ wait: The maximum number of seconds the server waits for the run to finish. If not provided, waits
763
+ indefinitely.
764
+
765
+ Returns:
766
+ Info about the started Actor run.
767
+ """
768
+ self._raise_if_not_initialized()
769
+
770
+ client = self.new_client(token=token) if token else self._apify_client
771
+
772
+ if webhooks:
773
+ serialized_webhooks = [
774
+ hook.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=True) for hook in webhooks
775
+ ]
776
+ else:
777
+ serialized_webhooks = None
778
+
779
+ api_result = await client.task(task_id).call(
780
+ task_input=task_input,
781
+ build=build,
782
+ memory_mbytes=memory_mbytes,
783
+ timeout_secs=int(timeout.total_seconds()) if timeout is not None else None,
784
+ webhooks=serialized_webhooks,
785
+ wait_secs=int(wait.total_seconds()) if wait is not None else None,
786
+ )
787
+
788
+ return ActorRun.model_validate(api_result)
789
+
790
+ async def metamorph(
791
+ self,
792
+ target_actor_id: str,
793
+ run_input: Any = None,
794
+ *,
795
+ target_actor_build: str | None = None,
796
+ content_type: str | None = None,
797
+ custom_after_sleep: timedelta | None = None,
798
+ ) -> None:
799
+ """Transform this Actor run to an Actor run of a different Actor.
800
+
801
+ The platform stops the current Actor container and starts a new container with the new Actor instead. All
802
+ the default storages are preserved, and the new input is stored under the `INPUT-METAMORPH-1` key in the same
803
+ default key-value store.
804
+
805
+ Args:
806
+ target_actor_id: ID of the target Actor that the run should be transformed into
807
+ run_input: The input to pass to the new run.
808
+ target_actor_build: The build of the target Actor. It can be either a build tag or build number.
809
+ By default, the run uses the build specified in the default run configuration for the target Actor
810
+ (typically the latest build).
811
+ content_type: The content type of the input.
812
+ custom_after_sleep: How long to sleep for after the metamorph, to wait for the container to be stopped.
813
+ """
814
+ self._raise_if_not_initialized()
815
+
816
+ if not self.is_at_home():
817
+ self.log.error('Actor.metamorph() is only supported when running on the Apify platform.')
818
+ return
819
+
820
+ if not custom_after_sleep:
821
+ custom_after_sleep = self._configuration.metamorph_after_sleep
822
+
823
+ # If is_at_home() is True, config.actor_run_id is always set
824
+ if not self._configuration.actor_run_id:
825
+ raise RuntimeError('actor_run_id cannot be None when running on the Apify platform.')
826
+
827
+ await self._apify_client.run(self._configuration.actor_run_id).metamorph(
828
+ target_actor_id=target_actor_id,
829
+ run_input=run_input,
830
+ target_actor_build=target_actor_build,
831
+ content_type=content_type,
832
+ )
833
+
834
+ if custom_after_sleep:
835
+ await asyncio.sleep(custom_after_sleep.total_seconds())
836
+
837
+ async def reboot(
838
+ self,
839
+ *,
840
+ event_listeners_timeout: timedelta | None = EVENT_LISTENERS_TIMEOUT, # noqa: ARG002
841
+ custom_after_sleep: timedelta | None = None,
842
+ ) -> None:
843
+ """Internally reboot this Actor.
844
+
845
+ The system stops the current container and starts a new one, with the same run ID and default storages.
846
+
847
+ Args:
848
+ event_listeners_timeout: How long should the Actor wait for Actor event listeners to finish before exiting
849
+ custom_after_sleep: How long to sleep for after the reboot, to wait for the container to be stopped.
850
+ """
851
+ self._raise_if_not_initialized()
852
+
853
+ if not self.is_at_home():
854
+ self.log.error('Actor.reboot() is only supported when running on the Apify platform.')
855
+ return
856
+
857
+ if self._is_rebooting:
858
+ self.log.debug('Actor is already rebooting, skipping the additional reboot call.')
859
+ return
860
+
861
+ self._is_rebooting = True
862
+
863
+ if not custom_after_sleep:
864
+ custom_after_sleep = self._configuration.metamorph_after_sleep
865
+
866
+ # Call all the listeners for the PERSIST_STATE and MIGRATING events, and wait for them to finish.
867
+ # PERSIST_STATE listeners are called to allow the Actor to persist its state before the reboot.
868
+ # MIGRATING listeners are called to allow the Actor to gracefully stop in-progress tasks before the reboot.
869
+ # Typically, crawlers are listening for the MIIGRATING event to stop processing new requests.
870
+ # We can't just emit the events and wait for all listeners to finish,
871
+ # because this method might be called from an event listener itself, and we would deadlock.
872
+ persist_state_listeners = flatten(
873
+ (self._event_manager._listeners_to_wrappers[Event.PERSIST_STATE] or {}).values() # noqa: SLF001
874
+ )
875
+ migrating_listeners = flatten(
876
+ (self._event_manager._listeners_to_wrappers[Event.MIGRATING] or {}).values() # noqa: SLF001
877
+ )
878
+
879
+ await asyncio.gather(
880
+ *[listener(EventPersistStateData(is_migrating=True)) for listener in persist_state_listeners],
881
+ *[listener(EventMigratingData()) for listener in migrating_listeners],
882
+ )
883
+
884
+ if not self._configuration.actor_run_id:
885
+ raise RuntimeError('actor_run_id cannot be None when running on the Apify platform.')
886
+
887
+ await self._apify_client.run(self._configuration.actor_run_id).reboot()
888
+
889
+ if custom_after_sleep:
890
+ await asyncio.sleep(custom_after_sleep.total_seconds())
891
+
892
+ async def add_webhook(
893
+ self,
894
+ webhook: Webhook,
895
+ *,
896
+ ignore_ssl_errors: bool | None = None,
897
+ do_not_retry: bool | None = None,
898
+ idempotency_key: str | None = None,
899
+ ) -> None:
900
+ """Create an ad-hoc webhook for the current Actor run.
901
+
902
+ This webhook lets you receive a notification when the Actor run finished or failed.
903
+
904
+ Note that webhooks are only supported for Actors running on the Apify platform. When running the Actor locally,
905
+ the function will print a warning and have no effect.
906
+
907
+ For more information about Apify Actor webhooks, please see the [documentation](https://docs.apify.com/webhooks).
908
+
909
+ Args:
910
+ webhook: The webhook to be added
911
+ ignore_ssl_errors: Whether the webhook should ignore SSL errors returned by request_url
912
+ do_not_retry: Whether the webhook should retry sending the payload to request_url upon failure.
913
+ idempotency_key: A unique identifier of a webhook. You can use it to ensure that you won't create
914
+ the same webhook multiple times.
915
+
916
+ Returns:
917
+ The created webhook.
918
+ """
919
+ self._raise_if_not_initialized()
920
+
921
+ if not self.is_at_home():
922
+ self.log.error('Actor.add_webhook() is only supported when running on the Apify platform.')
923
+ return
924
+
925
+ # If is_at_home() is True, config.actor_run_id is always set
926
+ if not self._configuration.actor_run_id:
927
+ raise RuntimeError('actor_run_id cannot be None when running on the Apify platform.')
928
+
929
+ await self._apify_client.webhooks().create(
930
+ actor_run_id=self._configuration.actor_run_id,
931
+ event_types=webhook.event_types,
932
+ request_url=webhook.request_url,
933
+ payload_template=webhook.payload_template,
934
+ ignore_ssl_errors=ignore_ssl_errors,
935
+ do_not_retry=do_not_retry,
936
+ idempotency_key=idempotency_key,
937
+ )
938
+
939
+ async def set_status_message(
940
+ self,
941
+ status_message: str,
942
+ *,
943
+ is_terminal: bool | None = None,
944
+ ) -> ActorRun | None:
945
+ """Set the status message for the current Actor run.
946
+
947
+ Args:
948
+ status_message: The status message to set to the run.
949
+ is_terminal: Set this flag to True if this is the final status message of the Actor run.
950
+
951
+ Returns:
952
+ The updated Actor run object.
953
+ """
954
+ self._raise_if_not_initialized()
955
+
956
+ if not self.is_at_home():
957
+ title = 'Terminal status message' if is_terminal else 'Status message'
958
+ self.log.info(f'[{title}]: {status_message}')
959
+ return None
960
+
961
+ # If is_at_home() is True, config.actor_run_id is always set
962
+ if not self._configuration.actor_run_id:
963
+ raise RuntimeError('actor_run_id cannot be None when running on the Apify platform.')
964
+
965
+ api_result = await self._apify_client.run(self._configuration.actor_run_id).update(
966
+ status_message=status_message, is_status_message_terminal=is_terminal
967
+ )
968
+
969
+ return ActorRun.model_validate(api_result)
970
+
971
+ async def create_proxy_configuration(
972
+ self,
973
+ *,
974
+ actor_proxy_input: dict
975
+ | None = None, # this is the raw proxy input from the actor run input, it is not spread or snake_cased in here
976
+ password: str | None = None,
977
+ groups: list[str] | None = None,
978
+ country_code: str | None = None,
979
+ proxy_urls: list[str | None] | None = None,
980
+ new_url_function: _NewUrlFunction | None = None,
981
+ ) -> ProxyConfiguration | None:
982
+ """Create a ProxyConfiguration object with the passed proxy configuration.
983
+
984
+ Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target
985
+ websites from blocking your crawlers based on IP address rate limits or blacklists.
986
+
987
+ For more details and code examples, see the `ProxyConfiguration` class.
988
+
989
+ Args:
990
+ actor_proxy_input: Proxy configuration field from the Actor input, if input has such input field. If you
991
+ pass this argument, all the other arguments will be inferred from it.
992
+ password: Password for the Apify Proxy. If not provided, will use os.environ['APIFY_PROXY_PASSWORD'],
993
+ if available.
994
+ groups: Proxy groups which the Apify Proxy should use, if provided.
995
+ country_code: Country which the Apify Proxy should use, if provided.
996
+ proxy_urls: Custom proxy server URLs which should be rotated through.
997
+ new_url_function: Function which returns a custom proxy URL to be used.
998
+
999
+ Returns:
1000
+ ProxyConfiguration object with the passed configuration, or None, if no proxy should be used based
1001
+ on the configuration.
1002
+ """
1003
+ self._raise_if_not_initialized()
1004
+
1005
+ if actor_proxy_input is not None:
1006
+ if actor_proxy_input.get('useApifyProxy', False):
1007
+ country_code = country_code or actor_proxy_input.get('apifyProxyCountry')
1008
+ groups = groups or actor_proxy_input.get('apifyProxyGroups')
1009
+ else:
1010
+ proxy_urls = actor_proxy_input.get('proxyUrls', [])
1011
+ if not proxy_urls:
1012
+ return None
1013
+
1014
+ proxy_configuration = ProxyConfiguration(
1015
+ password=password,
1016
+ groups=groups,
1017
+ country_code=country_code,
1018
+ proxy_urls=proxy_urls,
1019
+ new_url_function=new_url_function,
1020
+ _actor_config=self._configuration,
1021
+ _apify_client=self._apify_client,
1022
+ )
1023
+
1024
+ await proxy_configuration.initialize()
1025
+
1026
+ return proxy_configuration
1027
+
1028
+
1029
+ Actor = cast(_ActorType, Proxy(_ActorType))
1030
+ """The entry point of the SDK, through which all the Actor operations should be done."""