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