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