diff --git a/docs/01_overview/code/01_usage_async.py b/docs/01_overview/code/01_usage_async.py index 4a45b1e2..688399bf 100644 --- a/docs/01_overview/code/01_usage_async.py +++ b/docs/01_overview/code/01_usage_async.py @@ -5,10 +5,10 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) + apify_client = ApifyClientAsync(token=TOKEN) # Start an Actor and wait for it to finish. - actor_client = apify_client.actor('john-doe/my-cool-actor') + actor_client = apify_client.actor(actor_id='john-doe/my-cool-actor') call_result = await actor_client.call() if call_result is None: @@ -16,6 +16,6 @@ async def main() -> None: return # Fetch results from the Actor run's default dataset. - dataset_client = apify_client.dataset(call_result.default_dataset_id) + dataset_client = apify_client.dataset(dataset_id=call_result.default_dataset_id) list_items_result = await dataset_client.list_items() print(f'Dataset: {list_items_result}') diff --git a/docs/01_overview/code/01_usage_sync.py b/docs/01_overview/code/01_usage_sync.py index 84e430fa..0a906e80 100644 --- a/docs/01_overview/code/01_usage_sync.py +++ b/docs/01_overview/code/01_usage_sync.py @@ -5,10 +5,10 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) + apify_client = ApifyClient(token=TOKEN) # Start an Actor and wait for it to finish. - actor_client = apify_client.actor('john-doe/my-cool-actor') + actor_client = apify_client.actor(actor_id='john-doe/my-cool-actor') call_result = actor_client.call() if call_result is None: @@ -16,6 +16,6 @@ def main() -> None: return # Fetch results from the Actor run's default dataset. - dataset_client = apify_client.dataset(call_result.default_dataset_id) + dataset_client = apify_client.dataset(dataset_id=call_result.default_dataset_id) list_items_result = dataset_client.list_items() print(f'Dataset: {list_items_result}') diff --git a/docs/01_overview/code/02_auth_async.py b/docs/01_overview/code/02_auth_async.py index a584ccba..5a34a959 100644 --- a/docs/01_overview/code/02_auth_async.py +++ b/docs/01_overview/code/02_auth_async.py @@ -5,4 +5,4 @@ async def main() -> None: # Client initialization with the API token. - apify_client = ApifyClientAsync(TOKEN) + apify_client = ApifyClientAsync(token=TOKEN) diff --git a/docs/01_overview/code/02_auth_sync.py b/docs/01_overview/code/02_auth_sync.py index a5f4de39..a72c976a 100644 --- a/docs/01_overview/code/02_auth_sync.py +++ b/docs/01_overview/code/02_auth_sync.py @@ -5,4 +5,4 @@ def main() -> None: # Client initialization with the API token. - apify_client = ApifyClient(TOKEN) + apify_client = ApifyClient(token=TOKEN) diff --git a/docs/01_overview/code/03_dataset_async.py b/docs/01_overview/code/03_dataset_async.py index 99541d2a..f576bff9 100644 --- a/docs/01_overview/code/03_dataset_async.py +++ b/docs/01_overview/code/03_dataset_async.py @@ -4,8 +4,8 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) - dataset_client = apify_client.dataset('dataset-id') + apify_client = ApifyClientAsync(token=TOKEN) + dataset_client = apify_client.dataset(dataset_id='dataset-id') # Lists items from the Actor's dataset. dataset_items = (await dataset_client.list_items()).items diff --git a/docs/01_overview/code/03_dataset_sync.py b/docs/01_overview/code/03_dataset_sync.py index 3cc7554d..cef72045 100644 --- a/docs/01_overview/code/03_dataset_sync.py +++ b/docs/01_overview/code/03_dataset_sync.py @@ -4,8 +4,8 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) - dataset_client = apify_client.dataset('dataset-id') + apify_client = ApifyClient(token=TOKEN) + dataset_client = apify_client.dataset(dataset_id='dataset-id') # Lists items from the Actor's dataset. dataset_items = dataset_client.list_items().items diff --git a/docs/01_overview/code/03_input_async.py b/docs/01_overview/code/03_input_async.py index bef7ac72..5fbb1232 100644 --- a/docs/01_overview/code/03_input_async.py +++ b/docs/01_overview/code/03_input_async.py @@ -4,8 +4,8 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) - actor_client = apify_client.actor('username/actor-name') + apify_client = ApifyClientAsync(token=TOKEN) + actor_client = apify_client.actor(actor_id='username/actor-name') # Define the input for the Actor. run_input = { diff --git a/docs/01_overview/code/03_input_sync.py b/docs/01_overview/code/03_input_sync.py index 7fab1635..5257f43d 100644 --- a/docs/01_overview/code/03_input_sync.py +++ b/docs/01_overview/code/03_input_sync.py @@ -4,8 +4,8 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) - actor_client = apify_client.actor('username/actor-name') + apify_client = ApifyClient(token=TOKEN) + actor_client = apify_client.actor(actor_id='username/actor-name') # Define the input for the Actor. run_input = { diff --git a/docs/02_concepts/code/01_async_support.py b/docs/02_concepts/code/01_async_support.py index e8fe81b0..be33aff5 100644 --- a/docs/02_concepts/code/01_async_support.py +++ b/docs/02_concepts/code/01_async_support.py @@ -6,12 +6,12 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) - actor_client = apify_client.actor('my-actor-id') + apify_client = ApifyClientAsync(token=TOKEN) + actor_client = apify_client.actor(actor_id='my-actor-id') # Start the Actor and get the run ID run_result = await actor_client.start() - run_client = apify_client.run(run_result.id) + run_client = apify_client.run(run_id=run_result.id) log_client = run_client.log() # Stream the logs diff --git a/docs/02_concepts/code/02_collection_async.py b/docs/02_concepts/code/02_collection_async.py index 85ed3290..536a6034 100644 --- a/docs/02_concepts/code/02_collection_async.py +++ b/docs/02_concepts/code/02_collection_async.py @@ -4,7 +4,7 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) + apify_client = ApifyClientAsync(token=TOKEN) # Collection clients do not require a parameter actor_collection_client = apify_client.actors() diff --git a/docs/02_concepts/code/02_collection_sync.py b/docs/02_concepts/code/02_collection_sync.py index 988e41e7..18861378 100644 --- a/docs/02_concepts/code/02_collection_sync.py +++ b/docs/02_concepts/code/02_collection_sync.py @@ -4,7 +4,7 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) + apify_client = ApifyClient(token=TOKEN) # Collection clients do not require a parameter actor_collection_client = apify_client.actors() diff --git a/docs/02_concepts/code/02_single_async.py b/docs/02_concepts/code/02_single_async.py index c6b1a0ac..ca95bc2a 100644 --- a/docs/02_concepts/code/02_single_async.py +++ b/docs/02_concepts/code/02_single_async.py @@ -4,10 +4,10 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) + apify_client = ApifyClientAsync(token=TOKEN) # Resource clients accept an ID of the resource - actor_client = apify_client.actor('username/actor-name') + actor_client = apify_client.actor(actor_id='username/actor-name') # Fetch the 'username/actor-name' object from the API my_actor = await actor_client.get() diff --git a/docs/02_concepts/code/02_single_sync.py b/docs/02_concepts/code/02_single_sync.py index 033e54de..5406a153 100644 --- a/docs/02_concepts/code/02_single_sync.py +++ b/docs/02_concepts/code/02_single_sync.py @@ -4,10 +4,10 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) + apify_client = ApifyClient(token=TOKEN) # Resource clients accept an ID of the resource - actor_client = apify_client.actor('username/actor-name') + actor_client = apify_client.actor(actor_id='username/actor-name') # Fetch the 'username/actor-name' object from the API my_actor = actor_client.get() diff --git a/docs/02_concepts/code/03_nested_async.py b/docs/02_concepts/code/03_nested_async.py index 662657c8..490dcb29 100644 --- a/docs/02_concepts/code/03_nested_async.py +++ b/docs/02_concepts/code/03_nested_async.py @@ -4,9 +4,9 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) + apify_client = ApifyClientAsync(token=TOKEN) - actor_client = apify_client.actor('username/actor-name') + actor_client = apify_client.actor(actor_id='username/actor-name') runs_client = actor_client.runs() # List the last 10 runs of the Actor diff --git a/docs/02_concepts/code/03_nested_sync.py b/docs/02_concepts/code/03_nested_sync.py index 74654576..82296dfa 100644 --- a/docs/02_concepts/code/03_nested_sync.py +++ b/docs/02_concepts/code/03_nested_sync.py @@ -4,9 +4,9 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) + apify_client = ApifyClient(token=TOKEN) - actor_client = apify_client.actor('username/actor-name') + actor_client = apify_client.actor(actor_id='username/actor-name') runs_client = actor_client.runs() # List the last 10 runs of the Actor diff --git a/docs/02_concepts/code/04_error_async.py b/docs/02_concepts/code/04_error_async.py index 0057ea44..c900b7dc 100644 --- a/docs/02_concepts/code/04_error_async.py +++ b/docs/02_concepts/code/04_error_async.py @@ -4,11 +4,11 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) + apify_client = ApifyClientAsync(token=TOKEN) try: # Try to list items from non-existing dataset - dataset_client = apify_client.dataset('not-existing-dataset-id') + dataset_client = apify_client.dataset(dataset_id='not-existing-dataset-id') dataset_items = (await dataset_client.list_items()).items except Exception as ApifyApiError: # The exception is an instance of ApifyApiError diff --git a/docs/02_concepts/code/04_error_sync.py b/docs/02_concepts/code/04_error_sync.py index 83fc3080..833bc0e8 100644 --- a/docs/02_concepts/code/04_error_sync.py +++ b/docs/02_concepts/code/04_error_sync.py @@ -4,11 +4,11 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) + apify_client = ApifyClient(token=TOKEN) try: # Try to list items from non-existing dataset - dataset_client = apify_client.dataset('not-existing-dataset-id') + dataset_client = apify_client.dataset(dataset_id='not-existing-dataset-id') dataset_items = dataset_client.list_items().items except Exception as ApifyApiError: # The exception is an instance of ApifyApiError diff --git a/docs/02_concepts/code/07_call_async.py b/docs/02_concepts/code/07_call_async.py index 955f7532..b36d8cef 100644 --- a/docs/02_concepts/code/07_call_async.py +++ b/docs/02_concepts/code/07_call_async.py @@ -4,8 +4,8 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) - actor_client = apify_client.actor('username/actor-name') + apify_client = ApifyClientAsync(token=TOKEN) + actor_client = apify_client.actor(actor_id='username/actor-name') # Start an Actor and waits for it to finish finished_actor_run = await actor_client.call() diff --git a/docs/02_concepts/code/07_call_sync.py b/docs/02_concepts/code/07_call_sync.py index af790eaa..14b277c3 100644 --- a/docs/02_concepts/code/07_call_sync.py +++ b/docs/02_concepts/code/07_call_sync.py @@ -4,8 +4,8 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) - actor_client = apify_client.actor('username/actor-name') + apify_client = ApifyClient(token=TOKEN) + actor_client = apify_client.actor(actor_id='username/actor-name') # Start an Actor and waits for it to finish finished_actor_run = actor_client.call() diff --git a/docs/02_concepts/code/08_pagination_async.py b/docs/02_concepts/code/08_pagination_async.py index 50e9d047..1d910880 100644 --- a/docs/02_concepts/code/08_pagination_async.py +++ b/docs/02_concepts/code/08_pagination_async.py @@ -4,10 +4,10 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) + apify_client = ApifyClientAsync(token=TOKEN) # Initialize the dataset client - dataset_client = apify_client.dataset('dataset-id') + dataset_client = apify_client.dataset(dataset_id='dataset-id') # Define the pagination parameters limit = 1000 # Number of items per page diff --git a/docs/02_concepts/code/08_pagination_sync.py b/docs/02_concepts/code/08_pagination_sync.py index 3beb4fbe..ca7a05f4 100644 --- a/docs/02_concepts/code/08_pagination_sync.py +++ b/docs/02_concepts/code/08_pagination_sync.py @@ -4,10 +4,10 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) + apify_client = ApifyClient(token=TOKEN) # Initialize the dataset client - dataset_client = apify_client.dataset('dataset-id') + dataset_client = apify_client.dataset(dataset_id='dataset-id') # Define the pagination parameters limit = 1000 # Number of items per page diff --git a/docs/02_concepts/code/09_streaming_async.py b/docs/02_concepts/code/09_streaming_async.py index 5459784e..923cacd0 100644 --- a/docs/02_concepts/code/09_streaming_async.py +++ b/docs/02_concepts/code/09_streaming_async.py @@ -4,8 +4,8 @@ async def main() -> None: - apify_client = ApifyClientAsync(TOKEN) - run_client = apify_client.run('MY-RUN-ID') + apify_client = ApifyClientAsync(token=TOKEN) + run_client = apify_client.run(run_id='MY-RUN-ID') log_client = run_client.log() async with log_client.stream() as log_stream: diff --git a/docs/02_concepts/code/09_streaming_sync.py b/docs/02_concepts/code/09_streaming_sync.py index e7617ab3..285d0015 100644 --- a/docs/02_concepts/code/09_streaming_sync.py +++ b/docs/02_concepts/code/09_streaming_sync.py @@ -4,8 +4,8 @@ def main() -> None: - apify_client = ApifyClient(TOKEN) - run_client = apify_client.run('MY-RUN-ID') + apify_client = ApifyClient(token=TOKEN) + run_client = apify_client.run(run_id='MY-RUN-ID') log_client = run_client.log() with log_client.stream() as log_stream: diff --git a/docs/03_examples/code/01_input_async.py b/docs/03_examples/code/01_input_async.py index c225a0a2..07caa4ce 100644 --- a/docs/03_examples/code/01_input_async.py +++ b/docs/03_examples/code/01_input_async.py @@ -11,7 +11,7 @@ async def main() -> None: apify_client = ApifyClientAsync(token=TOKEN) # Get the Actor client - actor_client = apify_client.actor('apify/instagram-hashtag-scraper') + actor_client = apify_client.actor(actor_id='apify/instagram-hashtag-scraper') input_data = {'hashtags': ['rainbow'], 'resultsLimit': 20} diff --git a/docs/03_examples/code/01_input_sync.py b/docs/03_examples/code/01_input_sync.py index ea99665c..b2f7715e 100644 --- a/docs/03_examples/code/01_input_sync.py +++ b/docs/03_examples/code/01_input_sync.py @@ -10,7 +10,7 @@ def main() -> None: apify_client = ApifyClient(token=TOKEN) # Get the Actor client - actor_client = apify_client.actor('apify/instagram-hashtag-scraper') + actor_client = apify_client.actor(actor_id='apify/instagram-hashtag-scraper') input_data = {'hashtags': ['rainbow'], 'resultsLimit': 20} diff --git a/docs/03_examples/code/02_tasks_async.py b/docs/03_examples/code/02_tasks_async.py index f7a4c271..fcadfd58 100644 --- a/docs/03_examples/code/02_tasks_async.py +++ b/docs/03_examples/code/02_tasks_async.py @@ -25,7 +25,7 @@ async def main() -> None: print('Tasks created:', apify_tasks) # Create Apify task clients - apify_task_clients = [apify_client.task(task.id) for task in apify_tasks] + apify_task_clients = [apify_client.task(task_id=task.id) for task in apify_tasks] print('Task clients created:', apify_task_clients) diff --git a/docs/03_examples/code/02_tasks_sync.py b/docs/03_examples/code/02_tasks_sync.py index e869727b..cac995af 100644 --- a/docs/03_examples/code/02_tasks_sync.py +++ b/docs/03_examples/code/02_tasks_sync.py @@ -23,7 +23,7 @@ def main() -> None: print('Tasks created:', apify_tasks) # Create Apify task clients - apify_task_clients = [apify_client.task(task.id) for task in apify_tasks] + apify_task_clients = [apify_client.task(task_id=task.id) for task in apify_tasks] print('Task clients created:', apify_task_clients) diff --git a/docs/03_examples/code/03_retrieve_async.py b/docs/03_examples/code/03_retrieve_async.py index fc60d068..0cea3d8d 100644 --- a/docs/03_examples/code/03_retrieve_async.py +++ b/docs/03_examples/code/03_retrieve_async.py @@ -8,7 +8,7 @@ async def main() -> None: # Client initialization with the API token apify_client = ApifyClientAsync(token=TOKEN) - actor_client = apify_client.actor('apify/instagram-hashtag-scraper') + actor_client = apify_client.actor(actor_id='apify/instagram-hashtag-scraper') runs_client = actor_client.runs() # See pagination to understand how to get more datasets @@ -19,12 +19,12 @@ async def main() -> None: for dataset_item in actor_datasets.items: # Dataset items can be handled here. Dataset items can be paginated - dataset_client = apify_client.dataset(dataset_item.id) + dataset_client = apify_client.dataset(dataset_id=dataset_item.id) dataset_items = await dataset_client.list_items(limit=1000) # Items can be pushed to single dataset - merging_dataset_client = apify_client.dataset(merging_dataset.id) - await merging_dataset_client.push_items(dataset_items.items) + merging_dataset_client = apify_client.dataset(dataset_id=merging_dataset.id) + await merging_dataset_client.push_items(items=dataset_items.items) # ... diff --git a/docs/03_examples/code/03_retrieve_sync.py b/docs/03_examples/code/03_retrieve_sync.py index 24e05e2f..878abdcc 100644 --- a/docs/03_examples/code/03_retrieve_sync.py +++ b/docs/03_examples/code/03_retrieve_sync.py @@ -6,7 +6,7 @@ def main() -> None: # Client initialization with the API token apify_client = ApifyClient(token=TOKEN) - actor_client = apify_client.actor('apify/instagram-hashtag-scraper') + actor_client = apify_client.actor(actor_id='apify/instagram-hashtag-scraper') runs_client = actor_client.runs() # See pagination to understand how to get more datasets @@ -17,12 +17,12 @@ def main() -> None: for dataset_item in actor_datasets.items: # Dataset items can be handled here. Dataset items can be paginated - dataset_client = apify_client.dataset(dataset_item.id) + dataset_client = apify_client.dataset(dataset_id=dataset_item.id) dataset_items = dataset_client.list_items(limit=1000) # Items can be pushed to single dataset - merging_dataset_client = apify_client.dataset(merging_dataset.id) - merging_dataset_client.push_items(dataset_items.items) + merging_dataset_client = apify_client.dataset(dataset_id=merging_dataset.id) + merging_dataset_client.push_items(items=dataset_items.items) # ... diff --git a/docs/03_examples/code/04_pandas_async.py b/docs/03_examples/code/04_pandas_async.py index aecc0655..da3bfe73 100644 --- a/docs/03_examples/code/04_pandas_async.py +++ b/docs/03_examples/code/04_pandas_async.py @@ -10,7 +10,7 @@ async def main() -> None: # Initialize the Apify client apify_client = ApifyClientAsync(token=TOKEN) - actor_client = apify_client.actor('apify/web-scraper') + actor_client = apify_client.actor(actor_id='apify/web-scraper') run_client = actor_client.last_run() dataset_client = run_client.dataset() diff --git a/docs/03_examples/code/04_pandas_sync.py b/docs/03_examples/code/04_pandas_sync.py index a42e074f..ca68d1a2 100644 --- a/docs/03_examples/code/04_pandas_sync.py +++ b/docs/03_examples/code/04_pandas_sync.py @@ -8,7 +8,7 @@ def main() -> None: # Initialize the Apify client apify_client = ApifyClient(token=TOKEN) - actor_client = apify_client.actor('apify/web-scraper') + actor_client = apify_client.actor(actor_id='apify/web-scraper') run_client = actor_client.last_run() dataset_client = run_client.dataset() diff --git a/src/apify_client/_apify_client.py b/src/apify_client/_apify_client.py index 93f68f1a..9944d8f1 100644 --- a/src/apify_client/_apify_client.py +++ b/src/apify_client/_apify_client.py @@ -86,8 +86,8 @@ class ApifyClient: def __init__( self, - token: str | None = None, *, + token: str | None = None, api_url: str = DEFAULT_API_URL, api_public_url: str | None = DEFAULT_API_URL, max_retries: int = DEFAULT_MAX_RETRIES, @@ -114,7 +114,7 @@ def __init__( api_public_url = DEFAULT_API_URL if api_public_url is None else api_public_url if headers: - self._check_custom_headers(headers) + self._check_custom_headers(headers=headers) self._token = token """Apify API token for authentication.""" @@ -181,7 +181,7 @@ def _base_kwargs(self) -> dict: 'client_registry': self._client_registry, } - def _check_custom_headers(self, headers: dict[str, str]) -> None: + def _check_custom_headers(self, *, headers: dict[str, str]) -> None: """Warn if custom headers override important default headers.""" overwrite_headers = [key for key in headers if key.title() in self._OVERRIDABLE_DEFAULT_HEADERS] if overwrite_headers: @@ -198,7 +198,7 @@ def token(self) -> str | None: """The Apify API token used by the client.""" return self._token - def actor(self, actor_id: str) -> ActorClient: + def actor(self, *, actor_id: str) -> ActorClient: """Retrieve the sub-client for manipulating a single Actor. Args: @@ -210,7 +210,7 @@ def actors(self) -> ActorCollectionClient: """Retrieve the sub-client for manipulating Actors.""" return ActorCollectionClient(**self._base_kwargs) - def build(self, build_id: str) -> BuildClient: + def build(self, *, build_id: str) -> BuildClient: """Retrieve the sub-client for manipulating a single Actor build. Args: @@ -222,7 +222,7 @@ def builds(self) -> BuildCollectionClient: """Retrieve the sub-client for querying multiple builds of a user.""" return BuildCollectionClient(**self._base_kwargs) - def run(self, run_id: str) -> RunClient: + def run(self, *, run_id: str) -> RunClient: """Retrieve the sub-client for manipulating a single Actor run. Args: @@ -234,7 +234,7 @@ def runs(self) -> RunCollectionClient: """Retrieve the sub-client for querying multiple Actor runs of a user.""" return RunCollectionClient(**self._base_kwargs) - def dataset(self, dataset_id: str) -> DatasetClient: + def dataset(self, *, dataset_id: str) -> DatasetClient: """Retrieve the sub-client for manipulating a single dataset. Args: @@ -246,7 +246,7 @@ def datasets(self) -> DatasetCollectionClient: """Retrieve the sub-client for manipulating datasets.""" return DatasetCollectionClient(**self._base_kwargs) - def key_value_store(self, key_value_store_id: str) -> KeyValueStoreClient: + def key_value_store(self, *, key_value_store_id: str) -> KeyValueStoreClient: """Retrieve the sub-client for manipulating a single key-value store. Args: @@ -258,7 +258,7 @@ def key_value_stores(self) -> KeyValueStoreCollectionClient: """Retrieve the sub-client for manipulating key-value stores.""" return KeyValueStoreCollectionClient(**self._base_kwargs) - def request_queue(self, request_queue_id: str, *, client_key: str | None = None) -> RequestQueueClient: + def request_queue(self, *, request_queue_id: str, client_key: str | None = None) -> RequestQueueClient: """Retrieve the sub-client for manipulating a single request queue. Args: @@ -271,7 +271,7 @@ def request_queues(self) -> RequestQueueCollectionClient: """Retrieve the sub-client for manipulating request queues.""" return RequestQueueCollectionClient(**self._base_kwargs) - def webhook(self, webhook_id: str) -> WebhookClient: + def webhook(self, *, webhook_id: str) -> WebhookClient: """Retrieve the sub-client for manipulating a single webhook. Args: @@ -283,7 +283,7 @@ def webhooks(self) -> WebhookCollectionClient: """Retrieve the sub-client for querying multiple webhooks of a user.""" return WebhookCollectionClient(**self._base_kwargs) - def webhook_dispatch(self, webhook_dispatch_id: str) -> WebhookDispatchClient: + def webhook_dispatch(self, *, webhook_dispatch_id: str) -> WebhookDispatchClient: """Retrieve the sub-client for accessing a single webhook dispatch. Args: @@ -295,7 +295,7 @@ def webhook_dispatches(self) -> WebhookDispatchCollectionClient: """Retrieve the sub-client for querying multiple webhook dispatches of a user.""" return WebhookDispatchCollectionClient(**self._base_kwargs) - def schedule(self, schedule_id: str) -> ScheduleClient: + def schedule(self, *, schedule_id: str) -> ScheduleClient: """Retrieve the sub-client for manipulating a single schedule. Args: @@ -307,7 +307,7 @@ def schedules(self) -> ScheduleCollectionClient: """Retrieve the sub-client for manipulating schedules.""" return ScheduleCollectionClient(**self._base_kwargs) - def log(self, build_or_run_id: str) -> LogClient: + def log(self, *, build_or_run_id: str) -> LogClient: """Retrieve the sub-client for retrieving logs. Args: @@ -315,7 +315,7 @@ def log(self, build_or_run_id: str) -> LogClient: """ return LogClient(resource_id=build_or_run_id, **self._base_kwargs) - def task(self, task_id: str) -> TaskClient: + def task(self, *, task_id: str) -> TaskClient: """Retrieve the sub-client for manipulating a single task. Args: @@ -327,7 +327,7 @@ def tasks(self) -> TaskCollectionClient: """Retrieve the sub-client for manipulating tasks.""" return TaskCollectionClient(**self._base_kwargs) - def user(self, user_id: str | None = None) -> UserClient: + def user(self, *, user_id: str | None = None) -> UserClient: """Retrieve the sub-client for querying users. Args: @@ -347,8 +347,8 @@ class ApifyClientAsync: def __init__( self, - token: str | None = None, *, + token: str | None = None, api_url: str = DEFAULT_API_URL, api_public_url: str | None = DEFAULT_API_URL, max_retries: int = DEFAULT_MAX_RETRIES, @@ -375,7 +375,7 @@ def __init__( api_public_url = DEFAULT_API_URL if api_public_url is None else api_public_url if headers: - self._check_custom_headers(headers) + self._check_custom_headers(headers=headers) self._token = token """Apify API token for authentication.""" @@ -442,7 +442,7 @@ def _base_kwargs(self) -> dict: 'client_registry': self._client_registry, } - def _check_custom_headers(self, headers: dict[str, str]) -> None: + def _check_custom_headers(self, *, headers: dict[str, str]) -> None: """Warn if custom headers override important default headers.""" overwrite_headers = [key for key in headers if key.title() in self._OVERRIDABLE_DEFAULT_HEADERS] if overwrite_headers: @@ -459,7 +459,7 @@ def token(self) -> str | None: """The Apify API token used by the client.""" return self._token - def actor(self, actor_id: str) -> ActorClientAsync: + def actor(self, *, actor_id: str) -> ActorClientAsync: """Retrieve the sub-client for manipulating a single Actor. Args: @@ -471,7 +471,7 @@ def actors(self) -> ActorCollectionClientAsync: """Retrieve the sub-client for manipulating Actors.""" return ActorCollectionClientAsync(**self._base_kwargs) - def build(self, build_id: str) -> BuildClientAsync: + def build(self, *, build_id: str) -> BuildClientAsync: """Retrieve the sub-client for manipulating a single Actor build. Args: @@ -483,7 +483,7 @@ def builds(self) -> BuildCollectionClientAsync: """Retrieve the sub-client for querying multiple builds of a user.""" return BuildCollectionClientAsync(**self._base_kwargs) - def run(self, run_id: str) -> RunClientAsync: + def run(self, *, run_id: str) -> RunClientAsync: """Retrieve the sub-client for manipulating a single Actor run. Args: @@ -495,7 +495,7 @@ def runs(self) -> RunCollectionClientAsync: """Retrieve the sub-client for querying multiple Actor runs of a user.""" return RunCollectionClientAsync(**self._base_kwargs) - def dataset(self, dataset_id: str) -> DatasetClientAsync: + def dataset(self, *, dataset_id: str) -> DatasetClientAsync: """Retrieve the sub-client for manipulating a single dataset. Args: @@ -507,7 +507,7 @@ def datasets(self) -> DatasetCollectionClientAsync: """Retrieve the sub-client for manipulating datasets.""" return DatasetCollectionClientAsync(**self._base_kwargs) - def key_value_store(self, key_value_store_id: str) -> KeyValueStoreClientAsync: + def key_value_store(self, *, key_value_store_id: str) -> KeyValueStoreClientAsync: """Retrieve the sub-client for manipulating a single key-value store. Args: @@ -519,7 +519,7 @@ def key_value_stores(self) -> KeyValueStoreCollectionClientAsync: """Retrieve the sub-client for manipulating key-value stores.""" return KeyValueStoreCollectionClientAsync(**self._base_kwargs) - def request_queue(self, request_queue_id: str, *, client_key: str | None = None) -> RequestQueueClientAsync: + def request_queue(self, *, request_queue_id: str, client_key: str | None = None) -> RequestQueueClientAsync: """Retrieve the sub-client for manipulating a single request queue. Args: @@ -532,7 +532,7 @@ def request_queues(self) -> RequestQueueCollectionClientAsync: """Retrieve the sub-client for manipulating request queues.""" return RequestQueueCollectionClientAsync(**self._base_kwargs) - def webhook(self, webhook_id: str) -> WebhookClientAsync: + def webhook(self, *, webhook_id: str) -> WebhookClientAsync: """Retrieve the sub-client for manipulating a single webhook. Args: @@ -544,7 +544,7 @@ def webhooks(self) -> WebhookCollectionClientAsync: """Retrieve the sub-client for querying multiple webhooks of a user.""" return WebhookCollectionClientAsync(**self._base_kwargs) - def webhook_dispatch(self, webhook_dispatch_id: str) -> WebhookDispatchClientAsync: + def webhook_dispatch(self, *, webhook_dispatch_id: str) -> WebhookDispatchClientAsync: """Retrieve the sub-client for accessing a single webhook dispatch. Args: @@ -556,7 +556,7 @@ def webhook_dispatches(self) -> WebhookDispatchCollectionClientAsync: """Retrieve the sub-client for querying multiple webhook dispatches of a user.""" return WebhookDispatchCollectionClientAsync(**self._base_kwargs) - def schedule(self, schedule_id: str) -> ScheduleClientAsync: + def schedule(self, *, schedule_id: str) -> ScheduleClientAsync: """Retrieve the sub-client for manipulating a single schedule. Args: @@ -568,7 +568,7 @@ def schedules(self) -> ScheduleCollectionClientAsync: """Retrieve the sub-client for manipulating schedules.""" return ScheduleCollectionClientAsync(**self._base_kwargs) - def log(self, build_or_run_id: str) -> LogClientAsync: + def log(self, *, build_or_run_id: str) -> LogClientAsync: """Retrieve the sub-client for retrieving logs. Args: @@ -576,7 +576,7 @@ def log(self, build_or_run_id: str) -> LogClientAsync: """ return LogClientAsync(resource_id=build_or_run_id, **self._base_kwargs) - def task(self, task_id: str) -> TaskClientAsync: + def task(self, *, task_id: str) -> TaskClientAsync: """Retrieve the sub-client for manipulating a single task. Args: @@ -588,7 +588,7 @@ def tasks(self) -> TaskCollectionClientAsync: """Retrieve the sub-client for manipulating tasks.""" return TaskCollectionClientAsync(**self._base_kwargs) - def user(self, user_id: str | None = None) -> UserClientAsync: + def user(self, *, user_id: str | None = None) -> UserClientAsync: """Retrieve the sub-client for querying users. Args: diff --git a/src/apify_client/_http_clients/_base.py b/src/apify_client/_http_clients/_base.py index a91de5cf..3a183832 100644 --- a/src/apify_client/_http_clients/_base.py +++ b/src/apify_client/_http_clients/_base.py @@ -71,7 +71,7 @@ def __init__( self._headers = {**default_headers, **(headers or {})} @staticmethod - def _parse_params(params: dict[str, Any] | None) -> dict[str, Any] | None: + def _parse_params(*, params: dict[str, Any] | None) -> dict[str, Any] | None: """Convert request parameters to Apify API-compatible formats. Converts booleans to 0/1, lists to comma-separated strings, datetimes to ISO 8601 Zulu format. @@ -95,7 +95,7 @@ def _parse_params(params: dict[str, Any] | None) -> dict[str, Any] | None: return parsed_params @staticmethod - def _is_retryable_error(exc: Exception) -> bool: + def _is_retryable_error(*, exc: Exception) -> bool: """Check if an exception represents a transient error that should be retried. All ``impit.HTTPError`` subclasses are considered retryable because they represent transport-level failures @@ -112,6 +112,7 @@ def _is_retryable_error(exc: Exception) -> bool: def _prepare_request_call( self, + *, headers: dict[str, str] | None = None, params: dict[str, Any] | None = None, data: str | bytes | bytearray | None = None, @@ -135,9 +136,9 @@ def _prepare_request_call( data = gzip.compress(data) headers['Content-Encoding'] = 'gzip' - return (headers, self._parse_params(params), data) + return (headers, self._parse_params(params=params), data) - def _build_url_with_params(self, url: str, params: dict[str, Any] | None = None) -> str: + def _build_url_with_params(self, *, url: str, params: dict[str, Any] | None = None) -> str: """Build a URL with query parameters appended. List values are expanded into multiple key=value pairs.""" if not params: return url @@ -153,8 +154,8 @@ def _build_url_with_params(self, url: str, params: dict[str, Any] | None = None) return f'{url}?{query_string}' - def _calculate_timeout(self, attempt: int, timeout: timedelta | None = None) -> float: + def _calculate_timeout(self, *, attempt: int, timeout: timedelta | None = None) -> float: """Calculate timeout for a request attempt with exponential increase, bounded by client timeout.""" - timeout_secs = to_seconds(timeout or self._timeout) - client_timeout_secs = to_seconds(self._timeout) + timeout_secs = to_seconds(td=timeout or self._timeout) + client_timeout_secs = to_seconds(td=self._timeout) return min(client_timeout_secs, timeout_secs * 2 ** (attempt - 1)) diff --git a/src/apify_client/_http_clients/_http_client.py b/src/apify_client/_http_clients/_http_client.py index 291fac3f..7de33607 100644 --- a/src/apify_client/_http_clients/_http_client.py +++ b/src/apify_client/_http_clients/_http_client.py @@ -62,7 +62,7 @@ def __init__( self._impit_client = impit.Client( headers=self._headers, follow_redirects=True, - timeout=to_seconds(self._timeout), + timeout=to_seconds(td=self._timeout), ) def call( @@ -101,10 +101,12 @@ def call( self._statistics.calls += 1 - prepared_headers, prepared_params, content = self._prepare_request_call(headers, params, data, json) + prepared_headers, prepared_params, content = self._prepare_request_call( + headers=headers, params=params, data=data, json=json + ) return self._retry_with_exp_backoff( - lambda stop_retrying, attempt: self._make_request( + func=lambda stop_retrying, attempt: self._make_request( stop_retrying=stop_retrying, attempt=attempt, method=method, @@ -157,14 +159,14 @@ def _make_request( self._statistics.requests += 1 try: - url_with_params = self._build_url_with_params(url, params) + url_with_params = self._build_url_with_params(url=url, params=params) response = self._impit_client.request( method=method, url=url_with_params, headers=headers, content=content, - timeout=self._calculate_timeout(attempt, timeout), + timeout=self._calculate_timeout(attempt=attempt, timeout=timeout), stream=stream or False, ) @@ -173,11 +175,11 @@ def _make_request( return response if response.status_code == HTTPStatus.TOO_MANY_REQUESTS: - self._statistics.add_rate_limit_error(attempt) + self._statistics.add_rate_limit_error(attempt=attempt) except Exception as exc: logger.debug('Request threw exception', exc_info=exc) - if not self._is_retryable_error(exc): + if not self._is_retryable_error(exc=exc): logger.debug('Exception is not retryable', exc_info=exc) stop_retrying() raise @@ -193,12 +195,12 @@ def _make_request( # Read the response in case it is a stream, so we can raise the error properly. response.read() - raise ApifyApiError(response, attempt, method=method) + raise ApifyApiError(response=response, attempt=attempt, method=method) @staticmethod def _retry_with_exp_backoff( - func: Callable[[Callable[[], None], int], T], *, + func: Callable[[Callable[[], None], int], T], max_retries: int = 8, backoff_base: timedelta = timedelta(milliseconds=500), backoff_factor: float = 2, @@ -238,7 +240,7 @@ def stop_retrying() -> None: raise random_sleep_factor = random.uniform(1, 1 + random_factor) - backoff_base_secs = to_seconds(backoff_base) + backoff_base_secs = to_seconds(td=backoff_base) backoff_exp_factor = backoff_factor ** (attempt - 1) sleep_time_secs = random_sleep_factor * backoff_base_secs * backoff_exp_factor @@ -282,7 +284,7 @@ def __init__( self._impit_async_client = impit.AsyncClient( headers=self._headers, follow_redirects=True, - timeout=to_seconds(self._timeout), + timeout=to_seconds(td=self._timeout), ) async def call( @@ -321,10 +323,12 @@ async def call( self._statistics.calls += 1 - prepared_headers, prepared_params, content = self._prepare_request_call(headers, params, data, json) + prepared_headers, prepared_params, content = self._prepare_request_call( + headers=headers, params=params, data=data, json=json + ) return await self._retry_with_exp_backoff( - lambda stop_retrying, attempt: self._make_request( + func=lambda stop_retrying, attempt: self._make_request( stop_retrying=stop_retrying, attempt=attempt, method=method, @@ -377,14 +381,14 @@ async def _make_request( self._statistics.requests += 1 try: - url_with_params = self._build_url_with_params(url, params) + url_with_params = self._build_url_with_params(url=url, params=params) response = await self._impit_async_client.request( method=method, url=url_with_params, headers=headers, content=content, - timeout=self._calculate_timeout(attempt, timeout), + timeout=self._calculate_timeout(attempt=attempt, timeout=timeout), stream=stream or False, ) @@ -393,11 +397,11 @@ async def _make_request( return response if response.status_code == HTTPStatus.TOO_MANY_REQUESTS: - self._statistics.add_rate_limit_error(attempt) + self._statistics.add_rate_limit_error(attempt=attempt) except Exception as exc: logger.debug('Request threw exception', exc_info=exc) - if not self._is_retryable_error(exc): + if not self._is_retryable_error(exc=exc): logger.debug('Exception is not retryable', exc_info=exc) stop_retrying() raise @@ -413,12 +417,12 @@ async def _make_request( # Read the response in case it is a stream, so we can raise the error properly. await response.aread() - raise ApifyApiError(response, attempt, method=method) + raise ApifyApiError(response=response, attempt=attempt, method=method) @staticmethod async def _retry_with_exp_backoff( - func: Callable[[Callable[[], None], int], Awaitable[T]], *, + func: Callable[[Callable[[], None], int], Awaitable[T]], max_retries: int = 8, backoff_base: timedelta = timedelta(milliseconds=500), backoff_factor: float = 2, @@ -458,7 +462,7 @@ def stop_retrying() -> None: raise random_sleep_factor = random.uniform(1, 1 + random_factor) - backoff_base_secs = to_seconds(backoff_base) + backoff_base_secs = to_seconds(td=backoff_base) backoff_exp_factor = backoff_factor ** (attempt - 1) sleep_time_secs = random_sleep_factor * backoff_base_secs * backoff_exp_factor diff --git a/src/apify_client/_logging.py b/src/apify_client/_logging.py index 989d0a36..6cbe1ad6 100644 --- a/src/apify_client/_logging.py +++ b/src/apify_client/_logging.py @@ -49,7 +49,7 @@ def __new__(cls, name: str, bases: tuple, attrs: dict) -> WithLogDetailsClient: """Wrap all public methods in the class with logging context injection.""" for attr_name, attr_value in attrs.items(): if not attr_name.startswith('_') and inspect.isfunction(attr_value): - attrs[attr_name] = _injects_client_details_to_log_context(attr_value) + attrs[attr_name] = _injects_client_details_to_log_context(fun=attr_value) return type.__new__(cls, name, bases, attrs) @@ -71,7 +71,7 @@ def format(self, record: logging.LogRecord) -> str: return f'{formatted_logger_name} -> {formatted_message}' -def create_redirect_logger(name: str) -> logging.Logger: +def create_redirect_logger(*, name: str) -> logging.Logger: """Create a logger for redirecting logs from another Actor. Args: @@ -109,7 +109,7 @@ def filter(self, record: logging.LogRecord) -> bool: return True -def _injects_client_details_to_log_context(fun: Callable) -> Callable: +def _injects_client_details_to_log_context(*, fun: Callable) -> Callable: """Wrap a method to inject resource client details into log context before execution.""" if inspect.iscoroutinefunction(fun): diff --git a/src/apify_client/_representations.py b/src/apify_client/_representations.py index a0a24423..2b9b14bb 100644 --- a/src/apify_client/_representations.py +++ b/src/apify_client/_representations.py @@ -30,7 +30,7 @@ def build_actor_standby_dict( 'isEnabled': is_enabled, 'desiredRequestsPerActorRun': desired_requests_per_actor_run, 'maxRequestsPerActorRun': max_requests_per_actor_run, - 'idleTimeoutSecs': to_seconds(idle_timeout, as_int=True), + 'idleTimeoutSecs': to_seconds(td=idle_timeout, as_int=True), 'build': build, 'memoryMbytes': memory_mbytes, } @@ -50,7 +50,7 @@ def build_default_run_options_dict( 'build': build, 'maxItems': max_items, 'memoryMbytes': memory_mbytes, - 'timeoutSecs': to_seconds(timeout, as_int=True), + 'timeoutSecs': to_seconds(td=timeout, as_int=True), 'restartOnError': restart_on_error, 'forcePermissionLevel': force_permission_level, } @@ -69,7 +69,7 @@ def build_task_options_dict( 'build': build, 'maxItems': max_items, 'memoryMbytes': memory_mbytes, - 'timeoutSecs': to_seconds(timeout, as_int=True), + 'timeoutSecs': to_seconds(td=timeout, as_int=True), 'restartOnError': restart_on_error, } @@ -231,7 +231,7 @@ def get_actor_version_repr( 'buildTag': build_tag, 'envVars': env_vars, 'applyEnvVarsToBuild': apply_env_vars_to_build, - 'sourceType': enum_to_value(source_type), + 'sourceType': enum_to_value(value=source_type), 'sourceFiles': source_files, 'gitRepoUrl': git_repo_url, 'tarballUrl': tarball_url, @@ -297,6 +297,6 @@ def get_webhook_repr( webhook['isAdHoc'] = True if event_types is not None: - webhook['eventTypes'] = [enum_to_value(event_type) for event_type in event_types] + webhook['eventTypes'] = [enum_to_value(value=event_type) for event_type in event_types] return webhook diff --git a/src/apify_client/_resource_clients/_resource_client.py b/src/apify_client/_resource_clients/_resource_client.py index 7b2020ff..2d21677c 100644 --- a/src/apify_client/_resource_clients/_resource_client.py +++ b/src/apify_client/_resource_clients/_resource_client.py @@ -66,7 +66,7 @@ def _resource_url(self) -> str: """Build the full resource URL from base URL, path, and optional ID.""" url = f'{self._base_url}/{self._resource_path}' if self._resource_id is not None: - url = f'{url}/{to_safe_id(self._resource_id)}' + url = f'{url}/{to_safe_id(id=self._resource_id)}' return url @cached_property @@ -85,8 +85,8 @@ def _base_client_kwargs(self) -> dict[str, Any]: def _build_url( self, - path: str | None = None, *, + path: str | None = None, public: bool = False, ) -> str: """Build complete URL for API request. @@ -164,12 +164,12 @@ def _get(self, *, timeout: timedelta | None = None) -> dict | None: params=self._build_params(), timeout=timeout, ) - return response_to_dict(response) + return response_to_dict(response=response) except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None - def _update(self, updated_fields: dict, *, timeout: timedelta | None = None) -> dict: + def _update(self, *, updated_fields: dict, timeout: timedelta | None = None) -> dict: """Perform a PUT request to update this resource with the given fields.""" response = self._http_client.call( url=self._build_url(), @@ -178,7 +178,7 @@ def _update(self, updated_fields: dict, *, timeout: timedelta | None = None) -> json=updated_fields, timeout=timeout, ) - return response_to_dict(response) + return response_to_dict(response=response) def _delete(self, *, timeout: timedelta | None = None) -> None: """Perform a DELETE request to delete this resource, ignoring 404 errors.""" @@ -190,7 +190,7 @@ def _delete(self, *, timeout: timedelta | None = None) -> None: timeout=timeout, ) except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) def _list(self, **kwargs: Any) -> dict: """Perform a GET request to list resources.""" @@ -199,9 +199,9 @@ def _list(self, **kwargs: Any) -> dict: method='GET', params=self._build_params(**kwargs), ) - return response_to_dict(response) + return response_to_dict(response=response) - def _create(self, created_fields: dict) -> dict: + def _create(self, *, created_fields: dict) -> dict: """Perform a POST request to create a resource.""" response = self._http_client.call( url=self._build_url(), @@ -209,7 +209,7 @@ def _create(self, created_fields: dict) -> dict: params=self._build_params(), json=created_fields, ) - return response_to_dict(response) + return response_to_dict(response=response) def _get_or_create(self, *, name: str | None = None, resource_fields: dict | None = None) -> dict: """Perform a POST request to get or create a named resource.""" @@ -219,10 +219,11 @@ def _get_or_create(self, *, name: str | None = None, resource_fields: dict | Non params=self._build_params(name=name), json=resource_fields, ) - return response_to_dict(response) + return response_to_dict(response=response) def _wait_for_finish( self, + *, url: str, params: dict, wait_duration: timedelta | None = None, @@ -251,10 +252,10 @@ def _wait_for_finish( while True: if deadline is not None: - remaining_secs = max(0, int(to_seconds(deadline - datetime.now(UTC)))) + remaining_secs = max(0, int(to_seconds(td=deadline - datetime.now(UTC)))) wait_for_finish = remaining_secs else: - wait_for_finish = to_seconds(DEFAULT_WAIT_FOR_FINISH, as_int=True) + wait_for_finish = to_seconds(td=DEFAULT_WAIT_FOR_FINISH, as_int=True) try: response = self._http_client.call( @@ -262,7 +263,7 @@ def _wait_for_finish( method='GET', params={**params, 'waitForFinish': wait_for_finish}, ) - result = response_to_dict(response) + result = response_to_dict(response=response) actor_job_response = ActorJobResponse.model_validate(result) actor_job = actor_job_response.data.model_dump() @@ -273,7 +274,7 @@ def _wait_for_finish( break except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) # If there are still not found errors after DEFAULT_WAIT_WHEN_JOB_NOT_EXIST, we give up # and return None. In such case, the requested record probably really doesn't exist. @@ -330,12 +331,12 @@ async def _get(self, *, timeout: timedelta | None = None) -> dict | None: params=self._build_params(), timeout=timeout, ) - return response_to_dict(response) + return response_to_dict(response=response) except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None - async def _update(self, updated_fields: dict, *, timeout: timedelta | None = None) -> dict: + async def _update(self, *, updated_fields: dict, timeout: timedelta | None = None) -> dict: """Perform a PUT request to update this resource with the given fields.""" response = await self._http_client.call( url=self._build_url(), @@ -344,7 +345,7 @@ async def _update(self, updated_fields: dict, *, timeout: timedelta | None = Non json=updated_fields, timeout=timeout, ) - return response_to_dict(response) + return response_to_dict(response=response) async def _delete(self, *, timeout: timedelta | None = None) -> None: """Perform a DELETE request to delete this resource, ignoring 404 errors.""" @@ -356,7 +357,7 @@ async def _delete(self, *, timeout: timedelta | None = None) -> None: timeout=timeout, ) except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) async def _list(self, **kwargs: Any) -> dict: """Perform a GET request to list resources.""" @@ -365,9 +366,9 @@ async def _list(self, **kwargs: Any) -> dict: method='GET', params=self._build_params(**kwargs), ) - return response_to_dict(response) + return response_to_dict(response=response) - async def _create(self, created_fields: dict) -> dict: + async def _create(self, *, created_fields: dict) -> dict: """Perform a POST request to create a resource.""" response = await self._http_client.call( url=self._build_url(), @@ -375,7 +376,7 @@ async def _create(self, created_fields: dict) -> dict: params=self._build_params(), json=created_fields, ) - return response_to_dict(response) + return response_to_dict(response=response) async def _get_or_create(self, *, name: str | None = None, resource_fields: dict | None = None) -> dict: """Perform a POST request to get or create a named resource.""" @@ -385,10 +386,11 @@ async def _get_or_create(self, *, name: str | None = None, resource_fields: dict params=self._build_params(name=name), json=resource_fields, ) - return response_to_dict(response) + return response_to_dict(response=response) async def _wait_for_finish( self, + *, url: str, params: dict, wait_duration: timedelta | None = None, @@ -417,10 +419,10 @@ async def _wait_for_finish( while True: if deadline is not None: - remaining_secs = max(0, int(to_seconds(deadline - datetime.now(UTC)))) + remaining_secs = max(0, int(to_seconds(td=deadline - datetime.now(UTC)))) wait_for_finish = remaining_secs else: - wait_for_finish = to_seconds(DEFAULT_WAIT_FOR_FINISH, as_int=True) + wait_for_finish = to_seconds(td=DEFAULT_WAIT_FOR_FINISH, as_int=True) try: response = await self._http_client.call( @@ -428,7 +430,7 @@ async def _wait_for_finish( method='GET', params={**params, 'waitForFinish': wait_for_finish}, ) - result = response_to_dict(response) + result = response_to_dict(response=response) actor_job_response = ActorJobResponse.model_validate(result) actor_job = actor_job_response.data.model_dump() @@ -439,7 +441,7 @@ async def _wait_for_finish( break except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) # If there are still not found errors after DEFAULT_WAIT_WHEN_JOB_NOT_EXIST, we give up # and return None. In such case, the requested record probably really doesn't exist. diff --git a/src/apify_client/_resource_clients/actor.py b/src/apify_client/_resource_clients/actor.py index 5e3594aa..8298801a 100644 --- a/src/apify_client/_resource_clients/actor.py +++ b/src/apify_client/_resource_clients/actor.py @@ -176,9 +176,9 @@ def update( actor_permission_level=actor_permission_level, tagged_builds=tagged_builds, ) - cleaned = filter_none_values(actor_representation, remove_empty_dicts=True) + cleaned = filter_none_values(data=actor_representation, remove_empty_dicts=True) - result = self._update(cleaned) + result = self._update(updated_fields=cleaned) return ActorResponse.model_validate(result).data def delete(self) -> None: @@ -236,7 +236,7 @@ def start( Returns: The run object. """ - run_input, content_type = encode_key_value_store_record_value(run_input, content_type) + run_input, content_type = encode_key_value_store_record_value(value=run_input, content_type=content_type) request_params = self._build_params( build=build, @@ -244,21 +244,21 @@ def start( maxTotalChargeUsd=max_total_charge_usd, restartOnError=restart_on_error, memory=memory_mbytes, - timeout=to_seconds(timeout, as_int=True), + timeout=to_seconds(td=timeout, as_int=True), waitForFinish=wait_for_finish, forcePermissionLevel=force_permission_level.value if force_permission_level is not None else None, - webhooks=encode_webhook_list_to_base64(webhooks) if webhooks is not None else None, + webhooks=encode_webhook_list_to_base64(webhooks=webhooks) if webhooks is not None else None, ) response = self._http_client.call( - url=self._build_url('runs'), + url=self._build_url(path='runs'), method='POST', headers={'content-type': content_type}, data=run_input, params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data def call( @@ -378,12 +378,12 @@ def build( ) response = self._http_client.call( - url=self._build_url('builds'), + url=self._build_url(path='builds'), method='POST', params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return BuildResponse.model_validate(result).data def builds(self) -> BuildCollectionClient: @@ -420,8 +420,10 @@ def default_build( waitForFinish=wait_for_finish, ) - response = self._http_client.call(url=self._build_url('builds/default'), method='GET', params=request_params) - result = response_to_dict(response) + response = self._http_client.call( + url=self._build_url(path='builds/default'), method='GET', params=request_params + ) + result = response_to_dict(response=response) return self._client_registry.build_client( resource_id=result['data']['id'], @@ -452,8 +454,8 @@ def last_run( resource_id='last', resource_path='runs', params=self._build_params( - status=enum_to_value(status), - origin=enum_to_value(origin), + status=enum_to_value(value=status), + origin=enum_to_value(value=origin), ), **self._base_client_kwargs, ) @@ -462,7 +464,7 @@ def versions(self) -> ActorVersionCollectionClient: """Retrieve a client for the versions of this Actor.""" return self._client_registry.actor_version_collection_client(**self._base_client_kwargs) - def version(self, version_number: str) -> ActorVersionClient: + def version(self, *, version_number: str) -> ActorVersionClient: """Retrieve the client for the specified version of this Actor. Args: @@ -481,7 +483,7 @@ def webhooks(self) -> WebhookCollectionClient: return self._client_registry.webhook_collection_client(**self._base_client_kwargs) def validate_input( - self, run_input: Any = None, *, build_tag: str | None = None, content_type: str | None = None + self, *, run_input: Any = None, build_tag: str | None = None, content_type: str | None = None ) -> bool: """Validate an input for the Actor that defines an input schema. @@ -493,10 +495,10 @@ def validate_input( Returns: True if the input is valid, else raise an exception with validation error details. """ - run_input, content_type = encode_key_value_store_record_value(run_input, content_type) + run_input, content_type = encode_key_value_store_record_value(value=run_input, content_type=content_type) self._http_client.call( - url=self._build_url('validate-input'), + url=self._build_url(path='validate-input'), method='POST', headers={'content-type': content_type}, data=run_input, @@ -635,9 +637,9 @@ async def update( actor_permission_level=actor_permission_level, tagged_builds=tagged_builds, ) - cleaned = filter_none_values(actor_representation, remove_empty_dicts=True) + cleaned = filter_none_values(data=actor_representation, remove_empty_dicts=True) - result = await self._update(cleaned) + result = await self._update(updated_fields=cleaned) return ActorResponse.model_validate(result).data async def delete(self) -> None: @@ -695,7 +697,7 @@ async def start( Returns: The run object. """ - run_input, content_type = encode_key_value_store_record_value(run_input, content_type) + run_input, content_type = encode_key_value_store_record_value(value=run_input, content_type=content_type) request_params = self._build_params( build=build, @@ -703,21 +705,21 @@ async def start( maxTotalChargeUsd=max_total_charge_usd, restartOnError=restart_on_error, memory=memory_mbytes, - timeout=to_seconds(timeout, as_int=True), + timeout=to_seconds(td=timeout, as_int=True), waitForFinish=wait_for_finish, forcePermissionLevel=force_permission_level.value if force_permission_level is not None else None, - webhooks=encode_webhook_list_to_base64(webhooks) if webhooks is not None else None, + webhooks=encode_webhook_list_to_base64(webhooks=webhooks) if webhooks is not None else None, ) response = await self._http_client.call( - url=self._build_url('runs'), + url=self._build_url(path='runs'), method='POST', headers={'content-type': content_type}, data=run_input, params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data async def call( @@ -841,12 +843,12 @@ async def build( ) response = await self._http_client.call( - url=self._build_url('builds'), + url=self._build_url(path='builds'), method='POST', params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return BuildResponse.model_validate(result).data def builds(self) -> BuildCollectionClientAsync: @@ -884,11 +886,11 @@ async def default_build( ) response = await self._http_client.call( - url=self._build_url('builds/default'), + url=self._build_url(path='builds/default'), method='GET', params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return self._client_registry.build_client( resource_id=result['data']['id'], @@ -919,8 +921,8 @@ def last_run( resource_id='last', resource_path='runs', params=self._build_params( - status=enum_to_value(status), - origin=enum_to_value(origin), + status=enum_to_value(value=status), + origin=enum_to_value(value=origin), ), **self._base_client_kwargs, ) @@ -929,7 +931,7 @@ def versions(self) -> ActorVersionCollectionClientAsync: """Retrieve a client for the versions of this Actor.""" return self._client_registry.actor_version_collection_client(**self._base_client_kwargs) - def version(self, version_number: str) -> ActorVersionClientAsync: + def version(self, *, version_number: str) -> ActorVersionClientAsync: """Retrieve the client for the specified version of this Actor. Args: @@ -948,7 +950,7 @@ def webhooks(self) -> WebhookCollectionClientAsync: return self._client_registry.webhook_collection_client(**self._base_client_kwargs) async def validate_input( - self, run_input: Any = None, *, build_tag: str | None = None, content_type: str | None = None + self, *, run_input: Any = None, build_tag: str | None = None, content_type: str | None = None ) -> bool: """Validate an input for the Actor that defines an input schema. @@ -960,10 +962,10 @@ async def validate_input( Returns: True if the input is valid, else raise an exception with validation error details. """ - run_input, content_type = encode_key_value_store_record_value(run_input, content_type) + run_input, content_type = encode_key_value_store_record_value(value=run_input, content_type=content_type) await self._http_client.call( - url=self._build_url('validate-input'), + url=self._build_url(path='validate-input'), method='POST', headers={'content-type': content_type}, data=run_input, diff --git a/src/apify_client/_resource_clients/actor_collection.py b/src/apify_client/_resource_clients/actor_collection.py index 7a2a6c63..96513b06 100644 --- a/src/apify_client/_resource_clients/actor_collection.py +++ b/src/apify_client/_resource_clients/actor_collection.py @@ -134,7 +134,7 @@ def create( actor_standby_memory_mbytes=actor_standby_memory_mbytes, ) - result = self._create(filter_none_values(actor_representation, remove_empty_dicts=True)) + result = self._create(created_fields=filter_none_values(data=actor_representation, remove_empty_dicts=True)) return ActorResponse.model_validate(result).data @@ -261,5 +261,7 @@ async def create( actor_standby_memory_mbytes=actor_standby_memory_mbytes, ) - result = await self._create(filter_none_values(actor_representation, remove_empty_dicts=True)) + result = await self._create( + created_fields=filter_none_values(data=actor_representation, remove_empty_dicts=True) + ) return ActorResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/actor_env_var.py b/src/apify_client/_resource_clients/actor_env_var.py index e4b9e985..a6d6144c 100644 --- a/src/apify_client/_resource_clients/actor_env_var.py +++ b/src/apify_client/_resource_clients/actor_env_var.py @@ -65,8 +65,8 @@ def update( name=name, value=value, ) - cleaned = filter_none_values(actor_env_var_representation) - result = self._update(cleaned) + cleaned = filter_none_values(data=actor_env_var_representation) + result = self._update(updated_fields=cleaned) return EnvVarResponse.model_validate(result).data def delete(self) -> None: @@ -121,8 +121,8 @@ async def update( name=name, value=value, ) - cleaned = filter_none_values(actor_env_var_representation) - result = await self._update(cleaned) + cleaned = filter_none_values(data=actor_env_var_representation) + result = await self._update(updated_fields=cleaned) return EnvVarResponse.model_validate(result).data async def delete(self) -> None: diff --git a/src/apify_client/_resource_clients/actor_env_var_collection.py b/src/apify_client/_resource_clients/actor_env_var_collection.py index 5bdd8f2f..55d071dc 100644 --- a/src/apify_client/_resource_clients/actor_env_var_collection.py +++ b/src/apify_client/_resource_clients/actor_env_var_collection.py @@ -51,7 +51,7 @@ def create( value=value, ) - result = self._create(filter_none_values(actor_env_var_representation)) + result = self._create(created_fields=filter_none_values(data=actor_env_var_representation)) return EnvVarResponse.model_validate(result).data @@ -98,5 +98,5 @@ async def create( value=value, ) - result = await self._create(filter_none_values(actor_env_var_representation)) + result = await self._create(created_fields=filter_none_values(data=actor_env_var_representation)) return EnvVarResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/actor_version.py b/src/apify_client/_resource_clients/actor_version.py index f4ea03a2..dcc637ec 100644 --- a/src/apify_client/_resource_clients/actor_version.py +++ b/src/apify_client/_resource_clients/actor_version.py @@ -90,9 +90,9 @@ def update( tarball_url=tarball_url, github_gist_url=github_gist_url, ) - cleaned = filter_none_values(actor_version_representation) + cleaned = filter_none_values(data=actor_version_representation) - result = self._update(cleaned) + result = self._update(updated_fields=cleaned) return VersionResponse.model_validate(result).data def delete(self) -> None: @@ -106,7 +106,7 @@ def env_vars(self) -> ActorEnvVarCollectionClient: """Retrieve a client for the environment variables of this Actor version.""" return self._client_registry.actor_env_var_collection_client(**self._base_client_kwargs) - def env_var(self, env_var_name: str) -> ActorEnvVarClient: + def env_var(self, *, env_var_name: str) -> ActorEnvVarClient: """Retrieve the client for the specified environment variable of this Actor version. Args: @@ -195,9 +195,9 @@ async def update( tarball_url=tarball_url, github_gist_url=github_gist_url, ) - cleaned = filter_none_values(actor_version_representation) + cleaned = filter_none_values(data=actor_version_representation) - result = await self._update(cleaned) + result = await self._update(updated_fields=cleaned) return VersionResponse.model_validate(result).data async def delete(self) -> None: @@ -211,7 +211,7 @@ def env_vars(self) -> ActorEnvVarCollectionClientAsync: """Retrieve a client for the environment variables of this Actor version.""" return self._client_registry.actor_env_var_collection_client(**self._base_client_kwargs) - def env_var(self, env_var_name: str) -> ActorEnvVarClientAsync: + def env_var(self, *, env_var_name: str) -> ActorEnvVarClientAsync: """Retrieve the client for the specified environment variable of this Actor version. Args: diff --git a/src/apify_client/_resource_clients/actor_version_collection.py b/src/apify_client/_resource_clients/actor_version_collection.py index 40c69c03..94944528 100644 --- a/src/apify_client/_resource_clients/actor_version_collection.py +++ b/src/apify_client/_resource_clients/actor_version_collection.py @@ -81,7 +81,7 @@ def create( github_gist_url=github_gist_url, ) - result = self._create(filter_none_values(actor_version_representation)) + result = self._create(created_fields=filter_none_values(data=actor_version_representation)) return VersionResponse.model_validate(result).data @@ -152,5 +152,5 @@ async def create( github_gist_url=github_gist_url, ) - result = await self._create(filter_none_values(actor_version_representation)) + result = await self._create(created_fields=filter_none_values(data=actor_version_representation)) return VersionResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/build.py b/src/apify_client/_resource_clients/build.py index ef8f7ef6..6f0463b5 100644 --- a/src/apify_client/_resource_clients/build.py +++ b/src/apify_client/_resource_clients/build.py @@ -57,11 +57,11 @@ def abort(self) -> Build: The data of the aborted Actor build. """ response = self._http_client.call( - url=self._build_url('abort'), + url=self._build_url(path='abort'), method='POST', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return BuildResponse.model_validate(result).data def get_open_api_definition(self) -> dict: @@ -73,10 +73,10 @@ def get_open_api_definition(self) -> dict: OpenAPI definition of the Actor's build. """ response = self._http_client.call( - url=self._build_url('openapi.json'), + url=self._build_url(path='openapi.json'), method='GET', ) - return response_to_dict(response) + return response_to_dict(response=response) def wait_for_finish(self, *, wait_duration: timedelta | None = None) -> Build | None: """Wait synchronously until the build finishes or the server times out. @@ -147,11 +147,11 @@ async def abort(self) -> Build: The data of the aborted Actor build. """ response = await self._http_client.call( - url=self._build_url('abort'), + url=self._build_url(path='abort'), method='POST', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return BuildResponse.model_validate(result).data async def delete(self) -> None: @@ -170,10 +170,10 @@ async def get_open_api_definition(self) -> dict: OpenAPI definition of the Actor's build. """ response = await self._http_client.call( - url=self._build_url('openapi.json'), + url=self._build_url(path='openapi.json'), method='GET', ) - return response_to_dict(response) + return response_to_dict(response=response) async def wait_for_finish(self, *, wait_duration: timedelta | None = None) -> Build | None: """Wait asynchronously until the build finishes or the server times out. diff --git a/src/apify_client/_resource_clients/dataset.py b/src/apify_client/_resource_clients/dataset.py index e0534743..3a8173fa 100644 --- a/src/apify_client/_resource_clients/dataset.py +++ b/src/apify_client/_resource_clients/dataset.py @@ -92,9 +92,9 @@ def update(self, *, name: str | None = None, general_access: GeneralAccess | Non 'name': name, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = self._update(cleaned, timeout=FAST_OPERATION_TIMEOUT) + result = self._update(updated_fields=cleaned, timeout=FAST_OPERATION_TIMEOUT) return DatasetResponse.model_validate(result).data def delete(self) -> None: @@ -171,13 +171,13 @@ def list_items( ) response = self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='GET', params=request_params, ) # When using signature, API returns items as list directly - items = response_to_list(response) + items = response_to_list(response=response) return DatasetItemsPage( items=items, @@ -456,7 +456,7 @@ def get_items_as_bytes( ) response = self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='GET', params=request_params, ) @@ -551,7 +551,7 @@ def stream_items( ) response = self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='GET', params=request_params, stream=True, @@ -561,7 +561,7 @@ def stream_items( if response: response.close() - def push_items(self, items: JsonSerializable) -> None: + def push_items(self, *, items: JsonSerializable) -> None: """Push items to the dataset. https://docs.apify.com/api/v2#/reference/datasets/item-collection/put-items @@ -579,7 +579,7 @@ def push_items(self, items: JsonSerializable) -> None: json = items self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='POST', headers={'content-type': 'application/json; charset=utf-8'}, params=self._build_params(), @@ -598,15 +598,15 @@ def get_statistics(self) -> DatasetStatistics | None: """ try: response = self._http_client.call( - url=self._build_url('statistics'), + url=self._build_url(path='statistics'), method='GET', params=self._build_params(), timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return DatasetStatisticsResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -664,7 +664,7 @@ def create_items_public_url( ) request_params['signature'] = signature - items_public_url = urlparse(self._build_url('items', public=True)) + items_public_url = urlparse(self._build_url(path='items', public=True)) filtered_params = {k: v for k, v in request_params.items() if v is not None} if filtered_params: items_public_url = items_public_url._replace(query=urlencode(filtered_params)) @@ -708,9 +708,9 @@ async def update(self, *, name: str | None = None, general_access: GeneralAccess 'name': name, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = await self._update(cleaned, timeout=FAST_OPERATION_TIMEOUT) + result = await self._update(updated_fields=cleaned, timeout=FAST_OPERATION_TIMEOUT) return DatasetResponse.model_validate(result).data async def delete(self) -> None: @@ -787,13 +787,13 @@ async def list_items( ) response = await self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='GET', params=request_params, ) # When using signature, API returns items as list directly - items = response_to_list(response) + items = response_to_list(response=response) return DatasetItemsPage( items=items, @@ -978,7 +978,7 @@ async def get_items_as_bytes( ) response = await self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='GET', params=request_params, ) @@ -1073,7 +1073,7 @@ async def stream_items( ) response = await self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='GET', params=request_params, stream=True, @@ -1083,7 +1083,7 @@ async def stream_items( if response: await response.aclose() - async def push_items(self, items: JsonSerializable) -> None: + async def push_items(self, *, items: JsonSerializable) -> None: """Push items to the dataset. https://docs.apify.com/api/v2#/reference/datasets/item-collection/put-items @@ -1101,7 +1101,7 @@ async def push_items(self, items: JsonSerializable) -> None: json = items await self._http_client.call( - url=self._build_url('items'), + url=self._build_url(path='items'), method='POST', headers={'content-type': 'application/json; charset=utf-8'}, params=self._build_params(), @@ -1120,15 +1120,15 @@ async def get_statistics(self) -> DatasetStatistics | None: """ try: response = await self._http_client.call( - url=self._build_url('statistics'), + url=self._build_url(path='statistics'), method='GET', params=self._build_params(), timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return DatasetStatisticsResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -1186,7 +1186,7 @@ async def create_items_public_url( ) request_params['signature'] = signature - items_public_url = urlparse(self._build_url('items', public=True)) + items_public_url = urlparse(self._build_url(path='items', public=True)) filtered_params = {k: v for k, v in request_params.items() if v is not None} if filtered_params: items_public_url = items_public_url._replace(query=urlencode(filtered_params)) diff --git a/src/apify_client/_resource_clients/dataset_collection.py b/src/apify_client/_resource_clients/dataset_collection.py index 1effcdd0..2226c503 100644 --- a/src/apify_client/_resource_clients/dataset_collection.py +++ b/src/apify_client/_resource_clients/dataset_collection.py @@ -50,7 +50,7 @@ def get_or_create(self, *, name: str | None = None, schema: dict | None = None) Returns: The retrieved or newly-created dataset. """ - result = self._get_or_create(name=name, resource_fields=filter_none_values({'schema': schema})) + result = self._get_or_create(name=name, resource_fields=filter_none_values(data={'schema': schema})) return DatasetResponse.model_validate(result).data @@ -102,5 +102,5 @@ async def get_or_create( Returns: The retrieved or newly-created dataset. """ - result = await self._get_or_create(name=name, resource_fields=filter_none_values({'schema': schema})) + result = await self._get_or_create(name=name, resource_fields=filter_none_values(data={'schema': schema})) return DatasetResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/key_value_store.py b/src/apify_client/_resource_clients/key_value_store.py index d6490108..db0330ca 100644 --- a/src/apify_client/_resource_clients/key_value_store.py +++ b/src/apify_client/_resource_clients/key_value_store.py @@ -34,7 +34,7 @@ from apify_client._models import GeneralAccess -def _parse_get_record_response(response: Response) -> Any: +def _parse_get_record_response(*, response: Response) -> Any: """Parse an HTTP response based on its content type. Args: @@ -63,7 +63,7 @@ def _parse_get_record_response(response: Response) -> Any: else: response_data = response.content except ValueError as err: - raise InvalidResponseBodyError(response) from err + raise InvalidResponseBodyError(response=response) from err else: return response_data @@ -104,9 +104,9 @@ def update(self, *, name: str | None = None, general_access: GeneralAccess | Non 'name': name, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = self._update(cleaned, timeout=FAST_OPERATION_TIMEOUT) + result = self._update(updated_fields=cleaned, timeout=FAST_OPERATION_TIMEOUT) return KeyValueStoreResponse.model_validate(result).data def delete(self) -> None: @@ -148,13 +148,13 @@ def list_keys( ) response = self._http_client.call( - url=self._build_url('keys'), + url=self._build_url(path='keys'), method='GET', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ListOfKeysResponse.model_validate(result).data def iterate_keys( @@ -206,7 +206,7 @@ def iterate_keys( exclusive_start_key = current_keys_page.next_exclusive_start_key - def get_record(self, key: str, signature: str | None = None) -> dict | None: + def get_record(self, *, key: str, signature: str | None = None) -> dict | None: """Retrieve the given record from the key-value store. https://docs.apify.com/api/v2#/reference/key-value-stores/record/get-record @@ -220,23 +220,23 @@ def get_record(self, key: str, signature: str | None = None) -> dict | None: """ try: response = self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='GET', params=self._build_params(signature=signature, attachment=True), ) return { 'key': key, - 'value': _parse_get_record_response(response), + 'value': _parse_get_record_response(response=response), 'content_type': response.headers['content-type'], } except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None - def record_exists(self, key: str) -> bool: + def record_exists(self, *, key: str) -> bool: """Check if given record is present in the key-value store. https://docs.apify.com/api/v2/key-value-store-record-head @@ -249,7 +249,7 @@ def record_exists(self, key: str) -> bool: """ try: response = self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='HEAD', params=self._build_params(), ) @@ -261,7 +261,7 @@ def record_exists(self, key: str) -> bool: return response.status_code == HTTPStatus.OK - def get_record_as_bytes(self, key: str, signature: str | None = None) -> dict | None: + def get_record_as_bytes(self, *, key: str, signature: str | None = None) -> dict | None: """Retrieve the given record from the key-value store, without parsing it. https://docs.apify.com/api/v2#/reference/key-value-stores/record/get-record @@ -275,7 +275,7 @@ def get_record_as_bytes(self, key: str, signature: str | None = None) -> dict | """ try: response = self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='GET', params=self._build_params(signature=signature, attachment=True), ) @@ -287,12 +287,12 @@ def get_record_as_bytes(self, key: str, signature: str | None = None) -> dict | } except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @contextmanager - def stream_record(self, key: str, signature: str | None = None) -> Iterator[dict | None]: + def stream_record(self, *, key: str, signature: str | None = None) -> Iterator[dict | None]: """Retrieve the given record from the key-value store, as a stream. https://docs.apify.com/api/v2#/reference/key-value-stores/record/get-record @@ -307,7 +307,7 @@ def stream_record(self, key: str, signature: str | None = None) -> Iterator[dict response = None try: response = self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='GET', params=self._build_params(signature=signature, attachment=True), stream=True, @@ -320,7 +320,7 @@ def stream_record(self, key: str, signature: str | None = None) -> Iterator[dict } except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) yield None finally: if response: @@ -328,6 +328,7 @@ def stream_record(self, key: str, signature: str | None = None) -> Iterator[dict def set_record( self, + *, key: str, value: Any, content_type: str | None = None, @@ -341,19 +342,19 @@ def set_record( value: The value to save into the record. content_type: The content type of the saved value. """ - value, content_type = encode_key_value_store_record_value(value, content_type) + value, content_type = encode_key_value_store_record_value(value=value, content_type=content_type) headers = {'content-type': content_type} self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='PUT', params=self._build_params(), data=value, headers=headers, ) - def delete_record(self, key: str) -> None: + def delete_record(self, *, key: str) -> None: """Delete the specified record from the key-value store. https://docs.apify.com/api/v2#/reference/key-value-stores/record/delete-record @@ -362,13 +363,13 @@ def delete_record(self, key: str) -> None: key: The key of the record which to delete. """ self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='DELETE', params=self._build_params(), timeout=FAST_OPERATION_TIMEOUT, ) - def get_record_public_url(self, key: str) -> str: + def get_record_public_url(self, *, key: str) -> str: """Generate a URL that can be used to access key-value store record. If the client has permission to access the key-value store's URL signing key, the URL will include a signature @@ -388,9 +389,9 @@ def get_record_public_url(self, key: str) -> str: request_params = self._build_params() if metadata and metadata.url_signing_secret_key: - request_params['signature'] = create_hmac_signature(metadata.url_signing_secret_key, key) + request_params['signature'] = create_hmac_signature(secret_key=metadata.url_signing_secret_key, message=key) - key_public_url = urlparse(self._build_url(f'records/{key}', public=True)) + key_public_url = urlparse(self._build_url(path=f'records/{key}', public=True)) filtered_params = {k: v for k, v in request_params.items() if v is not None} if filtered_params: @@ -438,7 +439,7 @@ def create_keys_public_url( ) request_params['signature'] = signature - keys_public_url = urlparse(self._build_url('keys', public=True)) + keys_public_url = urlparse(self._build_url(path='keys', public=True)) filtered_params = {k: v for k, v in request_params.items() if v is not None} if filtered_params: @@ -488,9 +489,9 @@ async def update( 'name': name, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = await self._update(cleaned, timeout=FAST_OPERATION_TIMEOUT) + result = await self._update(updated_fields=cleaned, timeout=FAST_OPERATION_TIMEOUT) return KeyValueStoreResponse.model_validate(result).data async def delete(self) -> None: @@ -532,13 +533,13 @@ async def list_keys( ) response = await self._http_client.call( - url=self._build_url('keys'), + url=self._build_url(path='keys'), method='GET', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ListOfKeysResponse.model_validate(result).data async def iterate_keys( @@ -591,7 +592,7 @@ async def iterate_keys( exclusive_start_key = current_keys_page.next_exclusive_start_key - async def get_record(self, key: str, signature: str | None = None) -> dict | None: + async def get_record(self, *, key: str, signature: str | None = None) -> dict | None: """Retrieve the given record from the key-value store. https://docs.apify.com/api/v2#/reference/key-value-stores/record/get-record @@ -605,23 +606,23 @@ async def get_record(self, key: str, signature: str | None = None) -> dict | Non """ try: response = await self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='GET', params=self._build_params(signature=signature, attachment=True), ) return { 'key': key, - 'value': _parse_get_record_response(response), + 'value': _parse_get_record_response(response=response), 'content_type': response.headers['content-type'], } except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None - async def record_exists(self, key: str) -> bool: + async def record_exists(self, *, key: str) -> bool: """Check if given record is present in the key-value store. https://docs.apify.com/api/v2/key-value-store-record-head @@ -634,7 +635,7 @@ async def record_exists(self, key: str) -> bool: """ try: response = await self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='HEAD', params=self._build_params(), ) @@ -646,7 +647,7 @@ async def record_exists(self, key: str) -> bool: return response.status_code == HTTPStatus.OK - async def get_record_as_bytes(self, key: str, signature: str | None = None) -> dict | None: + async def get_record_as_bytes(self, *, key: str, signature: str | None = None) -> dict | None: """Retrieve the given record from the key-value store, without parsing it. https://docs.apify.com/api/v2#/reference/key-value-stores/record/get-record @@ -660,7 +661,7 @@ async def get_record_as_bytes(self, key: str, signature: str | None = None) -> d """ try: response = await self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='GET', params=self._build_params(signature=signature, attachment=True), ) @@ -672,12 +673,12 @@ async def get_record_as_bytes(self, key: str, signature: str | None = None) -> d } except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @asynccontextmanager - async def stream_record(self, key: str, signature: str | None = None) -> AsyncIterator[dict | None]: + async def stream_record(self, *, key: str, signature: str | None = None) -> AsyncIterator[dict | None]: """Retrieve the given record from the key-value store, as a stream. https://docs.apify.com/api/v2#/reference/key-value-stores/record/get-record @@ -692,7 +693,7 @@ async def stream_record(self, key: str, signature: str | None = None) -> AsyncIt response = None try: response = await self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='GET', params=self._build_params(signature=signature, attachment=True), stream=True, @@ -705,7 +706,7 @@ async def stream_record(self, key: str, signature: str | None = None) -> AsyncIt } except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) yield None finally: if response: @@ -713,6 +714,7 @@ async def stream_record(self, key: str, signature: str | None = None) -> AsyncIt async def set_record( self, + *, key: str, value: Any, content_type: str | None = None, @@ -726,19 +728,19 @@ async def set_record( value: The value to save into the record. content_type: The content type of the saved value. """ - value, content_type = encode_key_value_store_record_value(value, content_type) + value, content_type = encode_key_value_store_record_value(value=value, content_type=content_type) headers = {'content-type': content_type} await self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='PUT', params=self._build_params(), data=value, headers=headers, ) - async def delete_record(self, key: str) -> None: + async def delete_record(self, *, key: str) -> None: """Delete the specified record from the key-value store. https://docs.apify.com/api/v2#/reference/key-value-stores/record/delete-record @@ -747,13 +749,13 @@ async def delete_record(self, key: str) -> None: key: The key of the record which to delete. """ await self._http_client.call( - url=self._build_url(f'records/{key}'), + url=self._build_url(path=f'records/{key}'), method='DELETE', params=self._build_params(), timeout=FAST_OPERATION_TIMEOUT, ) - async def get_record_public_url(self, key: str) -> str: + async def get_record_public_url(self, *, key: str) -> str: """Generate a URL that can be used to access key-value store record. If the client has permission to access the key-value store's URL signing key, the URL will include a signature @@ -773,9 +775,9 @@ async def get_record_public_url(self, key: str) -> str: request_params = self._build_params() if metadata and metadata.url_signing_secret_key: - request_params['signature'] = create_hmac_signature(metadata.url_signing_secret_key, key) + request_params['signature'] = create_hmac_signature(secret_key=metadata.url_signing_secret_key, message=key) - key_public_url = urlparse(self._build_url(f'records/{key}', public=True)) + key_public_url = urlparse(self._build_url(path=f'records/{key}', public=True)) filtered_params = {k: v for k, v in request_params.items() if v is not None} if filtered_params: @@ -808,7 +810,7 @@ async def create_keys_public_url( """ metadata = await self.get() - keys_public_url = urlparse(self._build_url('keys')) + keys_public_url = urlparse(self._build_url(path='keys')) request_params = self._build_params( limit=limit, @@ -825,7 +827,7 @@ async def create_keys_public_url( ) request_params['signature'] = signature - keys_public_url = urlparse(self._build_url('keys', public=True)) + keys_public_url = urlparse(self._build_url(path='keys', public=True)) filtered_params = {k: v for k, v in request_params.items() if v is not None} if filtered_params: keys_public_url = keys_public_url._replace(query=urlencode(filtered_params)) diff --git a/src/apify_client/_resource_clients/key_value_store_collection.py b/src/apify_client/_resource_clients/key_value_store_collection.py index abf5a87f..c8b764c3 100644 --- a/src/apify_client/_resource_clients/key_value_store_collection.py +++ b/src/apify_client/_resource_clients/key_value_store_collection.py @@ -60,7 +60,7 @@ def get_or_create( Returns: The retrieved or newly-created key-value store. """ - result = self._get_or_create(name=name, resource_fields=filter_none_values({'schema': schema})) + result = self._get_or_create(name=name, resource_fields=filter_none_values(data={'schema': schema})) return KeyValueStoreResponse.model_validate(result).data @@ -112,5 +112,5 @@ async def get_or_create( Returns: The retrieved or newly-created key-value store. """ - result = await self._get_or_create(name=name, resource_fields=filter_none_values({'schema': schema})) + result = await self._get_or_create(name=name, resource_fields=filter_none_values(data={'schema': schema})) return KeyValueStoreResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/log.py b/src/apify_client/_resource_clients/log.py index b214c114..2ed80d3a 100644 --- a/src/apify_client/_resource_clients/log.py +++ b/src/apify_client/_resource_clients/log.py @@ -41,7 +41,7 @@ def get(self, *, raw: bool = False) -> str | None: return response.text # noqa: TRY300 except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -66,7 +66,7 @@ def get_as_bytes(self, *, raw: bool = False) -> bytes | None: return response.content # noqa: TRY300 except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -93,7 +93,7 @@ def stream(self, *, raw: bool = False) -> Iterator[impit.Response | None]: yield response except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) yield None finally: if response: @@ -128,7 +128,7 @@ async def get(self, *, raw: bool = False) -> str | None: return response.text # noqa: TRY300 except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -153,7 +153,7 @@ async def get_as_bytes(self, *, raw: bool = False) -> bytes | None: return response.content # noqa: TRY300 except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -180,7 +180,7 @@ async def stream(self, *, raw: bool = False) -> AsyncIterator[impit.Response | N yield response except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) yield None finally: if response: diff --git a/src/apify_client/_resource_clients/request_queue.py b/src/apify_client/_resource_clients/request_queue.py index 907177d7..ba968d08 100644 --- a/src/apify_client/_resource_clients/request_queue.py +++ b/src/apify_client/_resource_clients/request_queue.py @@ -98,9 +98,9 @@ def update(self, *, name: str | None = None, general_access: GeneralAccess | Non 'name': name, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = self._update(cleaned, timeout=FAST_OPERATION_TIMEOUT) + result = self._update(updated_fields=cleaned, timeout=FAST_OPERATION_TIMEOUT) return RequestQueueResponse.model_validate(result).data def delete(self) -> None: @@ -124,13 +124,13 @@ def list_head(self, *, limit: int | None = None) -> RequestQueueHead: request_params = self._build_params(limit=limit, clientKey=self.client_key) response = self._http_client.call( - url=self._build_url('head'), + url=self._build_url(path='head'), method='GET', params=request_params, timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return HeadResponse.model_validate(result).data def list_and_lock_head(self, *, lock_duration: timedelta, limit: int | None = None) -> LockedRequestQueueHead: @@ -146,22 +146,22 @@ def list_and_lock_head(self, *, lock_duration: timedelta, limit: int | None = No The desired number of locked requests from the beginning of the queue. """ request_params = self._build_params( - lockSecs=to_seconds(lock_duration, as_int=True), + lockSecs=to_seconds(td=lock_duration, as_int=True), limit=limit, clientKey=self.client_key, ) response = self._http_client.call( - url=self._build_url('head/lock'), + url=self._build_url(path='head/lock'), method='POST', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return HeadAndLockResponse.model_validate(result).data - def add_request(self, request: dict, *, forefront: bool | None = None) -> RequestRegistration: + def add_request(self, *, request: dict, forefront: bool | None = None) -> RequestRegistration: """Add a request to the queue. https://docs.apify.com/api/v2#/reference/request-queues/request-collection/add-request @@ -176,17 +176,17 @@ def add_request(self, request: dict, *, forefront: bool | None = None) -> Reques request_params = self._build_params(forefront=forefront, clientKey=self.client_key) response = self._http_client.call( - url=self._build_url('requests'), + url=self._build_url(path='requests'), method='POST', json=request, params=request_params, timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return AddRequestResponse.model_validate(result).data - def get_request(self, request_id: str) -> Request | None: + def get_request(self, *, request_id: str) -> Request | None: """Retrieve a request from the queue. https://docs.apify.com/api/v2#/reference/request-queues/request/get-request @@ -199,20 +199,20 @@ def get_request(self, request_id: str) -> Request | None: """ try: response = self._http_client.call( - url=self._build_url(f'requests/{request_id}'), + url=self._build_url(path=f'requests/{request_id}'), method='GET', params=self._build_params(), timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RequestResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None - def update_request(self, request: dict, *, forefront: bool | None = None) -> RequestRegistration: + def update_request(self, *, request: dict, forefront: bool | None = None) -> RequestRegistration: """Update a request in the queue. https://docs.apify.com/api/v2#/reference/request-queues/request/update-request @@ -229,17 +229,17 @@ def update_request(self, request: dict, *, forefront: bool | None = None) -> Req request_params = self._build_params(forefront=forefront, clientKey=self.client_key) response = self._http_client.call( - url=self._build_url(f'requests/{request_id}'), + url=self._build_url(path=f'requests/{request_id}'), method='PUT', json=request, params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return AddRequestResponse.model_validate(result).data - def delete_request(self, request_id: str) -> None: + def delete_request(self, *, request_id: str) -> None: """Delete a request from the queue. https://docs.apify.com/api/v2#/reference/request-queues/request/delete-request @@ -252,7 +252,7 @@ def delete_request(self, request_id: str) -> None: ) self._http_client.call( - url=self._build_url(f'requests/{request_id}'), + url=self._build_url(path=f'requests/{request_id}'), method='DELETE', params=request_params, timeout=FAST_OPERATION_TIMEOUT, @@ -260,8 +260,8 @@ def delete_request(self, request_id: str) -> None: def prolong_request_lock( self, - request_id: str, *, + request_id: str, forefront: bool | None = None, lock_duration: timedelta, ) -> RequestLockInfo | None: @@ -277,20 +277,20 @@ def prolong_request_lock( request_params = self._build_params( clientKey=self.client_key, forefront=forefront, - lockSecs=to_seconds(lock_duration, as_int=True), + lockSecs=to_seconds(td=lock_duration, as_int=True), ) response = self._http_client.call( - url=self._build_url(f'requests/{request_id}/lock'), + url=self._build_url(path=f'requests/{request_id}/lock'), method='PUT', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ProlongRequestLockResponse.model_validate(result).data - def delete_request_lock(self, request_id: str, *, forefront: bool | None = None) -> None: + def delete_request_lock(self, *, request_id: str, forefront: bool | None = None) -> None: """Delete the lock on a request. https://docs.apify.com/api/v2#/reference/request-queues/request-lock/delete-request-lock @@ -302,7 +302,7 @@ def delete_request_lock(self, request_id: str, *, forefront: bool | None = None) request_params = self._build_params(clientKey=self.client_key, forefront=forefront) self._http_client.call( - url=self._build_url(f'requests/{request_id}/lock'), + url=self._build_url(path=f'requests/{request_id}/lock'), method='DELETE', params=request_params, timeout=FAST_OPERATION_TIMEOUT, @@ -310,8 +310,8 @@ def delete_request_lock(self, request_id: str, *, forefront: bool | None = None) def batch_add_requests( self, - requests: list[dict], *, + requests: list[dict], forefront: bool = False, max_parallel: int = 1, max_unprocessed_requests_retries: int | None = None, @@ -370,14 +370,14 @@ def batch_add_requests( # Send the batch to the API. response = self._http_client.call( - url=self._build_url('requests/batch'), + url=self._build_url(path='requests/batch'), method='POST', params=request_params, json=list(request_batch), timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) batch_response = BatchAddResponse.model_validate(result) processed_requests.extend(batch_response.data.processed_requests) unprocessed_requests.extend(batch_response.data.unprocessed_requests) @@ -389,7 +389,7 @@ def batch_add_requests( ) ).data - def batch_delete_requests(self, requests: list[dict]) -> BatchDeleteResult: + def batch_delete_requests(self, *, requests: list[dict]) -> BatchDeleteResult: """Delete given requests from the queue. https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/delete-requests @@ -400,14 +400,14 @@ def batch_delete_requests(self, requests: list[dict]) -> BatchDeleteResult: request_params = self._build_params(clientKey=self.client_key) response = self._http_client.call( - url=self._build_url('requests/batch'), + url=self._build_url(path='requests/batch'), method='DELETE', params=request_params, json=requests, timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return BatchDeleteResponse.model_validate(result).data def list_requests( @@ -427,13 +427,13 @@ def list_requests( request_params = self._build_params(limit=limit, exclusiveStartId=exclusive_start_id, clientKey=self.client_key) response = self._http_client.call( - url=self._build_url('requests'), + url=self._build_url(path='requests'), method='GET', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ListOfRequestsResponse.model_validate(result).data def unlock_requests(self: RequestQueueClient) -> UnlockRequestsResult: @@ -447,12 +447,12 @@ def unlock_requests(self: RequestQueueClient) -> UnlockRequestsResult: request_params = self._build_params(clientKey=self.client_key) response = self._http_client.call( - url=self._build_url('requests/unlock'), + url=self._build_url(path='requests/unlock'), method='POST', params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return UnlockRequestsResponse.model_validate(result).data @@ -508,9 +508,9 @@ async def update( 'name': name, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = await self._update(cleaned, timeout=FAST_OPERATION_TIMEOUT) + result = await self._update(updated_fields=cleaned, timeout=FAST_OPERATION_TIMEOUT) return RequestQueueResponse.model_validate(result).data async def delete(self) -> None: @@ -534,13 +534,13 @@ async def list_head(self, *, limit: int | None = None) -> RequestQueueHead: request_params = self._build_params(limit=limit, clientKey=self.client_key) response = await self._http_client.call( - url=self._build_url('head'), + url=self._build_url(path='head'), method='GET', params=request_params, timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return HeadResponse.model_validate(result).data async def list_and_lock_head(self, *, lock_duration: timedelta, limit: int | None = None) -> LockedRequestQueueHead: @@ -556,22 +556,22 @@ async def list_and_lock_head(self, *, lock_duration: timedelta, limit: int | Non The desired number of locked requests from the beginning of the queue. """ request_params = self._build_params( - lockSecs=to_seconds(lock_duration, as_int=True), + lockSecs=to_seconds(td=lock_duration, as_int=True), limit=limit, clientKey=self.client_key, ) response = await self._http_client.call( - url=self._build_url('head/lock'), + url=self._build_url(path='head/lock'), method='POST', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return HeadAndLockResponse.model_validate(result).data - async def add_request(self, request: dict, *, forefront: bool | None = None) -> RequestRegistration: + async def add_request(self, *, request: dict, forefront: bool | None = None) -> RequestRegistration: """Add a request to the queue. https://docs.apify.com/api/v2#/reference/request-queues/request-collection/add-request @@ -586,17 +586,17 @@ async def add_request(self, request: dict, *, forefront: bool | None = None) -> request_params = self._build_params(forefront=forefront, clientKey=self.client_key) response = await self._http_client.call( - url=self._build_url('requests'), + url=self._build_url(path='requests'), method='POST', json=request, params=request_params, timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return AddRequestResponse.model_validate(result).data - async def get_request(self, request_id: str) -> Request | None: + async def get_request(self, *, request_id: str) -> Request | None: """Retrieve a request from the queue. https://docs.apify.com/api/v2#/reference/request-queues/request/get-request @@ -609,18 +609,18 @@ async def get_request(self, request_id: str) -> Request | None: """ try: response = await self._http_client.call( - url=self._build_url(f'requests/{request_id}'), + url=self._build_url(path=f'requests/{request_id}'), method='GET', params=self._build_params(), timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RequestResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None - async def update_request(self, request: dict, *, forefront: bool | None = None) -> RequestRegistration: + async def update_request(self, *, request: dict, forefront: bool | None = None) -> RequestRegistration: """Update a request in the queue. https://docs.apify.com/api/v2#/reference/request-queues/request/update-request @@ -637,17 +637,17 @@ async def update_request(self, request: dict, *, forefront: bool | None = None) request_params = self._build_params(forefront=forefront, clientKey=self.client_key) response = await self._http_client.call( - url=self._build_url(f'requests/{request_id}'), + url=self._build_url(path=f'requests/{request_id}'), method='PUT', json=request, params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return AddRequestResponse.model_validate(result).data - async def delete_request(self, request_id: str) -> None: + async def delete_request(self, *, request_id: str) -> None: """Delete a request from the queue. https://docs.apify.com/api/v2#/reference/request-queues/request/delete-request @@ -658,7 +658,7 @@ async def delete_request(self, request_id: str) -> None: request_params = self._build_params(clientKey=self.client_key) await self._http_client.call( - url=self._build_url(f'requests/{request_id}'), + url=self._build_url(path=f'requests/{request_id}'), method='DELETE', params=request_params, timeout=FAST_OPERATION_TIMEOUT, @@ -666,8 +666,8 @@ async def delete_request(self, request_id: str) -> None: async def prolong_request_lock( self, - request_id: str, *, + request_id: str, forefront: bool | None = None, lock_duration: timedelta, ) -> RequestLockInfo | None: @@ -683,23 +683,23 @@ async def prolong_request_lock( request_params = self._build_params( clientKey=self.client_key, forefront=forefront, - lockSecs=to_seconds(lock_duration, as_int=True), + lockSecs=to_seconds(td=lock_duration, as_int=True), ) response = await self._http_client.call( - url=self._build_url(f'requests/{request_id}/lock'), + url=self._build_url(path=f'requests/{request_id}/lock'), method='PUT', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ProlongRequestLockResponse.model_validate(result).data async def delete_request_lock( self, - request_id: str, *, + request_id: str, forefront: bool | None = None, ) -> None: """Delete the lock on a request. @@ -713,7 +713,7 @@ async def delete_request_lock( request_params = self._build_params(clientKey=self.client_key, forefront=forefront) await self._http_client.call( - url=self._build_url(f'requests/{request_id}/lock'), + url=self._build_url(path=f'requests/{request_id}/lock'), method='DELETE', params=request_params, timeout=FAST_OPERATION_TIMEOUT, @@ -721,6 +721,7 @@ async def delete_request_lock( async def _batch_add_requests_worker( self, + *, queue: asyncio.Queue[Iterable[dict]], request_params: dict, ) -> BatchAddResponse: @@ -743,14 +744,14 @@ async def _batch_add_requests_worker( try: # Send the batch to the API. response = await self._http_client.call( - url=self._build_url('requests/batch'), + url=self._build_url(path='requests/batch'), method='POST', params=request_params, json=list(request_batch), timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) batch_response = BatchAddResponse.model_validate(result) processed_requests.extend(batch_response.data.processed_requests) unprocessed_requests.extend(batch_response.data.unprocessed_requests) @@ -768,8 +769,8 @@ async def _batch_add_requests_worker( async def batch_add_requests( self, - requests: list[dict], *, + requests: list[dict], forefront: bool = False, max_parallel: int = 5, max_unprocessed_requests_retries: int | None = None, @@ -818,8 +819,8 @@ async def batch_add_requests( # Start a required number of worker tasks to process the batches. for i in range(max_parallel): coro = self._batch_add_requests_worker( - asyncio_queue, - request_params, + queue=asyncio_queue, + request_params=request_params, ) task = asyncio.create_task(coro, name=f'batch_add_requests_worker_{i}') tasks.add(task) @@ -848,7 +849,7 @@ async def batch_add_requests( ) ).data - async def batch_delete_requests(self, requests: list[dict]) -> BatchDeleteResult: + async def batch_delete_requests(self, *, requests: list[dict]) -> BatchDeleteResult: """Delete given requests from the queue. https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/delete-requests @@ -859,13 +860,13 @@ async def batch_delete_requests(self, requests: list[dict]) -> BatchDeleteResult request_params = self._build_params(clientKey=self.client_key) response = await self._http_client.call( - url=self._build_url('requests/batch'), + url=self._build_url(path='requests/batch'), method='DELETE', params=request_params, json=requests, timeout=FAST_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return BatchDeleteResponse.model_validate(result).data async def list_requests( @@ -885,13 +886,13 @@ async def list_requests( request_params = self._build_params(limit=limit, exclusiveStartId=exclusive_start_id, clientKey=self.client_key) response = await self._http_client.call( - url=self._build_url('requests'), + url=self._build_url(path='requests'), method='GET', params=request_params, timeout=STANDARD_OPERATION_TIMEOUT, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ListOfRequestsResponse.model_validate(result).data async def unlock_requests(self: RequestQueueClientAsync) -> UnlockRequestsResult: @@ -905,10 +906,10 @@ async def unlock_requests(self: RequestQueueClientAsync) -> UnlockRequestsResult request_params = self._build_params(clientKey=self.client_key) response = await self._http_client.call( - url=self._build_url('requests/unlock'), + url=self._build_url(path='requests/unlock'), method='POST', params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return UnlockRequestsResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/run.py b/src/apify_client/_resource_clients/run.py index c545ebd6..c3d18f29 100644 --- a/src/apify_client/_resource_clients/run.py +++ b/src/apify_client/_resource_clients/run.py @@ -92,9 +92,9 @@ def update( 'isStatusMessageTerminal': is_status_message_terminal, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = self._update(cleaned) + result = self._update(updated_fields=cleaned) return RunResponse.model_validate(result).data def delete(self) -> None: @@ -118,11 +118,11 @@ def abort(self, *, gracefully: bool | None = None) -> Run: The data of the aborted Actor run. """ response = self._http_client.call( - url=self._build_url('abort'), + url=self._build_url(path='abort'), method='POST', params=self._build_params(gracefully=gracefully), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data def wait_for_finish(self, *, wait_duration: timedelta | None = None) -> Run | None: @@ -169,21 +169,21 @@ def metamorph( Returns: The Actor run data. """ - run_input, content_type = encode_key_value_store_record_value(run_input, content_type) + run_input, content_type = encode_key_value_store_record_value(value=run_input, content_type=content_type) - safe_target_actor_id = to_safe_id(target_actor_id) + safe_target_actor_id = to_safe_id(id=target_actor_id) request_params = self._build_params(targetActorId=safe_target_actor_id, build=target_actor_build) response = self._http_client.call( - url=self._build_url('metamorph'), + url=self._build_url(path='metamorph'), method='POST', headers={'content-type': content_type}, data=run_input, params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data def resurrect( @@ -223,19 +223,19 @@ def resurrect( request_params = self._build_params( build=build, memory=memory_mbytes, - timeout=to_seconds(timeout, as_int=True), + timeout=to_seconds(td=timeout, as_int=True), maxItems=max_items, maxTotalChargeUsd=max_total_charge_usd, restartOnError=restart_on_error, ) response = self._http_client.call( - url=self._build_url('resurrect'), + url=self._build_url(path='resurrect'), method='POST', params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data def reboot(self) -> Run: @@ -247,10 +247,10 @@ def reboot(self) -> Run: The Actor run data. """ response = self._http_client.call( - url=self._build_url('reboot'), + url=self._build_url(path='reboot'), method='POST', ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data def dataset(self) -> DatasetClient: @@ -305,7 +305,7 @@ def log(self) -> LogClient: **self._base_client_kwargs, ) - def get_streamed_log(self, to_logger: logging.Logger | None = None, *, from_start: bool = True) -> StreamedLogSync: + def get_streamed_log(self, *, to_logger: logging.Logger | None = None, from_start: bool = True) -> StreamedLogSync: """Get `StreamedLog` instance that can be used to redirect logs. `StreamedLog` can be explicitly started and stopped or used as a context manager. @@ -337,12 +337,13 @@ def get_streamed_log(self, to_logger: logging.Logger | None = None, *, from_star if not to_logger: name = ' '.join(part for part in (actor_name, run_id) if part) - to_logger = create_redirect_logger(f'apify.{name}') + to_logger = create_redirect_logger(name=f'apify.{name}') return self._client_registry.streamed_log(log_client=self.log(), to_logger=to_logger, from_start=from_start) def charge( self, + *, event_name: str, count: int | None = None, idempotency_key: str | None = None, @@ -369,7 +370,7 @@ def charge( idempotency_key = f'{self._resource_id}-{event_name}-{timestamp_ms}-{random_suffix}' self._http_client.call( - url=self._build_url('charge'), + url=self._build_url(path='charge'), method='POST', headers={ 'idempotency-key': idempotency_key, @@ -384,7 +385,7 @@ def charge( ) def get_status_message_watcher( - self, to_logger: logging.Logger | None = None, check_period: timedelta = timedelta(seconds=1) + self, *, to_logger: logging.Logger | None = None, check_period: timedelta = timedelta(seconds=1) ) -> StatusMessageWatcherSync: """Get `StatusMessageWatcher` instance that can be used to redirect status and status messages to logs. @@ -416,7 +417,7 @@ def get_status_message_watcher( if not to_logger: name = ' '.join(part for part in (actor_name, run_id) if part) - to_logger = create_redirect_logger(f'apify.{name}') + to_logger = create_redirect_logger(name=f'apify.{name}') return self._client_registry.status_message_watcher( run_client=self, to_logger=to_logger, check_period=check_period @@ -476,9 +477,9 @@ async def update( 'isStatusMessageTerminal': is_status_message_terminal, 'generalAccess': general_access, } - cleaned = filter_none_values(updated_fields) + cleaned = filter_none_values(data=updated_fields) - result = await self._update(cleaned) + result = await self._update(updated_fields=cleaned) return RunResponse.model_validate(result).data async def abort(self, *, gracefully: bool | None = None) -> Run: @@ -495,11 +496,11 @@ async def abort(self, *, gracefully: bool | None = None) -> Run: The data of the aborted Actor run. """ response = await self._http_client.call( - url=self._build_url('abort'), + url=self._build_url(path='abort'), method='POST', params=self._build_params(gracefully=gracefully), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data async def wait_for_finish(self, *, wait_duration: timedelta | None = None) -> Run | None: @@ -549,9 +550,9 @@ async def metamorph( Returns: The Actor run data. """ - run_input, content_type = encode_key_value_store_record_value(run_input, content_type) + run_input, content_type = encode_key_value_store_record_value(value=run_input, content_type=content_type) - safe_target_actor_id = to_safe_id(target_actor_id) + safe_target_actor_id = to_safe_id(id=target_actor_id) request_params = self._build_params( targetActorId=safe_target_actor_id, @@ -559,14 +560,14 @@ async def metamorph( ) response = await self._http_client.call( - url=self._build_url('metamorph'), + url=self._build_url(path='metamorph'), method='POST', headers={'content-type': content_type}, data=run_input, params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data async def resurrect( @@ -606,19 +607,19 @@ async def resurrect( request_params = self._build_params( build=build, memory=memory_mbytes, - timeout=to_seconds(timeout, as_int=True), + timeout=to_seconds(td=timeout, as_int=True), maxItems=max_items, maxTotalChargeUsd=max_total_charge_usd, restartOnError=restart_on_error, ) response = await self._http_client.call( - url=self._build_url('resurrect'), + url=self._build_url(path='resurrect'), method='POST', params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data async def reboot(self) -> Run: @@ -630,10 +631,10 @@ async def reboot(self) -> Run: The Actor run data. """ response = await self._http_client.call( - url=self._build_url('reboot'), + url=self._build_url(path='reboot'), method='POST', ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data def dataset(self) -> DatasetClientAsync: @@ -689,7 +690,7 @@ def log(self) -> LogClientAsync: ) async def get_streamed_log( - self, to_logger: logging.Logger | None = None, *, from_start: bool = True + self, *, to_logger: logging.Logger | None = None, from_start: bool = True ) -> StreamedLogAsync: """Get `StreamedLog` instance that can be used to redirect logs. @@ -722,12 +723,13 @@ async def get_streamed_log( if not to_logger: name = ' '.join(part for part in (actor_name, run_id) if part) - to_logger = create_redirect_logger(f'apify.{name}') + to_logger = create_redirect_logger(name=f'apify.{name}') return self._client_registry.streamed_log(log_client=self.log(), to_logger=to_logger, from_start=from_start) async def charge( self, + *, event_name: str, count: int | None = None, idempotency_key: str | None = None, @@ -754,7 +756,7 @@ async def charge( idempotency_key = f'{self._resource_id}-{event_name}-{timestamp_ms}-{random_suffix}' await self._http_client.call( - url=self._build_url('charge'), + url=self._build_url(path='charge'), method='POST', headers={ 'idempotency-key': idempotency_key, @@ -770,6 +772,7 @@ async def charge( async def get_status_message_watcher( self, + *, to_logger: logging.Logger | None = None, check_period: timedelta = timedelta(seconds=1), ) -> StatusMessageWatcherAsync: @@ -804,7 +807,7 @@ async def get_status_message_watcher( if not to_logger: name = ' '.join(part for part in (actor_name, run_id) if part) - to_logger = create_redirect_logger(f'apify.{name}') + to_logger = create_redirect_logger(name=f'apify.{name}') return self._client_registry.status_message_watcher( run_client=self, to_logger=to_logger, check_period=check_period diff --git a/src/apify_client/_resource_clients/run_collection.py b/src/apify_client/_resource_clients/run_collection.py index cdded09d..b764bcbf 100644 --- a/src/apify_client/_resource_clients/run_collection.py +++ b/src/apify_client/_resource_clients/run_collection.py @@ -48,7 +48,9 @@ def list( Returns: The retrieved Actor runs. """ - status_param = [enum_to_value(s) for s in status] if isinstance(status, list) else enum_to_value(status) + status_param = ( + [enum_to_value(value=s) for s in status] if isinstance(status, list) else enum_to_value(value=status) + ) result = self._list( limit=limit, @@ -97,7 +99,9 @@ async def list( Returns: The retrieved Actor runs. """ - status_param = [enum_to_value(s) for s in status] if isinstance(status, list) else enum_to_value(status) + status_param = ( + [enum_to_value(value=s) for s in status] if isinstance(status, list) else enum_to_value(value=status) + ) result = await self._list( limit=limit, diff --git a/src/apify_client/_resource_clients/schedule.py b/src/apify_client/_resource_clients/schedule.py index b87e3a17..f815d3a7 100644 --- a/src/apify_client/_resource_clients/schedule.py +++ b/src/apify_client/_resource_clients/schedule.py @@ -70,9 +70,9 @@ def update( timezone=timezone, title=title, ) - cleaned = filter_none_values(schedule_representation) + cleaned = filter_none_values(data=schedule_representation) - result = self._update(cleaned) + result = self._update(updated_fields=cleaned) return ScheduleResponse.model_validate(result).data def delete(self) -> None: @@ -92,14 +92,14 @@ def get_log(self) -> list[ScheduleInvoked] | None: """ try: response = self._http_client.call( - url=self._build_url('log'), + url=self._build_url(path='log'), method='GET', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ScheduleLogResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -165,9 +165,9 @@ async def update( timezone=timezone, title=title, ) - cleaned = filter_none_values(schedule_representation) + cleaned = filter_none_values(data=schedule_representation) - result = await self._update(cleaned) + result = await self._update(updated_fields=cleaned) return ScheduleResponse.model_validate(result).data async def delete(self) -> None: @@ -187,13 +187,13 @@ async def get_log(self) -> list[ScheduleInvoked] | None: """ try: response = await self._http_client.call( - url=self._build_url('log'), + url=self._build_url(path='log'), method='GET', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return ScheduleLogResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None diff --git a/src/apify_client/_resource_clients/schedule_collection.py b/src/apify_client/_resource_clients/schedule_collection.py index ff69a2d5..9d77606c 100644 --- a/src/apify_client/_resource_clients/schedule_collection.py +++ b/src/apify_client/_resource_clients/schedule_collection.py @@ -82,7 +82,7 @@ def create( title=title, ) - result = self._create(filter_none_values(schedule_representation)) + result = self._create(created_fields=filter_none_values(data=schedule_representation)) return ScheduleResponse.model_validate(result).data @@ -160,5 +160,5 @@ async def create( title=title, ) - result = await self._create(filter_none_values(schedule_representation)) + result = await self._create(created_fields=filter_none_values(data=schedule_representation)) return ScheduleResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/status_message_watcher.py b/src/apify_client/_resource_clients/status_message_watcher.py index 33f760b8..96f10ce6 100644 --- a/src/apify_client/_resource_clients/status_message_watcher.py +++ b/src/apify_client/_resource_clients/status_message_watcher.py @@ -41,10 +41,10 @@ def __init__(self, *, to_logger: logging.Logger, check_period: timedelta = timed if self._force_propagate: to_logger.propagate = True self._to_logger = to_logger - self._check_period = to_seconds(check_period) + self._check_period = to_seconds(td=check_period) self._last_status_message = '' - def _log_run_data(self, run_data: Run | None) -> bool: + def _log_run_data(self, *, run_data: Run | None) -> bool: """Get relevant run data, log them if changed and return `True` if more data is expected. Args: @@ -118,7 +118,7 @@ async def __aexit__( async def _log_changed_status_message(self) -> None: while True: run_data = await self._run_client.get() - if not self._log_run_data(run_data): + if not self._log_run_data(run_data=run_data): break await asyncio.sleep(self._check_period) @@ -173,7 +173,7 @@ def __exit__( def _log_changed_status_message(self) -> None: while True: - if not self._log_run_data(self._run_client.get()): + if not self._log_run_data(run_data=self._run_client.get()): break if self._stop_logging: break diff --git a/src/apify_client/_resource_clients/streamed_log.py b/src/apify_client/_resource_clients/streamed_log.py index edc83304..f1f423b6 100644 --- a/src/apify_client/_resource_clients/streamed_log.py +++ b/src/apify_client/_resource_clients/streamed_log.py @@ -29,7 +29,7 @@ class StreamedLog: # Test related flag to enable propagation of logs to the `caplog` fixture during tests. _force_propagate = False - def __init__(self, to_logger: logging.Logger, *, from_start: bool = True) -> None: + def __init__(self, *, to_logger: logging.Logger, from_start: bool = True) -> None: """Initialize `StreamedLog`. Args: @@ -46,7 +46,7 @@ def __init__(self, to_logger: logging.Logger, *, from_start: bool = True) -> Non self._split_marker = re.compile(rb'(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)') self._relevancy_time_limit: datetime | None = None if from_start else datetime.now(tz=UTC) - def _process_new_data(self, data: bytes) -> None: + def _process_new_data(self, *, data: bytes) -> None: new_chunk = data self._stream_buffer.append(new_chunk) if re.findall(self._split_marker, new_chunk): @@ -79,10 +79,10 @@ def _log_buffer_content(self, *, include_last_part: bool = False) -> None: # Skip irrelevant logs continue message = decoded_marker + decoded_content - self._to_logger.log(level=self._guess_log_level_from_message(message), msg=message.strip()) + self._to_logger.log(level=self._guess_log_level_from_message(message=message), msg=message.strip()) @staticmethod - def _guess_log_level_from_message(message: str) -> int: + def _guess_log_level_from_message(*, message: str) -> int: """Guess the log level from the message.""" # Using only levels explicitly mentioned in the logging module known_levels = ('CRITICAL', 'FATAL', 'ERROR', 'WARN', 'WARNING', 'INFO', 'DEBUG', 'NOTSET') @@ -97,7 +97,7 @@ def _guess_log_level_from_message(message: str) -> int: class StreamedLogSync(StreamedLog): """Sync variant of `StreamedLog` that is logging in threads.""" - def __init__(self, log_client: LogClient, *, to_logger: logging.Logger, from_start: bool = True) -> None: + def __init__(self, *, log_client: LogClient, to_logger: logging.Logger, from_start: bool = True) -> None: super().__init__(to_logger=to_logger, from_start=from_start) self._log_client = log_client self._streaming_thread: Thread | None = None @@ -137,7 +137,7 @@ def _stream_log(self) -> None: if not log_stream: return for data in log_stream.iter_bytes(): - self._process_new_data(data) + self._process_new_data(data=data) if self._stop_logging: break @@ -149,7 +149,7 @@ def _stream_log(self) -> None: class StreamedLogAsync(StreamedLog): """Async variant of `StreamedLog` that is logging in tasks.""" - def __init__(self, log_client: LogClientAsync, *, to_logger: logging.Logger, from_start: bool = True) -> None: + def __init__(self, *, log_client: LogClientAsync, to_logger: logging.Logger, from_start: bool = True) -> None: super().__init__(to_logger=to_logger, from_start=from_start) self._log_client = log_client self._streaming_task: Task | None = None @@ -190,7 +190,7 @@ async def _stream_log(self) -> None: if not log_stream: return async for data in log_stream.aiter_bytes(): - self._process_new_data(data) + self._process_new_data(data=data) # If the stream is finished, then the last part will be also processed. self._log_buffer_content(include_last_part=True) diff --git a/src/apify_client/_resource_clients/task.py b/src/apify_client/_resource_clients/task.py index a380510c..9150288a 100644 --- a/src/apify_client/_resource_clients/task.py +++ b/src/apify_client/_resource_clients/task.py @@ -116,9 +116,9 @@ def update( actor_standby_build=actor_standby_build, actor_standby_memory_mbytes=actor_standby_memory_mbytes, ) - cleaned = filter_none_values(task_representation, remove_empty_dicts=True) + cleaned = filter_none_values(data=task_representation, remove_empty_dicts=True) - result = self._update(cleaned) + result = self._update(updated_fields=cleaned) return TaskResponse.model_validate(result).data def delete(self) -> None: @@ -173,21 +173,21 @@ def start( build=build, maxItems=max_items, memory=memory_mbytes, - timeout=to_seconds(timeout, as_int=True), + timeout=to_seconds(td=timeout, as_int=True), restartOnError=restart_on_error, waitForFinish=wait_for_finish, - webhooks=encode_webhook_list_to_base64(webhooks) if webhooks is not None else None, + webhooks=encode_webhook_list_to_base64(webhooks=webhooks) if webhooks is not None else None, ) response = self._http_client.call( - url=self._build_url('runs'), + url=self._build_url(path='runs'), method='POST', headers={'content-type': 'application/json; charset=utf-8'}, json=task_input, params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data def call( @@ -258,13 +258,13 @@ def get_input(self) -> dict | None: """ try: response = self._http_client.call( - url=self._build_url('input'), + url=self._build_url(path='input'), method='GET', params=self._build_params(), ) - return response_to_dict(response) + return response_to_dict(response=response) except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None def update_input(self, *, task_input: dict) -> dict: @@ -279,12 +279,12 @@ def update_input(self, *, task_input: dict) -> dict: The updated task input. """ response = self._http_client.call( - url=self._build_url('input'), + url=self._build_url(path='input'), method='PUT', params=self._build_params(), json=task_input, ) - return response_to_dict(response) + return response_to_dict(response=response) def runs(self) -> RunCollectionClient: """Retrieve a client for the runs of this task.""" @@ -308,7 +308,7 @@ def last_run(self, *, status: ActorJobStatus | None = None, origin: RunOrigin | return self._client_registry.run_client( resource_id='last', resource_path='runs', - params=self._build_params(status=enum_to_value(status), origin=enum_to_value(origin)), + params=self._build_params(status=enum_to_value(value=status), origin=enum_to_value(value=origin)), **self._base_client_kwargs, ) @@ -404,9 +404,9 @@ async def update( actor_standby_build=actor_standby_build, actor_standby_memory_mbytes=actor_standby_memory_mbytes, ) - cleaned = filter_none_values(task_representation, remove_empty_dicts=True) + cleaned = filter_none_values(data=task_representation, remove_empty_dicts=True) - result = await self._update(cleaned) + result = await self._update(updated_fields=cleaned) return TaskResponse.model_validate(result).data async def delete(self) -> None: @@ -461,21 +461,21 @@ async def start( build=build, maxItems=max_items, memory=memory_mbytes, - timeout=to_seconds(timeout, as_int=True), + timeout=to_seconds(td=timeout, as_int=True), restartOnError=restart_on_error, waitForFinish=wait_for_finish, - webhooks=encode_webhook_list_to_base64(webhooks) if webhooks is not None else None, + webhooks=encode_webhook_list_to_base64(webhooks=webhooks) if webhooks is not None else None, ) response = await self._http_client.call( - url=self._build_url('runs'), + url=self._build_url(path='runs'), method='POST', headers={'content-type': 'application/json; charset=utf-8'}, json=task_input, params=request_params, ) - result = response_to_dict(response) + result = response_to_dict(response=response) return RunResponse.model_validate(result).data async def call( @@ -545,13 +545,13 @@ async def get_input(self) -> dict | None: """ try: response = await self._http_client.call( - url=self._build_url('input'), + url=self._build_url(path='input'), method='GET', params=self._build_params(), ) - return response_to_dict(response) + return response_to_dict(response=response) except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None async def update_input(self, *, task_input: dict) -> dict: @@ -566,12 +566,12 @@ async def update_input(self, *, task_input: dict) -> dict: The updated task input. """ response = await self._http_client.call( - url=self._build_url('input'), + url=self._build_url(path='input'), method='PUT', params=self._build_params(), json=task_input, ) - return response_to_dict(response) + return response_to_dict(response=response) def runs(self) -> RunCollectionClientAsync: """Retrieve a client for the runs of this task.""" @@ -595,7 +595,7 @@ def last_run(self, *, status: ActorJobStatus | None = None, origin: RunOrigin | return self._client_registry.run_client( resource_id='last', resource_path='runs', - params=self._build_params(status=enum_to_value(status), origin=enum_to_value(origin)), + params=self._build_params(status=enum_to_value(value=status), origin=enum_to_value(value=origin)), **self._base_client_kwargs, ) diff --git a/src/apify_client/_resource_clients/task_collection.py b/src/apify_client/_resource_clients/task_collection.py index e55b0d46..2fdfa5cf 100644 --- a/src/apify_client/_resource_clients/task_collection.py +++ b/src/apify_client/_resource_clients/task_collection.py @@ -106,7 +106,7 @@ def create( actor_standby_memory_mbytes=actor_standby_memory_mbytes, ) - result = self._create(filter_none_values(task_representation, remove_empty_dicts=True)) + result = self._create(created_fields=filter_none_values(data=task_representation, remove_empty_dicts=True)) return TaskResponse.model_validate(result).data @@ -205,5 +205,7 @@ async def create( actor_standby_memory_mbytes=actor_standby_memory_mbytes, ) - result = await self._create(filter_none_values(task_representation, remove_empty_dicts=True)) + result = await self._create( + created_fields=filter_none_values(data=task_representation, remove_empty_dicts=True) + ) return TaskResponse.model_validate(result).data diff --git a/src/apify_client/_resource_clients/user.py b/src/apify_client/_resource_clients/user.py index af6e6357..6e4fa7f3 100644 --- a/src/apify_client/_resource_clients/user.py +++ b/src/apify_client/_resource_clients/user.py @@ -61,15 +61,15 @@ def monthly_usage(self) -> MonthlyUsage | None: """ try: response = self._http_client.call( - url=self._build_url('usage/monthly'), + url=self._build_url(path='usage/monthly'), method='GET', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return MonthlyUsageResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -86,15 +86,15 @@ def limits(self) -> AccountLimits | None: """ try: response = self._http_client.call( - url=self._build_url('limits'), + url=self._build_url(path='limits'), method='GET', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return LimitsResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -106,11 +106,11 @@ def update_limits( ) -> None: """Update the account's limits manageable on your account's Limits page.""" self._http_client.call( - url=self._build_url('limits'), + url=self._build_url(path='limits'), method='PUT', params=self._build_params(), json=filter_none_values( - { + data={ 'maxMonthlyUsageUsd': max_monthly_usage_usd, 'dataRetentionDays': data_retention_days, } @@ -160,15 +160,15 @@ async def monthly_usage(self) -> MonthlyUsage | None: """ try: response = await self._http_client.call( - url=self._build_url('usage/monthly'), + url=self._build_url(path='usage/monthly'), method='GET', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return MonthlyUsageResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -185,15 +185,15 @@ async def limits(self) -> AccountLimits | None: """ try: response = await self._http_client.call( - url=self._build_url('limits'), + url=self._build_url(path='limits'), method='GET', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return LimitsResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -205,11 +205,11 @@ async def update_limits( ) -> None: """Update the account's limits manageable on your account's Limits page.""" await self._http_client.call( - url=self._build_url('limits'), + url=self._build_url(path='limits'), method='PUT', params=self._build_params(), json=filter_none_values( - { + data={ 'maxMonthlyUsageUsd': max_monthly_usage_usd, 'dataRetentionDays': data_retention_days, } diff --git a/src/apify_client/_resource_clients/webhook.py b/src/apify_client/_resource_clients/webhook.py index ecf906de..59f958c9 100644 --- a/src/apify_client/_resource_clients/webhook.py +++ b/src/apify_client/_resource_clients/webhook.py @@ -84,9 +84,9 @@ def update( do_not_retry=do_not_retry, is_ad_hoc=is_ad_hoc, ) - cleaned = filter_none_values(webhook_representation, remove_empty_dicts=True) + cleaned = filter_none_values(data=webhook_representation, remove_empty_dicts=True) - result = self._update(cleaned) + result = self._update(updated_fields=cleaned) return WebhookResponse.model_validate(result).data def delete(self) -> None: @@ -108,16 +108,16 @@ def test(self) -> WebhookDispatch | None: """ try: response = self._http_client.call( - url=self._build_url('test'), + url=self._build_url(path='test'), method='POST', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return TestWebhookResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None @@ -201,9 +201,9 @@ async def update( do_not_retry=do_not_retry, is_ad_hoc=is_ad_hoc, ) - cleaned = filter_none_values(webhook_representation, remove_empty_dicts=True) + cleaned = filter_none_values(data=webhook_representation, remove_empty_dicts=True) - result = await self._update(cleaned) + result = await self._update(updated_fields=cleaned) return WebhookResponse.model_validate(result).data async def delete(self) -> None: @@ -225,16 +225,16 @@ async def test(self) -> WebhookDispatch | None: """ try: response = await self._http_client.call( - url=self._build_url('test'), + url=self._build_url(path='test'), method='POST', params=self._build_params(), ) - result = response_to_dict(response) + result = response_to_dict(response=response) return TestWebhookResponse.model_validate(result).data except ApifyApiError as exc: - catch_not_found_or_throw(exc) + catch_not_found_or_throw(exc=exc) return None diff --git a/src/apify_client/_resource_clients/webhook_collection.py b/src/apify_client/_resource_clients/webhook_collection.py index 82c90781..f07dde31 100644 --- a/src/apify_client/_resource_clients/webhook_collection.py +++ b/src/apify_client/_resource_clients/webhook_collection.py @@ -93,7 +93,7 @@ def create( is_ad_hoc=is_ad_hoc, ) - result = self._create(filter_none_values(webhook_representation, remove_empty_dicts=True)) + result = self._create(created_fields=filter_none_values(data=webhook_representation, remove_empty_dicts=True)) return WebhookResponse.model_validate(result).data @@ -179,5 +179,7 @@ async def create( is_ad_hoc=is_ad_hoc, ) - result = await self._create(filter_none_values(webhook_representation, remove_empty_dicts=True)) + result = await self._create( + created_fields=filter_none_values(data=webhook_representation, remove_empty_dicts=True) + ) return WebhookResponse.model_validate(result).data diff --git a/src/apify_client/_statistics.py b/src/apify_client/_statistics.py index b1639bb3..2b649afe 100644 --- a/src/apify_client/_statistics.py +++ b/src/apify_client/_statistics.py @@ -17,7 +17,7 @@ class ClientStatistics: rate_limit_errors: defaultdict[int, int] = field(default_factory=lambda: defaultdict(int)) """List tracking which retry attempts encountered rate limit (429) errors.""" - def add_rate_limit_error(self, attempt: int) -> None: + def add_rate_limit_error(self, *, attempt: int) -> None: """Add rate limit error for specific attempt. Args: diff --git a/src/apify_client/_utils.py b/src/apify_client/_utils.py index 00eb297e..4c48c315 100644 --- a/src/apify_client/_utils.py +++ b/src/apify_client/_utils.py @@ -29,16 +29,16 @@ @overload -def to_seconds(td: None, *, as_int: bool = ...) -> None: ... +def to_seconds(*, td: None, as_int: bool = ...) -> None: ... @overload -def to_seconds(td: timedelta) -> float: ... +def to_seconds(*, td: timedelta) -> float: ... @overload -def to_seconds(td: timedelta, *, as_int: Literal[True]) -> int: ... +def to_seconds(*, td: timedelta, as_int: Literal[True]) -> int: ... @overload -def to_seconds(td: timedelta, *, as_int: Literal[False]) -> float: ... +def to_seconds(*, td: timedelta, as_int: Literal[False]) -> float: ... -def to_seconds(td: timedelta | None, *, as_int: bool = False) -> float | int | None: +def to_seconds(*, td: timedelta | None, as_int: bool = False) -> float | int | None: """Convert timedelta to seconds. Args: @@ -54,7 +54,7 @@ def to_seconds(td: timedelta | None, *, as_int: bool = False) -> float | int | N return int(seconds) if as_int else seconds -def catch_not_found_or_throw(exc: ApifyApiError) -> None: +def catch_not_found_or_throw(*, exc: ApifyApiError) -> None: """Suppress 404 Not Found errors and re-raise all other API errors. Args: @@ -70,8 +70,8 @@ def catch_not_found_or_throw(exc: ApifyApiError) -> None: def filter_none_values( - data: dict, *, + data: dict, remove_empty_dicts: bool | None = None, ) -> dict: """Recursively remove None values from a dictionary. @@ -110,12 +110,12 @@ def filter_none_values( # Optionally remove empty dictionaries if remove_empty_dicts: - _remove_empty_dicts_inplace(result) + _remove_empty_dicts_inplace(data=result) return result -def _remove_empty_dicts_inplace(data: dict[str, Any]) -> None: +def _remove_empty_dicts_inplace(*, data: dict[str, Any]) -> None: """Recursively remove empty dictionaries from a dict in place. This is a helper function for filter_none_values. @@ -124,7 +124,7 @@ def _remove_empty_dicts_inplace(data: dict[str, Any]) -> None: for key, val in data.items(): if isinstance(val, dict): - _remove_empty_dicts_inplace(val) + _remove_empty_dicts_inplace(data=val) if not val: keys_to_remove.append(key) @@ -132,7 +132,7 @@ def _remove_empty_dicts_inplace(data: dict[str, Any]) -> None: del data[key] -def encode_webhook_list_to_base64(webhooks: list[dict]) -> str: +def encode_webhook_list_to_base64(*, webhooks: list[dict]) -> str: """Encode a list of webhook dictionaries to base64 for API transmission. Args: @@ -145,7 +145,7 @@ def encode_webhook_list_to_base64(webhooks: list[dict]) -> str: for webhook in webhooks: webhook_representation = { - 'eventTypes': [enum_to_value(event_type) for event_type in webhook['event_types']], + 'eventTypes': [enum_to_value(value=event_type) for event_type in webhook['event_types']], 'requestUrl': webhook['request_url'], } if 'payload_template' in webhook: @@ -157,7 +157,7 @@ def encode_webhook_list_to_base64(webhooks: list[dict]) -> str: return b64encode(json.dumps(data).encode('utf-8')).decode('ascii') -def encode_key_value_store_record_value(value: Any, content_type: str | None = None) -> tuple[Any, str]: +def encode_key_value_store_record_value(*, value: Any, content_type: str | None = None) -> tuple[Any, str]: """Encode a value for storage in a key-value store record. Args: @@ -191,7 +191,7 @@ def encode_key_value_store_record_value(value: Any, content_type: str | None = N return (value, content_type) -def enum_to_value(value: Any) -> Any: +def enum_to_value(*, value: Any) -> Any: """Convert an Enum member to its value, or return the value unchanged if not an Enum. Ensures Enum instances are converted to primitive values suitable for API transmission. @@ -207,7 +207,7 @@ def enum_to_value(value: Any) -> Any: return value -def is_retryable_error(exc: Exception) -> bool: +def is_retryable_error(*, exc: Exception) -> bool: """Check if the given error is retryable. All ``impit.HTTPError`` subclasses are considered retryable because they represent transport-level failures @@ -223,7 +223,7 @@ def is_retryable_error(exc: Exception) -> bool: ) -def to_safe_id(id: str) -> str: +def to_safe_id(*, id: str) -> str: """Convert a resource ID to URL-safe format by replacing forward slashes with tildes. Args: @@ -235,7 +235,7 @@ def to_safe_id(id: str) -> str: return id.replace('/', '~') -def response_to_dict(response: Response) -> dict: +def response_to_dict(*, response: Response) -> dict: """Parse the API response as a dictionary and validate its type. Args: @@ -255,7 +255,7 @@ def response_to_dict(response: Response) -> dict: raise ValueError(f'The response is not a dictionary. Got: {type(data).__name__}') -def response_to_list(response: Response) -> list: +def response_to_list(*, response: Response) -> list: """Parse the API response as a list and validate its type. Args: @@ -278,7 +278,7 @@ def response_to_list(response: Response) -> list: raise ValueError(f'The response is not a list. Got: {type(data).__name__}') -def encode_base62(num: int) -> str: +def encode_base62(*, num: int) -> str: """Encode an integer to a base62 string. Args: @@ -300,7 +300,7 @@ def encode_base62(num: int) -> str: return ''.join(reversed(parts)) -def create_hmac_signature(secret_key: str, message: str) -> str: +def create_hmac_signature(*, secret_key: str, message: str) -> str: """Generate an HMAC-SHA256 signature and encode it using base62. The HMAC signature is truncated to 30 characters and then encoded in base62 to reduce the signature length. @@ -316,10 +316,11 @@ def create_hmac_signature(secret_key: str, message: str) -> str: decimal_signature = int(signature, 16) - return encode_base62(decimal_signature) + return encode_base62(num=decimal_signature) def create_storage_content_signature( + *, resource_id: str, url_signing_secret_key: str, expires_in: timedelta | None = None, @@ -340,10 +341,10 @@ def create_storage_content_signature( Returns: The base64url-encoded signature string. """ - expires_at = int(time.time() * 1000) + int(to_seconds(expires_in) * 1000) if expires_in is not None else 0 + expires_at = int(time.time() * 1000) + int(to_seconds(td=expires_in) * 1000) if expires_in is not None else 0 message_to_sign = f'{version}.{expires_at}.{resource_id}' - hmac_sig = create_hmac_signature(url_signing_secret_key, message_to_sign) + hmac_sig = create_hmac_signature(secret_key=url_signing_secret_key, message=message_to_sign) base64url_encoded_payload = urlsafe_b64encode(f'{version}.{expires_at}.{hmac_sig}'.encode()) return base64url_encoded_payload.decode('utf-8') diff --git a/src/apify_client/errors.py b/src/apify_client/errors.py index bd4e2205..c7600647 100644 --- a/src/apify_client/errors.py +++ b/src/apify_client/errors.py @@ -17,7 +17,7 @@ class ApifyApiError(ApifyClientError): retried automatically, while validation errors are thrown immediately for user correction. """ - def __init__(self, response: impit.Response, attempt: int, method: str = 'GET') -> None: + def __init__(self, *, response: impit.Response, attempt: int, method: str = 'GET') -> None: """Initialize an API error from a failed response. Args: @@ -61,7 +61,7 @@ class InvalidResponseBodyError(ApifyClientError): Commonly occurs when only partial JSON is received. Usually resolved by retrying the request. """ - def __init__(self, response: impit.Response) -> None: + def __init__(self, *, response: impit.Response) -> None: """Initialize a new instance. Args: diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index dfa8386d..7ffe0dad 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -49,14 +49,14 @@ def api_token_2() -> str: def test_dataset_of_another_user(api_token_2: str) -> Generator[DatasetFixture]: """Dataset owned by secondary user for testing cross-user access restrictions.""" api_url = os.getenv(API_URL_ENV_VAR) or DEFAULT_API_URL - client = ApifyClient(api_token_2, api_url=api_url) + client = ApifyClient(token=api_token_2, api_url=api_url) # Create dataset with test data dataset_name = f'API-test-permissions-{get_crypto_random_object_id()}' dataset = client.datasets().get_or_create(name=dataset_name) dataset_client = client.dataset(dataset_id=dataset.id) expected_content = [{'item1': 1, 'item2': 2, 'item3': 3}, {'item1': 4, 'item2': 5, 'item3': 6}] - dataset_client.push_items(json.dumps(expected_content)) + dataset_client.push_items(items=json.dumps(expected_content)) # Generate signature for authenticated access assert dataset.url_signing_secret_key is not None @@ -78,7 +78,7 @@ def test_dataset_of_another_user(api_token_2: str) -> Generator[DatasetFixture]: def test_kvs_of_another_user(api_token_2: str) -> Generator[KvsFixture]: """Key-value store owned by secondary user for testing cross-user access restrictions.""" api_url = os.getenv(API_URL_ENV_VAR) or DEFAULT_API_URL - client = ApifyClient(api_token_2, api_url=api_url) + client = ApifyClient(token=api_token_2, api_url=api_url) # Create key-value store with test data kvs_name = f'API-test-permissions-{get_crypto_random_object_id()}' @@ -86,7 +86,7 @@ def test_kvs_of_another_user(api_token_2: str) -> Generator[KvsFixture]: kvs_client = client.key_value_store(key_value_store_id=kvs.id) expected_content = {'key1': 1, 'key2': 2, 'key3': 3} for key, value in expected_content.items(): - kvs_client.set_record(key, value) + kvs_client.set_record(key=key, value=value) # Generate signatures for authenticated access signature = create_storage_content_signature( @@ -98,7 +98,10 @@ def test_kvs_of_another_user(api_token_2: str) -> Generator[KvsFixture]: id=kvs.id, signature=signature, expected_content=expected_content, - keys_signature={key: create_hmac_signature(kvs.url_signing_secret_key or '', key) for key in expected_content}, + keys_signature={ + key: create_hmac_signature(secret_key=kvs.url_signing_secret_key or '', message=key) + for key in expected_content + }, ) kvs_client.delete() @@ -113,14 +116,14 @@ def test_kvs_of_another_user(api_token_2: str) -> Generator[KvsFixture]: def apify_client(api_token: str) -> ApifyClient: """Sync Apify client instance.""" api_url = os.getenv(API_URL_ENV_VAR) or DEFAULT_API_URL - return ApifyClient(api_token, api_url=api_url) + return ApifyClient(token=api_token, api_url=api_url) @pytest.fixture def apify_client_async(api_token: str) -> ApifyClientAsync: """Async Apify client instance.""" api_url = os.getenv(API_URL_ENV_VAR) or DEFAULT_API_URL - return ApifyClientAsync(api_token, api_url=api_url) + return ApifyClientAsync(token=api_token, api_url=api_url) @pytest.fixture(params=['sync', 'async']) diff --git a/tests/integration/test_actor.py b/tests/integration/test_actor.py index 9f12b0ed..cbdf3022 100644 --- a/tests/integration/test_actor.py +++ b/tests/integration/test_actor.py @@ -15,7 +15,7 @@ async def test_get_public_actor(client: ApifyClient | ApifyClientAsync) -> None: """Test getting a public Actor by ID.""" # Use a well-known public actor (Apify's web scraper) - result = await maybe_await(client.actor('apify/web-scraper').get()) + result = await maybe_await(client.actor(actor_id='apify/web-scraper').get()) actor = cast('Actor', result) assert actor is not None @@ -26,7 +26,7 @@ async def test_get_public_actor(client: ApifyClient | ApifyClientAsync) -> None: async def test_get_actor_by_full_name(client: ApifyClient | ApifyClientAsync) -> None: """Test getting an Actor using username/actorname format.""" - result = await maybe_await(client.actor('apify/hello-world').get()) + result = await maybe_await(client.actor(actor_id='apify/hello-world').get()) actor = cast('Actor', result) assert actor is not None @@ -99,7 +99,7 @@ async def test_actor_create_update_delete(client: ApifyClient | ApifyClientAsync assert created_actor.id is not None assert created_actor.name == actor_name - actor_client = client.actor(created_actor.id) + actor_client = client.actor(actor_id=created_actor.id) try: # Update actor (only title and description - updating defaultRunOptions requires build to be set) @@ -134,7 +134,7 @@ async def test_actor_create_update_delete(client: ApifyClient | ApifyClientAsync async def test_actor_default_build(client: ApifyClient | ApifyClientAsync) -> None: """Test getting an Actor's default build.""" # Use a public actor that has builds - actor_client = client.actor('apify/hello-world') + actor_client = client.actor(actor_id='apify/hello-world') # Get default build client result = await maybe_await(actor_client.default_build()) @@ -152,7 +152,7 @@ async def test_actor_default_build(client: ApifyClient | ApifyClientAsync) -> No async def test_actor_last_run(client: ApifyClient | ApifyClientAsync) -> None: """Test getting an Actor's last run.""" # First run an actor to ensure there is a last run - actor_client = client.actor('apify/hello-world') + actor_client = client.actor(actor_id='apify/hello-world') result = await maybe_await(actor_client.call()) run = cast('Run', result) assert run is not None @@ -169,14 +169,14 @@ async def test_actor_last_run(client: ApifyClient | ApifyClientAsync) -> None: assert last_run.id is not None finally: - await maybe_await(client.run(run.id).delete()) + await maybe_await(client.run(run_id=run.id).delete()) async def test_actor_validate_input(client: ApifyClient | ApifyClientAsync) -> None: """Test validating Actor input.""" # Use a public actor with an input schema - actor_client = client.actor('apify/hello-world') + actor_client = client.actor(actor_id='apify/hello-world') # Valid input (hello-world accepts empty input or simple input) - is_valid = await maybe_await(actor_client.validate_input({})) + is_valid = await maybe_await(actor_client.validate_input(run_input={})) assert is_valid is True diff --git a/tests/integration/test_actor_env_var.py b/tests/integration/test_actor_env_var.py index 97011b9c..e46c7cc5 100644 --- a/tests/integration/test_actor_env_var.py +++ b/tests/integration/test_actor_env_var.py @@ -44,8 +44,8 @@ async def test_actor_env_var_list(client: ApifyClient | ApifyClientAsync) -> Non ) ) actor = cast('Actor', result) - actor_client = client.actor(actor.id) - version_client = actor_client.version('0.0') + actor_client = client.actor(actor_id=actor.id) + version_client = actor_client.version(version_number='0.0') try: # List env vars @@ -90,8 +90,8 @@ async def test_actor_env_var_create_and_get(client: ApifyClient | ApifyClientAsy ) ) actor = cast('Actor', result) - actor_client = client.actor(actor.id) - version_client = actor_client.version('1.0') + actor_client = client.actor(actor_id=actor.id) + version_client = actor_client.version(version_number='1.0') try: # Create a new env var @@ -110,7 +110,7 @@ async def test_actor_env_var_create_and_get(client: ApifyClient | ApifyClientAsy assert created_env_var.is_secret is False # Get the same env var - env_var_client = version_client.env_var('MY_VAR') + env_var_client = version_client.env_var(env_var_name='MY_VAR') result = await maybe_await(env_var_client.get()) retrieved_env_var = cast('EnvVar', result) @@ -154,9 +154,9 @@ async def test_actor_env_var_update(client: ApifyClient | ApifyClientAsync) -> N ) ) actor = cast('Actor', result) - actor_client = client.actor(actor.id) - version_client = actor_client.version('0.1') - env_var_client = version_client.env_var('UPDATE_VAR') + actor_client = client.actor(actor_id=actor.id) + version_client = actor_client.version(version_number='0.1') + env_var_client = version_client.env_var(env_var_name='UPDATE_VAR') try: # Update the env var @@ -219,12 +219,12 @@ async def test_actor_env_var_delete(client: ApifyClient | ApifyClientAsync) -> N ) ) actor = cast('Actor', result) - actor_client = client.actor(actor.id) - version_client = actor_client.version('0.1') + actor_client = client.actor(actor_id=actor.id) + version_client = actor_client.version(version_number='0.1') try: # Delete the first env var - env_var_client = version_client.env_var('VAR_TO_DELETE') + env_var_client = version_client.env_var(env_var_name='VAR_TO_DELETE') await maybe_await(env_var_client.delete()) # Verify it's gone @@ -232,7 +232,7 @@ async def test_actor_env_var_delete(client: ApifyClient | ApifyClientAsync) -> N assert deleted_env_var is None # Verify the other env var still exists - result = await maybe_await(version_client.env_var('VAR_TO_KEEP').get()) + result = await maybe_await(version_client.env_var(env_var_name='VAR_TO_KEEP').get()) remaining_env_var = cast('EnvVar', result) assert remaining_env_var is not None assert remaining_env_var.name == 'VAR_TO_KEEP' diff --git a/tests/integration/test_actor_version.py b/tests/integration/test_actor_version.py index 9fb09023..ad72b842 100644 --- a/tests/integration/test_actor_version.py +++ b/tests/integration/test_actor_version.py @@ -38,7 +38,7 @@ async def test_actor_version_list(client: ApifyClient | ApifyClientAsync) -> Non ) ) actor = cast('Actor', result) - actor_client = client.actor(actor.id) + actor_client = client.actor(actor_id=actor.id) try: # List versions @@ -65,7 +65,7 @@ async def test_actor_version_create_and_get(client: ApifyClient | ApifyClientAsy # Create an actor without versions result = await maybe_await(client.actors().create(name=actor_name)) actor = cast('Actor', result) - actor_client = client.actor(actor.id) + actor_client = client.actor(actor_id=actor.id) try: # Create a new version @@ -91,7 +91,7 @@ async def test_actor_version_create_and_get(client: ApifyClient | ApifyClientAsy assert created_version.source_type == VersionSourceType.SOURCE_FILES # Get the same version - version_client = actor_client.version('1.0') + version_client = actor_client.version(version_number='1.0') result = await maybe_await(version_client.get()) retrieved_version = cast('Version | None', result) @@ -128,8 +128,8 @@ async def test_actor_version_update(client: ApifyClient | ApifyClientAsync) -> N ) ) actor = cast('Actor', result) - actor_client = client.actor(actor.id) - version_client = actor_client.version('0.1') + actor_client = client.actor(actor_id=actor.id) + version_client = actor_client.version(version_number='0.1') try: # Update the version @@ -198,11 +198,11 @@ async def test_actor_version_delete(client: ApifyClient | ApifyClientAsync) -> N ) ) actor = cast('Actor', result) - actor_client = client.actor(actor.id) + actor_client = client.actor(actor_id=actor.id) try: # Delete version 0.1 - version_client = actor_client.version('0.1') + version_client = actor_client.version(version_number='0.1') await maybe_await(version_client.delete()) # Verify it's gone @@ -210,7 +210,7 @@ async def test_actor_version_delete(client: ApifyClient | ApifyClientAsync) -> N assert deleted_version is None # Verify version 0.2 still exists - result = await maybe_await(actor_client.version('0.2').get()) + result = await maybe_await(actor_client.version(version_number='0.2').get()) remaining_version = cast('Version | None', result) assert remaining_version is not None assert remaining_version.version_number == '0.2' diff --git a/tests/integration/test_apify_client.py b/tests/integration/test_apify_client.py index 6bd1bf92..bcaa722e 100644 --- a/tests/integration/test_apify_client.py +++ b/tests/integration/test_apify_client.py @@ -14,7 +14,7 @@ async def test_apify_client(client: ApifyClient | ApifyClientAsync) -> None: """Test basic apify client functionality.""" - user_client = client.user('me') + user_client = client.user(user_id='me') result = await maybe_await(user_client.get()) me = cast('UserPrivateInfo | UserPublicInfo', result) assert me.username is not None diff --git a/tests/integration/test_build.py b/tests/integration/test_build.py index bcf5cfe1..b1ca12c8 100644 --- a/tests/integration/test_build.py +++ b/tests/integration/test_build.py @@ -20,7 +20,7 @@ async def test_build_list_for_actor(client: ApifyClient | ApifyClientAsync) -> None: """Test listing builds for a public Actor.""" # Get builds for hello-world actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.builds().list(limit=10)) builds_page = cast('ListOfBuilds', result) @@ -37,14 +37,14 @@ async def test_build_list_for_actor(client: ApifyClient | ApifyClientAsync) -> N async def test_build_get(client: ApifyClient | ApifyClientAsync) -> None: """Test getting a specific build.""" # First list builds to get a build ID - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.builds().list(limit=1)) builds_page = cast('ListOfBuilds', result) assert builds_page.items build_id = builds_page.items[0].id # Get the specific build - result = await maybe_await(client.build(build_id).get()) + result = await maybe_await(client.build(build_id=build_id).get()) build = cast('Build | None', result) assert build is not None @@ -68,7 +68,7 @@ async def test_user_builds_list(client: ApifyClient | ApifyClientAsync) -> None: async def test_build_log(client: ApifyClient | ApifyClientAsync) -> None: """Test getting build log.""" # First list builds to get a completed build ID - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.builds().list(limit=5)) builds_page = cast('ListOfBuilds', result) assert builds_page.items @@ -85,7 +85,7 @@ async def test_build_log(client: ApifyClient | ApifyClientAsync) -> None: completed_build = builds_page.items[0] # Get the build log - log_client = client.build(completed_build.id).log() + log_client = client.build(build_id=completed_build.id).log() log_content = await maybe_await(log_client.get()) # Build logs should be available for completed builds @@ -95,7 +95,7 @@ async def test_build_log(client: ApifyClient | ApifyClientAsync) -> None: async def test_build_wait_for_finish(client: ApifyClient | ApifyClientAsync) -> None: """Test wait_for_finish on an already completed build.""" # First list builds to get a completed build ID - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.builds().list(limit=5)) builds_page = cast('ListOfBuilds', result) assert builds_page.items @@ -118,7 +118,9 @@ async def test_build_wait_for_finish(client: ApifyClient | ApifyClientAsync) -> completed_build = builds_page.items[0] # Wait for finish on already completed build (should return immediately) - result = await maybe_await(client.build(completed_build.id).wait_for_finish(wait_duration=timedelta(seconds=5))) + result = await maybe_await( + client.build(build_id=completed_build.id).wait_for_finish(wait_duration=timedelta(seconds=5)) + ) build = cast('Build | None', result) assert build is not None @@ -164,20 +166,20 @@ async def test_build_delete_and_abort(client: ApifyClient | ApifyClientAsync) -> ) created_actor = cast('Actor', result) assert created_actor is not None - actor_client = client.actor(created_actor.id) + actor_client = client.actor(actor_id=created_actor.id) try: # Build both versions - we need 2 builds because we can't delete the default build result = await maybe_await(actor_client.build(version_number='0.1')) first_build = cast('Build', result) assert first_build is not None - first_build_client = client.build(first_build.id) + first_build_client = client.build(build_id=first_build.id) await maybe_await(first_build_client.wait_for_finish()) result = await maybe_await(actor_client.build(version_number='0.2')) second_build = cast('Build', result) assert second_build is not None - second_build_client = client.build(second_build.id) + second_build_client = client.build(build_id=second_build.id) # Wait for the second build to finish result = await maybe_await(second_build_client.wait_for_finish()) @@ -207,14 +209,14 @@ async def test_build_delete_and_abort(client: ApifyClient | ApifyClientAsync) -> async def test_build_get_open_api_definition(client: ApifyClient | ApifyClientAsync) -> None: """Test getting OpenAPI definition for a build.""" # Get builds for hello-world actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.builds().list(limit=1)) builds_page = cast('ListOfBuilds', result) assert builds_page.items build_id = builds_page.items[0].id # Get the OpenAPI definition - build_client = client.build(build_id) + build_client = client.build(build_id=build_id) openapi_def = await maybe_await(build_client.get_open_api_definition()) # OpenAPI definition should be a dict with standard OpenAPI fields diff --git a/tests/integration/test_dataset.py b/tests/integration/test_dataset.py index 6ded3519..9d1b1dcf 100644 --- a/tests/integration/test_dataset.py +++ b/tests/integration/test_dataset.py @@ -61,7 +61,7 @@ async def test_dataset_collection_get_or_create(client: ApifyClient | ApifyClien same_dataset = cast('Dataset', result2) assert same_dataset.id == dataset.id finally: - await maybe_await(client.dataset(dataset.id).delete()) + await maybe_await(client.dataset(dataset_id=dataset.id).delete()) async def test_dataset_should_create_public_items_expiring_url_with_params( @@ -71,7 +71,7 @@ async def test_dataset_should_create_public_items_expiring_url_with_params( result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset = client.dataset(created_dataset.id) + dataset = client.dataset(dataset_id=created_dataset.id) try: result = await maybe_await( @@ -101,7 +101,7 @@ async def test_dataset_should_create_public_items_non_expiring_url( result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset = client.dataset(created_dataset.id) + dataset = client.dataset(dataset_id=created_dataset.id) try: result = await maybe_await(dataset.create_items_public_url()) @@ -202,7 +202,7 @@ async def test_dataset_get_or_create_and_get(client: ApifyClient | ApifyClientAs assert created_dataset.name == dataset_name # Get the same dataset - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: result = await maybe_await(dataset_client.get()) @@ -221,7 +221,7 @@ async def test_dataset_update(client: ApifyClient | ApifyClientAsync) -> None: result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: # Update the name @@ -246,7 +246,7 @@ async def test_dataset_push_and_list_items(client: ApifyClient | ApifyClientAsyn result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: # Push some items @@ -255,7 +255,7 @@ async def test_dataset_push_and_list_items(client: ApifyClient | ApifyClientAsyn {'id': 2, 'name': 'Item 2', 'value': 200}, {'id': 3, 'name': 'Item 3', 'value': 300}, ] - await maybe_await(dataset_client.push_items(items_to_push)) + await maybe_await(dataset_client.push_items(items=items_to_push)) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -283,12 +283,12 @@ async def test_dataset_list_items_with_pagination(client: ApifyClient | ApifyCli result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: # Push more items items_to_push = [{'index': i, 'value': i * 10} for i in range(10)] - await maybe_await(dataset_client.push_items(items_to_push)) + await maybe_await(dataset_client.push_items(items=items_to_push)) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -320,7 +320,7 @@ async def test_dataset_list_items_with_fields(client: ApifyClient | ApifyClientA result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: # Push items with multiple fields @@ -328,7 +328,7 @@ async def test_dataset_list_items_with_fields(client: ApifyClient | ApifyClientA {'id': 1, 'name': 'Item 1', 'value': 100, 'extra': 'data1'}, {'id': 2, 'name': 'Item 2', 'value': 200, 'extra': 'data2'}, ] - await maybe_await(dataset_client.push_items(items_to_push)) + await maybe_await(dataset_client.push_items(items=items_to_push)) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -354,12 +354,12 @@ async def test_dataset_iterate_items(client: ApifyClient | ApifyClientAsync, *, result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: # Push items items_to_push = [{'index': i} for i in range(5)] - await maybe_await(dataset_client.push_items(items_to_push)) + await maybe_await(dataset_client.push_items(items=items_to_push)) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -383,7 +383,7 @@ async def test_dataset_delete_nonexistent(client: ApifyClient | ApifyClientAsync result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) # Delete dataset await maybe_await(dataset_client.delete()) @@ -400,7 +400,7 @@ async def test_dataset_get_statistics(client: ApifyClient | ApifyClientAsync, *, result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: # Push some items first @@ -408,7 +408,7 @@ async def test_dataset_get_statistics(client: ApifyClient | ApifyClientAsync, *, {'id': 1, 'name': 'Item 1'}, {'id': 2, 'name': 'Item 2'}, ] - await maybe_await(dataset_client.push_items(items_to_push)) + await maybe_await(dataset_client.push_items(items=items_to_push)) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -430,7 +430,7 @@ async def test_dataset_stream_items(client: ApifyClient | ApifyClientAsync, *, i result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) created_dataset = cast('Dataset', result) - dataset_client = client.dataset(created_dataset.id) + dataset_client = client.dataset(dataset_id=created_dataset.id) try: # Push some items @@ -439,7 +439,7 @@ async def test_dataset_stream_items(client: ApifyClient | ApifyClientAsync, *, i {'id': 2, 'name': 'Item 2', 'value': 200}, {'id': 3, 'name': 'Item 3', 'value': 300}, ] - await maybe_await(dataset_client.push_items(items_to_push)) + await maybe_await(dataset_client.push_items(items=items_to_push)) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) diff --git a/tests/integration/test_key_value_store.py b/tests/integration/test_key_value_store.py index 16716c49..768a2779 100644 --- a/tests/integration/test_key_value_store.py +++ b/tests/integration/test_key_value_store.py @@ -57,7 +57,7 @@ async def test_key_value_store_collection_get_or_create(client: ApifyClient | Ap same_kvs = cast('KeyValueStore', result2) assert same_kvs.id == kvs.id finally: - await maybe_await(client.key_value_store(kvs.id).delete()) + await maybe_await(client.key_value_store(key_value_store_id=kvs.id).delete()) async def test_key_value_store_should_create_expiring_keys_public_url_with_params( @@ -67,7 +67,7 @@ async def test_key_value_store_should_create_expiring_keys_public_url_with_param result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store = client.key_value_store(created_store.id) + store = client.key_value_store(key_value_store_id=created_store.id) try: result = await maybe_await( @@ -95,7 +95,7 @@ async def test_key_value_store_should_create_public_keys_non_expiring_url( result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store = client.key_value_store(created_store.id) + store = client.key_value_store(key_value_store_id=created_store.id) try: result = await maybe_await(store.create_keys_public_url()) @@ -231,7 +231,7 @@ async def test_key_value_store_get_or_create_and_get(client: ApifyClient | Apify assert created_store.name == store_name # Get the same store - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: result = await maybe_await(store_client.get()) @@ -250,7 +250,7 @@ async def test_key_value_store_update(client: ApifyClient | ApifyClientAsync) -> result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Update the name @@ -275,18 +275,18 @@ async def test_key_value_store_set_and_get_record(client: ApifyClient | ApifyCli result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set a JSON record test_value = {'name': 'Test Item', 'value': 123, 'nested': {'data': 'value'}} - await maybe_await(store_client.set_record('test-key', test_value)) + await maybe_await(store_client.set_record(key='test-key', value=test_value)) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) # Get the record - result = await maybe_await(store_client.get_record('test-key')) + result = await maybe_await(store_client.get_record(key='test-key')) record = cast('dict', result) assert record is not None assert record['key'] == 'test-key' @@ -304,18 +304,18 @@ async def test_key_value_store_set_and_get_text_record( result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set a text record test_text = 'Hello, this is a test text!' - await maybe_await(store_client.set_record('text-key', test_text, content_type='text/plain')) + await maybe_await(store_client.set_record(key='text-key', value=test_text, content_type='text/plain')) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) # Get the record - result = await maybe_await(store_client.get_record('text-key')) + result = await maybe_await(store_client.get_record(key='text-key')) record = cast('dict', result) assert record is not None assert record['key'] == 'text-key' @@ -331,12 +331,12 @@ async def test_key_value_store_list_keys(client: ApifyClient | ApifyClientAsync, result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set multiple records for i in range(5): - await maybe_await(store_client.set_record(f'key-{i}', {'index': i})) + await maybe_await(store_client.set_record(key=f'key-{i}', value={'index': i})) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -361,12 +361,12 @@ async def test_key_value_store_list_keys_with_limit(client: ApifyClient | ApifyC result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set multiple records for i in range(10): - await maybe_await(store_client.set_record(f'item-{i:02d}', {'index': i})) + await maybe_await(store_client.set_record(key=f'item-{i:02d}', value={'index': i})) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -386,19 +386,19 @@ async def test_key_value_store_record_exists(client: ApifyClient | ApifyClientAs result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set a record - await maybe_await(store_client.set_record('exists-key', {'data': 'value'})) + await maybe_await(store_client.set_record(key='exists-key', value={'data': 'value'})) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) # Check existence - result = await maybe_await(store_client.record_exists('exists-key')) + result = await maybe_await(store_client.record_exists(key='exists-key')) assert result is True - result = await maybe_await(store_client.record_exists('non-existent-key')) + result = await maybe_await(store_client.record_exists(key='non-existent-key')) assert result is False finally: await maybe_await(store_client.delete()) @@ -410,27 +410,27 @@ async def test_key_value_store_delete_record(client: ApifyClient | ApifyClientAs result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set a record - await maybe_await(store_client.set_record('delete-me', {'data': 'value'})) + await maybe_await(store_client.set_record(key='delete-me', value={'data': 'value'})) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) # Verify it exists - result = await maybe_await(store_client.get_record('delete-me')) + result = await maybe_await(store_client.get_record(key='delete-me')) assert result is not None # Delete the record - await maybe_await(store_client.delete_record('delete-me')) + await maybe_await(store_client.delete_record(key='delete-me')) # Wait briefly await maybe_sleep(1, is_async=is_async) # Verify it's gone - result = await maybe_await(store_client.get_record('delete-me')) + result = await maybe_await(store_client.get_record(key='delete-me')) assert result is None finally: await maybe_await(store_client.delete()) @@ -442,7 +442,7 @@ async def test_key_value_store_delete_nonexistent(client: ApifyClient | ApifyCli result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) # Delete store await maybe_await(store_client.delete()) @@ -459,12 +459,12 @@ async def test_key_value_store_iterate_keys(client: ApifyClient | ApifyClientAsy result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set multiple records for i in range(5): - await maybe_await(store_client.set_record(f'key-{i}', {'index': i})) + await maybe_await(store_client.set_record(key=f'key-{i}', value={'index': i})) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -493,12 +493,12 @@ async def test_key_value_store_iterate_keys_with_limit( result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set multiple records for i in range(10): - await maybe_await(store_client.set_record(f'item-{i:02d}', {'index': i})) + await maybe_await(store_client.set_record(key=f'item-{i:02d}', value={'index': i})) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -524,14 +524,14 @@ async def test_key_value_store_iterate_keys_with_prefix( result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) created_store = cast('KeyValueStore', result) - store_client = client.key_value_store(created_store.id) + store_client = client.key_value_store(key_value_store_id=created_store.id) try: # Set records with different prefixes for i in range(3): - await maybe_await(store_client.set_record(f'prefix-a-{i}', {'type': 'a', 'index': i})) + await maybe_await(store_client.set_record(key=f'prefix-a-{i}', value={'type': 'a', 'index': i})) for i in range(2): - await maybe_await(store_client.set_record(f'prefix-b-{i}', {'type': 'b', 'index': i})) + await maybe_await(store_client.set_record(key=f'prefix-b-{i}', value={'type': 'b', 'index': i})) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) diff --git a/tests/integration/test_log.py b/tests/integration/test_log.py index 4f49bc39..7dfc1a57 100644 --- a/tests/integration/test_log.py +++ b/tests/integration/test_log.py @@ -18,13 +18,13 @@ async def test_log_get_from_run(client: ApifyClient | ApifyClientAsync) -> None: """Test retrieving log from an Actor run.""" # Run hello-world actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) assert result is not None run = cast('Run', result) # Get log as text - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) log = await maybe_await(run_client.log().get()) assert log is not None @@ -38,14 +38,14 @@ async def test_log_get_from_run(client: ApifyClient | ApifyClientAsync) -> None: async def test_log_get_from_build(client: ApifyClient | ApifyClientAsync) -> None: """Test retrieving log from a build.""" # Get a build from hello-world actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.builds().list(limit=1)) builds_page = cast('ListOfBuilds', result) assert builds_page.items build_id = builds_page.items[0].id # Get log from the build - build = client.build(build_id) + build = client.build(build_id=build_id) log = await maybe_await(build.log().get()) # Build log may be None or empty for some builds @@ -56,13 +56,13 @@ async def test_log_get_from_build(client: ApifyClient | ApifyClientAsync) -> Non async def test_log_get_as_bytes(client: ApifyClient | ApifyClientAsync) -> None: """Test retrieving log as raw bytes.""" # Run hello-world actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) assert result is not None run = cast('Run', result) # Get log as bytes - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) log_bytes = await maybe_await(run_client.log().get_as_bytes()) assert log_bytes is not None diff --git a/tests/integration/test_request_queue.py b/tests/integration/test_request_queue.py index 170deb3a..728937cd 100644 --- a/tests/integration/test_request_queue.py +++ b/tests/integration/test_request_queue.py @@ -63,19 +63,19 @@ async def test_request_queue_collection_get_or_create(client: ApifyClient | Apif same_rq = cast('RequestQueue', result2) assert same_rq.id == rq.id finally: - await maybe_await(client.request_queue(rq.id).delete()) + await maybe_await(client.request_queue(request_queue_id=rq.id).delete()) async def test_request_queue_lock(client: ApifyClient | ApifyClientAsync) -> None: result = await maybe_await(client.request_queues().get_or_create(name=get_random_resource_name('queue'))) created_rq = cast('RequestQueue', result) - rq = client.request_queue(created_rq.id, client_key=get_random_string(10)) + rq = client.request_queue(request_queue_id=created_rq.id, client_key=get_random_string(10)) try: # Add requests and check if correct number of requests was locked for i in range(15): await maybe_await( - rq.add_request({'url': f'http://test-lock.com/{i}', 'uniqueKey': f'http://test-lock.com/{i}'}) + rq.add_request(request={'url': f'http://test-lock.com/{i}', 'uniqueKey': f'http://test-lock.com/{i}'}) ) result = await maybe_await(rq.list_and_lock_head(limit=10, lock_duration=timedelta(seconds=10))) @@ -85,7 +85,7 @@ async def test_request_queue_lock(client: ApifyClient | ApifyClientAsync) -> Non assert locked_request.lock_expires_at is not None # Check if the delete request works - await maybe_await(rq.delete_request_lock(get_head_and_lock_response.items[1].id)) + await maybe_await(rq.delete_request_lock(request_id=get_head_and_lock_response.items[1].id)) """This is probably not working: delete_lock_request = await maybe_await(rq.get_request(get_head_and_lock_response.items[1].id)) @@ -93,7 +93,7 @@ async def test_request_queue_lock(client: ApifyClient | ApifyClientAsync) -> Non assert delete_lock_request.lock_expires_at is None """ - await maybe_await(rq.delete_request_lock(get_head_and_lock_response.items[2].id, forefront=True)) + await maybe_await(rq.delete_request_lock(request_id=get_head_and_lock_response.items[2].id, forefront=True)) """This is probably not working: delete_lock_request2 = await maybe_await(rq.get_request(get_head_and_lock_response.items[2].id)) @@ -104,7 +104,7 @@ async def test_request_queue_lock(client: ApifyClient | ApifyClientAsync) -> Non # Check if the prolong request works result = await maybe_await( rq.prolong_request_lock( - get_head_and_lock_response.items[3].id, + request_id=get_head_and_lock_response.items[3].id, lock_duration=timedelta(seconds=15), ) ) @@ -122,7 +122,7 @@ async def test_request_queue_get_or_create_and_get(client: ApifyClient | ApifyCl # Create queue result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: assert created_rq is not None @@ -146,7 +146,7 @@ async def test_request_queue_update(client: ApifyClient | ApifyClientAsync) -> N result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Update the name @@ -171,7 +171,7 @@ async def test_request_queue_add_and_get_request(client: ApifyClient | ApifyClie result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Add a request @@ -180,7 +180,7 @@ async def test_request_queue_add_and_get_request(client: ApifyClient | ApifyClie 'uniqueKey': 'test-key-1', 'method': 'GET', } - result = await maybe_await(rq_client.add_request(request_data)) + result = await maybe_await(rq_client.add_request(request=request_data)) add_result = cast('RequestRegistration', result) assert add_result is not None assert add_result.request_id is not None @@ -190,7 +190,7 @@ async def test_request_queue_add_and_get_request(client: ApifyClient | ApifyClie await maybe_sleep(1, is_async=is_async) # Get the request - result = await maybe_await(rq_client.get_request(add_result.request_id)) + result = await maybe_await(rq_client.get_request(request_id=add_result.request_id)) request = cast('Request', result) assert request is not None assert str(request.url) == 'https://example.com/test' @@ -205,14 +205,14 @@ async def test_request_queue_list_head(client: ApifyClient | ApifyClientAsync, * result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Add multiple requests for i in range(5): await maybe_await( rq_client.add_request( - { + request={ 'url': f'https://example.com/page-{i}', 'uniqueKey': f'page-{i}', } @@ -237,14 +237,14 @@ async def test_request_queue_list_requests(client: ApifyClient | ApifyClientAsyn result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Add multiple requests for i in range(5): await maybe_await( rq_client.add_request( - { + request={ 'url': f'https://example.com/item-{i}', 'uniqueKey': f'item-{i}', } @@ -269,13 +269,13 @@ async def test_request_queue_delete_request(client: ApifyClient | ApifyClientAsy result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Add a request result = await maybe_await( rq_client.add_request( - { + request={ 'url': 'https://example.com/to-delete', 'uniqueKey': 'delete-me', } @@ -287,17 +287,17 @@ async def test_request_queue_delete_request(client: ApifyClient | ApifyClientAsy await maybe_sleep(1, is_async=is_async) # Verify it exists - request = await maybe_await(rq_client.get_request(add_result.request_id)) + request = await maybe_await(rq_client.get_request(request_id=add_result.request_id)) assert request is not None # Delete the request - await maybe_await(rq_client.delete_request(add_result.request_id)) + await maybe_await(rq_client.delete_request(request_id=add_result.request_id)) # Wait briefly await maybe_sleep(1, is_async=is_async) # Verify it's gone - deleted_request = await maybe_await(rq_client.get_request(add_result.request_id)) + deleted_request = await maybe_await(rq_client.get_request(request_id=add_result.request_id)) assert deleted_request is None finally: await maybe_await(rq_client.delete()) @@ -309,12 +309,12 @@ async def test_request_queue_batch_add_requests(client: ApifyClient | ApifyClien result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Batch add requests requests_to_add = [{'url': f'https://example.com/batch-{i}', 'uniqueKey': f'batch-{i}'} for i in range(10)] - result = await maybe_await(rq_client.batch_add_requests(requests_to_add)) + result = await maybe_await(rq_client.batch_add_requests(requests=requests_to_add)) batch_response = cast('BatchAddResult', result) assert batch_response is not None assert len(batch_response.processed_requests) == 10 @@ -337,14 +337,14 @@ async def test_request_queue_batch_delete_requests(client: ApifyClient | ApifyCl result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Add requests for i in range(10): await maybe_await( rq_client.add_request( - { + request={ 'url': f'https://example.com/delete-{i}', 'uniqueKey': f'delete-{i}', } @@ -360,7 +360,7 @@ async def test_request_queue_batch_delete_requests(client: ApifyClient | ApifyCl requests_to_delete = [{'uniqueKey': item.unique_key} for item in list_response.items[:5]] # Batch delete - result = await maybe_await(rq_client.batch_delete_requests(requests_to_delete)) + result = await maybe_await(rq_client.batch_delete_requests(requests=requests_to_delete)) delete_response = cast('BatchDeleteResult', result) assert delete_response is not None assert len(delete_response.processed_requests) == 5 @@ -382,7 +382,7 @@ async def test_request_queue_delete_nonexistent(client: ApifyClient | ApifyClien result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) # Delete queue await maybe_await(rq_client.delete()) @@ -398,12 +398,14 @@ async def test_request_queue_list_and_lock_head(client: ApifyClient | ApifyClien result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) + rq_client = client.request_queue(request_queue_id=created_rq.id, client_key=get_random_string(10)) try: # Add multiple requests for i in range(5): - await maybe_await(rq_client.add_request({'url': f'https://example.com/lock-{i}', 'uniqueKey': f'lock-{i}'})) + await maybe_await( + rq_client.add_request(request={'url': f'https://example.com/lock-{i}', 'uniqueKey': f'lock-{i}'}) + ) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -428,11 +430,13 @@ async def test_request_queue_prolong_request_lock(client: ApifyClient | ApifyCli result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) + rq_client = client.request_queue(request_queue_id=created_rq.id, client_key=get_random_string(10)) try: # Add a request - await maybe_await(rq_client.add_request({'url': 'https://example.com/prolong', 'uniqueKey': 'prolong-test'})) + await maybe_await( + rq_client.add_request(request={'url': 'https://example.com/prolong', 'uniqueKey': 'prolong-test'}) + ) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -446,7 +450,7 @@ async def test_request_queue_prolong_request_lock(client: ApifyClient | ApifyCli # Prolong the lock result = await maybe_await( - rq_client.prolong_request_lock(locked_request.id, lock_duration=timedelta(seconds=120)) + rq_client.prolong_request_lock(request_id=locked_request.id, lock_duration=timedelta(seconds=120)) ) prolong_response = cast('RequestLockInfo', result) assert prolong_response is not None @@ -462,11 +466,13 @@ async def test_request_queue_delete_request_lock(client: ApifyClient | ApifyClie result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) + rq_client = client.request_queue(request_queue_id=created_rq.id, client_key=get_random_string(10)) try: # Add a request - await maybe_await(rq_client.add_request({'url': 'https://example.com/unlock', 'uniqueKey': 'unlock-test'})) + await maybe_await( + rq_client.add_request(request={'url': 'https://example.com/unlock', 'uniqueKey': 'unlock-test'}) + ) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -478,11 +484,11 @@ async def test_request_queue_delete_request_lock(client: ApifyClient | ApifyClie locked_request = lock_response.items[0] # Delete the lock - await maybe_await(rq_client.delete_request_lock(locked_request.id)) + await maybe_await(rq_client.delete_request_lock(request_id=locked_request.id)) # Verify the operation succeeded (no exception thrown) # The request should still exist but be unlocked - request = await maybe_await(rq_client.get_request(locked_request.id)) + request = await maybe_await(rq_client.get_request(request_id=locked_request.id)) assert request is not None finally: await maybe_await(rq_client.delete()) @@ -494,13 +500,13 @@ async def test_request_queue_unlock_requests(client: ApifyClient | ApifyClientAs result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) + rq_client = client.request_queue(request_queue_id=created_rq.id, client_key=get_random_string(10)) try: # Add multiple requests for i in range(5): await maybe_await( - rq_client.add_request({'url': f'https://example.com/unlock-{i}', 'uniqueKey': f'unlock-{i}'}) + rq_client.add_request(request={'url': f'https://example.com/unlock-{i}', 'uniqueKey': f'unlock-{i}'}) ) # Wait briefly for eventual consistency @@ -526,7 +532,7 @@ async def test_request_queue_update_request(client: ApifyClient | ApifyClientAsy result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) created_rq = cast('RequestQueue', result) - rq_client = client.request_queue(created_rq.id) + rq_client = client.request_queue(request_queue_id=created_rq.id) try: # Add a request @@ -535,7 +541,7 @@ async def test_request_queue_update_request(client: ApifyClient | ApifyClientAsy 'uniqueKey': 'update-test', 'method': 'GET', } - result = await maybe_await(rq_client.add_request(request_data)) + result = await maybe_await(rq_client.add_request(request=request_data)) add_result = cast('RequestRegistration', result) assert add_result is not None assert add_result.request_id is not None @@ -544,7 +550,7 @@ async def test_request_queue_update_request(client: ApifyClient | ApifyClientAsy await maybe_sleep(1, is_async=is_async) # Get the request to get its full data - result = await maybe_await(rq_client.get_request(add_result.request_id)) + result = await maybe_await(rq_client.get_request(request_id=add_result.request_id)) original_request = cast('Request', result) assert original_request is not None @@ -556,7 +562,7 @@ async def test_request_queue_update_request(client: ApifyClient | ApifyClientAsy 'method': 'POST', 'userData': {'updated': True}, } - result = await maybe_await(rq_client.update_request(updated_request_data)) + result = await maybe_await(rq_client.update_request(request=updated_request_data)) update_result = cast('RequestRegistration', result) assert update_result is not None assert update_result.request_id == add_result.request_id diff --git a/tests/integration/test_run.py b/tests/integration/test_run.py index 774a227f..61b0ecaa 100644 --- a/tests/integration/test_run.py +++ b/tests/integration/test_run.py @@ -22,18 +22,18 @@ async def test_run_collection_list_multiple_statuses(client: ApifyClient | Apify """Test listing runs with multiple statuses.""" created_runs = list[Run]() - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).call()) if result is not None: successful_run = cast('Run', result) created_runs.append(successful_run) - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) if result is not None: timed_out_run = cast('Run', result) created_runs.append(timed_out_run) try: - run_collection = client.actor(HELLO_WORLD_ACTOR).runs() + run_collection = client.actor(actor_id=HELLO_WORLD_ACTOR).runs() result = await maybe_await(run_collection.list(status=[ActorJobStatus.SUCCEEDED, ActorJobStatus.TIMED_OUT])) multiple_status_runs = cast('ListOfRuns', result) @@ -52,19 +52,19 @@ async def test_run_collection_list_multiple_statuses(client: ApifyClient | Apify for run in created_runs: run_id = run.id if isinstance(run_id, str): - await maybe_await(client.run(run_id).delete()) + await maybe_await(client.run(run_id=run_id).delete()) async def test_run_collection_list_accept_date_range(client: ApifyClient | ApifyClientAsync) -> None: """Test listing runs with date range parameters.""" created_runs = list[Run]() - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).call()) if result is not None: successful_run = cast('Run', result) created_runs.append(successful_run) - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) if result is not None: timed_out_run = cast('Run', result) created_runs.append(timed_out_run) @@ -83,19 +83,19 @@ async def test_run_collection_list_accept_date_range(client: ApifyClient | Apify for run in created_runs: run_id = run.id if isinstance(run_id, str): - await maybe_await(client.run(run_id).delete()) + await maybe_await(client.run(run_id=run_id).delete()) async def test_run_get_and_delete(client: ApifyClient | ApifyClientAsync) -> None: """Test getting and deleting a run.""" # Run actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None # Get the run - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) result = await maybe_await(run_client.get()) retrieved_run = cast('Run', result) assert retrieved_run is not None @@ -113,13 +113,13 @@ async def test_run_get_and_delete(client: ApifyClient | ApifyClientAsync) -> Non async def test_run_dataset(client: ApifyClient | ApifyClientAsync) -> None: """Test accessing run's default dataset.""" # Run actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None # Access run's dataset - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: dataset_client = run_client.dataset() @@ -136,13 +136,13 @@ async def test_run_dataset(client: ApifyClient | ApifyClientAsync) -> None: async def test_run_key_value_store(client: ApifyClient | ApifyClientAsync) -> None: """Test accessing run's default key-value store.""" # Run actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None # Access run's key-value store - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: kvs_client = run_client.key_value_store() @@ -159,13 +159,13 @@ async def test_run_key_value_store(client: ApifyClient | ApifyClientAsync) -> No async def test_run_request_queue(client: ApifyClient | ApifyClientAsync) -> None: """Test accessing run's default request queue.""" # Run actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None # Access run's request queue - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: rq_client = run_client.request_queue() @@ -182,14 +182,14 @@ async def test_run_request_queue(client: ApifyClient | ApifyClientAsync) -> None async def test_run_abort(client: ApifyClient | ApifyClientAsync) -> None: """Test aborting a running Actor.""" # Start actor without waiting - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.start()) run = cast('Run', result) assert run is not None assert run.id is not None # Abort the run - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: result = await maybe_await(run_client.abort()) @@ -212,12 +212,12 @@ async def test_run_abort(client: ApifyClient | ApifyClientAsync) -> None: async def test_run_update(client: ApifyClient | ApifyClientAsync) -> None: """Test updating a run's status message.""" # Run actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: # Update run status message @@ -238,13 +238,13 @@ async def test_run_update(client: ApifyClient | ApifyClientAsync) -> None: async def test_run_resurrect(client: ApifyClient | ApifyClientAsync) -> None: """Test resurrecting a finished run.""" # Run actor and wait for it to finish - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None assert run.status.value == 'SUCCEEDED' - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: # Resurrect the run @@ -269,12 +269,12 @@ async def test_run_resurrect(client: ApifyClient | ApifyClientAsync) -> None: async def test_run_log(client: ApifyClient | ApifyClientAsync) -> None: """Test accessing run's log.""" # Run actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: # Get log client @@ -309,13 +309,13 @@ async def test_run_runs_client(client: ApifyClient | ApifyClientAsync) -> None: async def test_run_metamorph(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: """Test metamorphing a run into another Actor.""" # Start an actor that will run long enough to metamorph. We use hello-world and try to metamorph it into itself - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.start()) run = cast('Run', result) assert run is not None assert run.id is not None - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: # Wait a bit for the run to start properly @@ -351,13 +351,13 @@ async def test_run_metamorph(client: ApifyClient | ApifyClientAsync, *, is_async async def test_run_reboot(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: """Test rebooting a running Actor.""" # Start an actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.start()) run = cast('Run', result) assert run is not None assert run.id is not None - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: # Wait a bit and check if the run is still running @@ -395,12 +395,12 @@ async def test_run_charge(client: ApifyClient | ApifyClientAsync) -> None: be called correctly. """ # Run an actor - actor = client.actor(HELLO_WORLD_ACTOR) + actor = client.actor(actor_id=HELLO_WORLD_ACTOR) result = await maybe_await(actor.call()) run = cast('Run', result) assert run is not None - run_client = client.run(run.id) + run_client = client.run(run_id=run.id) try: # Try to charge - this will fail for non-PPE actors but tests the API call diff --git a/tests/integration/test_schedule.py b/tests/integration/test_schedule.py index 0c2bc8a0..ad91c9e9 100644 --- a/tests/integration/test_schedule.py +++ b/tests/integration/test_schedule.py @@ -26,7 +26,7 @@ async def test_schedule_create_and_get(client: ApifyClient | ApifyClientAsync) - ) ) created_schedule = cast('Schedule', result) - schedule_client = client.schedule(created_schedule.id) + schedule_client = client.schedule(schedule_id=created_schedule.id) try: assert created_schedule is not None @@ -61,7 +61,7 @@ async def test_schedule_update(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_schedule = cast('Schedule', result) - schedule_client = client.schedule(created_schedule.id) + schedule_client = client.schedule(schedule_id=created_schedule.id) try: # Update the schedule @@ -126,8 +126,8 @@ async def test_schedule_list(client: ApifyClient | ApifyClientAsync) -> None: assert created_1.id in schedule_ids assert created_2.id in schedule_ids finally: - await maybe_await(client.schedule(created_1.id).delete()) - await maybe_await(client.schedule(created_2.id).delete()) + await maybe_await(client.schedule(schedule_id=created_1.id).delete()) + await maybe_await(client.schedule(schedule_id=created_2.id).delete()) async def test_schedule_delete(client: ApifyClient | ApifyClientAsync) -> None: @@ -144,7 +144,7 @@ async def test_schedule_delete(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_schedule = cast('Schedule', result) - schedule_client = client.schedule(created_schedule.id) + schedule_client = client.schedule(schedule_id=created_schedule.id) # Delete schedule await maybe_await(schedule_client.delete()) @@ -168,7 +168,7 @@ async def test_schedule_get_log(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_schedule = cast('Schedule', result) - schedule_client = client.schedule(created_schedule.id) + schedule_client = client.schedule(schedule_id=created_schedule.id) try: # Get schedule log - new schedule has no log entries but the method should work diff --git a/tests/integration/test_task.py b/tests/integration/test_task.py index 055d4a01..1fc07b7b 100644 --- a/tests/integration/test_task.py +++ b/tests/integration/test_task.py @@ -20,7 +20,7 @@ async def test_task_create_and_get(client: ApifyClient | ApifyClientAsync) -> No task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None actor_id = actor.id @@ -33,7 +33,7 @@ async def test_task_create_and_get(client: ApifyClient | ApifyClientAsync) -> No ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: assert created_task is not None @@ -57,7 +57,7 @@ async def test_task_update(client: ApifyClient | ApifyClientAsync) -> None: new_name = get_random_resource_name('task-updated') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -69,7 +69,7 @@ async def test_task_update(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: # Update the task @@ -98,7 +98,7 @@ async def test_task_list(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -122,7 +122,7 @@ async def test_task_list(client: ApifyClient | ApifyClientAsync) -> None: task_ids = [t.id for t in tasks_page.items] assert created_task.id in task_ids finally: - await maybe_await(client.task(created_task.id).delete()) + await maybe_await(client.task(task_id=created_task.id).delete()) async def test_task_get_input(client: ApifyClient | ApifyClientAsync) -> None: @@ -131,7 +131,7 @@ async def test_task_get_input(client: ApifyClient | ApifyClientAsync) -> None: test_input = {'message': 'Hello from test'} # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -144,7 +144,7 @@ async def test_task_get_input(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: # Get input @@ -168,7 +168,7 @@ async def test_task_start(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -180,7 +180,7 @@ async def test_task_start(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: # Start the task @@ -191,13 +191,13 @@ async def test_task_start(client: ApifyClient | ApifyClientAsync) -> None: assert run.act_id == actor.id # Wait for the run to finish - result = await maybe_await(client.run(run.id).wait_for_finish()) + result = await maybe_await(client.run(run_id=run.id).wait_for_finish()) finished_run = cast('Run', result) assert finished_run is not None assert finished_run.status.value == 'SUCCEEDED' # Cleanup run - await maybe_await(client.run(run.id).delete()) + await maybe_await(client.run(run_id=run.id).delete()) finally: await maybe_await(task_client.delete()) @@ -207,7 +207,7 @@ async def test_task_call(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -219,7 +219,7 @@ async def test_task_call(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: # Call the task (waits for finish) @@ -230,7 +230,7 @@ async def test_task_call(client: ApifyClient | ApifyClientAsync) -> None: assert run.status.value == 'SUCCEEDED' # Cleanup run - await maybe_await(client.run(run.id).delete()) + await maybe_await(client.run(run_id=run.id).delete()) finally: await maybe_await(task_client.delete()) @@ -240,7 +240,7 @@ async def test_task_delete(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -252,7 +252,7 @@ async def test_task_delete(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) # Delete task await maybe_await(task_client.delete()) @@ -267,7 +267,7 @@ async def test_task_runs(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -279,7 +279,7 @@ async def test_task_runs(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: # Run the task @@ -296,7 +296,7 @@ async def test_task_runs(client: ApifyClient | ApifyClientAsync) -> None: assert len(runs_page.items) >= 1 # Cleanup run - await maybe_await(client.run(run.id).delete()) + await maybe_await(client.run(run_id=run.id).delete()) finally: # Cleanup task @@ -308,7 +308,7 @@ async def test_task_last_run(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -320,7 +320,7 @@ async def test_task_last_run(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: # Run the task @@ -336,7 +336,7 @@ async def test_task_last_run(client: ApifyClient | ApifyClientAsync) -> None: assert last_run.id == run.id # Cleanup run - await maybe_await(client.run(run.id).delete()) + await maybe_await(client.run(run_id=run.id).delete()) finally: # Cleanup task @@ -348,7 +348,7 @@ async def test_task_webhooks(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + result = await maybe_await(client.actor(actor_id=HELLO_WORLD_ACTOR).get()) actor = cast('Actor', result) assert actor is not None @@ -360,7 +360,7 @@ async def test_task_webhooks(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_task = cast('Task', result) - task_client = client.task(created_task.id) + task_client = client.task(task_id=created_task.id) try: # Get webhooks client diff --git a/tests/integration/test_webhook.py b/tests/integration/test_webhook.py index 5fbb92ac..62e47e23 100644 --- a/tests/integration/test_webhook.py +++ b/tests/integration/test_webhook.py @@ -26,7 +26,9 @@ async def _get_finished_run_id(client: ApifyClient | ApifyClientAsync) -> str: Using a finished run's ID for webhook conditions ensures the webhook will never actually fire, since a completed run won't emit new events. """ - runs_page = await maybe_await(client.actor(HELLO_WORLD_ACTOR).runs().list(limit=1, status=ActorJobStatus.SUCCEEDED)) + runs_page = await maybe_await( + client.actor(actor_id=HELLO_WORLD_ACTOR).runs().list(limit=1, status=ActorJobStatus.SUCCEEDED) + ) assert runs_page is not None assert len(runs_page.items) > 0, 'No completed runs found for hello-world actor' run = cast('Run', runs_page.items[0]) @@ -68,7 +70,7 @@ async def test_webhook_create_and_get(client: ApifyClient | ApifyClientAsync) -> ) ) created_webhook = cast('Webhook', result) - webhook_client = client.webhook(created_webhook.id) + webhook_client = client.webhook(webhook_id=created_webhook.id) try: assert created_webhook is not None @@ -97,7 +99,7 @@ async def test_webhook_update(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_webhook = cast('Webhook', result) - webhook_client = client.webhook(created_webhook.id) + webhook_client = client.webhook(webhook_id=created_webhook.id) try: # Update webhook @@ -127,7 +129,7 @@ async def test_webhook_test(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_webhook = cast('Webhook', result) - webhook_client = client.webhook(created_webhook.id) + webhook_client = client.webhook(webhook_id=created_webhook.id) try: # Test webhook (creates a dispatch with dummy payload) @@ -153,7 +155,7 @@ async def test_webhook_dispatches(client: ApifyClient | ApifyClientAsync) -> Non ) ) created_webhook = cast('Webhook', result) - webhook_client = client.webhook(created_webhook.id) + webhook_client = client.webhook(webhook_id=created_webhook.id) try: # Test webhook to create a dispatch @@ -183,7 +185,7 @@ async def test_webhook_delete(client: ApifyClient | ApifyClientAsync) -> None: ) ) created_webhook = cast('Webhook', result) - webhook_client = client.webhook(created_webhook.id) + webhook_client = client.webhook(webhook_id=created_webhook.id) # Delete webhook await maybe_await(webhook_client.delete()) diff --git a/tests/integration/test_webhook_dispatch.py b/tests/integration/test_webhook_dispatch.py index 81840094..ced37e5d 100644 --- a/tests/integration/test_webhook_dispatch.py +++ b/tests/integration/test_webhook_dispatch.py @@ -33,12 +33,12 @@ async def test_webhook_dispatch_get(client: ApifyClient | ApifyClientAsync) -> N if dispatches_page.items: # If there are dispatches, test the get method dispatch_id = dispatches_page.items[0].id - result = await maybe_await(client.webhook_dispatch(dispatch_id).get()) + result = await maybe_await(client.webhook_dispatch(webhook_dispatch_id=dispatch_id).get()) dispatch = cast('WebhookDispatch', result) assert dispatch is not None assert dispatch.id == dispatch_id else: # If no dispatches, test that get returns None for non-existent ID - dispatch = await maybe_await(client.webhook_dispatch('non-existent-id').get()) + dispatch = await maybe_await(client.webhook_dispatch(webhook_dispatch_id='non-existent-id').get()) assert dispatch is None diff --git a/tests/unit/test_actor_start_params.py b/tests/unit/test_actor_start_params.py index 6dd5a4dd..f538f524 100644 --- a/tests/unit/test_actor_start_params.py +++ b/tests/unit/test_actor_start_params.py @@ -73,7 +73,7 @@ def capture_request(request: Request) -> Response: client = ApifyClient(token='test_token', api_url=api_url) # Call start with timeout (timedelta) parameter - client.actor(_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=300)) + client.actor(actor_id=_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=300)) # Verify the request was made with correct timeout parameter assert len(captured_requests) == 1 @@ -106,7 +106,7 @@ def capture_request(request: Request) -> Response: client = ApifyClientAsync(token='test_token', api_url=api_url) # Call start with timeout (timedelta) parameter - await client.actor(_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=300)) + await client.actor(actor_id=_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=300)) # Verify the request was made with correct timeout parameter assert len(captured_requests) == 1 @@ -139,7 +139,7 @@ def capture_request(request: Request) -> Response: client = ApifyClient(token='test_token', api_url=api_url) # Call start without timeout_secs - client.actor(_MOCKED_ACTOR_ID).start() + client.actor(actor_id=_MOCKED_ACTOR_ID).start() # Verify timeout parameter is not present assert len(captured_requests) == 1 @@ -169,7 +169,7 @@ def capture_request(request: Request) -> Response: client = ApifyClientAsync(token='test_token', api_url=api_url) # Call start without timeout_secs - await client.actor(_MOCKED_ACTOR_ID).start() + await client.actor(actor_id=_MOCKED_ACTOR_ID).start() # Verify timeout parameter is not present assert len(captured_requests) == 1 @@ -199,7 +199,7 @@ def capture_request(request: Request) -> Response: api_url = httpserver.url_for('/').removesuffix('/') client = ApifyClient(token='test_token', api_url=api_url) - client.actor(_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=timeout_value)) + client.actor(actor_id=_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=timeout_value)) assert len(captured_requests) == 1 assert captured_requests[0].args['timeout'] == str(timeout_value) @@ -226,7 +226,7 @@ def capture_request(request: Request) -> Response: api_url = httpserver.url_for('/').removesuffix('/') client = ApifyClientAsync(token='test_token', api_url=api_url) - await client.actor(_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=timeout_value)) + await client.actor(actor_id=_MOCKED_ACTOR_ID).start(timeout=timedelta(seconds=timeout_value)) assert len(captured_requests) == 1 assert captured_requests[0].args['timeout'] == str(timeout_value) diff --git a/tests/unit/test_dataset_list_items.py b/tests/unit/test_dataset_list_items.py index 19831a15..7970bc19 100644 --- a/tests/unit/test_dataset_list_items.py +++ b/tests/unit/test_dataset_list_items.py @@ -45,7 +45,7 @@ def test_list_items_desc_false_sync(httpserver: HTTPServer, desc_header_value: s api_url = httpserver.url_for('/').removesuffix('/') client = ApifyClient(token='test-token', api_url=api_url) - result = client.dataset(DATASET_ID).list_items() + result = client.dataset(dataset_id=DATASET_ID).list_items() assert result.desc is False @@ -58,7 +58,7 @@ def test_list_items_desc_true_sync(httpserver: HTTPServer, desc_header_value: st api_url = httpserver.url_for('/').removesuffix('/') client = ApifyClient(token='test-token', api_url=api_url) - result = client.dataset(DATASET_ID).list_items() + result = client.dataset(dataset_id=DATASET_ID).list_items() assert result.desc is True @@ -71,7 +71,7 @@ async def test_list_items_desc_false_async(httpserver: HTTPServer, desc_header_v api_url = httpserver.url_for('/').removesuffix('/') client = ApifyClientAsync(token='test-token', api_url=api_url) - result = await client.dataset(DATASET_ID).list_items() + result = await client.dataset(dataset_id=DATASET_ID).list_items() assert result.desc is False @@ -84,6 +84,6 @@ async def test_list_items_desc_true_async(httpserver: HTTPServer, desc_header_va api_url = httpserver.url_for('/').removesuffix('/') client = ApifyClientAsync(token='test-token', api_url=api_url) - result = await client.dataset(DATASET_ID).list_items() + result = await client.dataset(dataset_id=DATASET_ID).list_items() assert result.desc is True diff --git a/tests/unit/test_http_clients.py b/tests/unit/test_http_clients.py index 2f60c7f5..1b982772 100644 --- a/tests/unit/test_http_clients.py +++ b/tests/unit/test_http_clients.py @@ -44,7 +44,7 @@ def bails_on_third_attempt(stop_retrying: Callable, attempt: int) -> Any: # Returns the correct result after the correct time (should take 100 + 200 + 400 + 800 = 1500 ms) start = time.time() result = HttpClient._retry_with_exp_backoff( - returns_on_fifth_attempt, backoff_base=timedelta(milliseconds=100), backoff_factor=2, random_factor=0 + func=returns_on_fifth_attempt, backoff_base=timedelta(milliseconds=100), backoff_factor=2, random_factor=0 ) elapsed_time_seconds = time.time() - start assert result == 'SUCCESS' @@ -56,14 +56,14 @@ def bails_on_third_attempt(stop_retrying: Callable, attempt: int) -> Any: attempt_counter = 0 with pytest.raises(RetryableError): HttpClient._retry_with_exp_backoff( - returns_on_fifth_attempt, max_retries=3, backoff_base=timedelta(milliseconds=1) + func=returns_on_fifth_attempt, max_retries=3, backoff_base=timedelta(milliseconds=1) ) assert attempt_counter == 4 # Bails when the bail function is called attempt_counter = 0 with pytest.raises(NonRetryableError): - HttpClient._retry_with_exp_backoff(bails_on_third_attempt, backoff_base=timedelta(milliseconds=1)) + HttpClient._retry_with_exp_backoff(func=bails_on_third_attempt, backoff_base=timedelta(milliseconds=1)) assert attempt_counter == 3 @@ -97,7 +97,7 @@ async def bails_on_third_attempt(stop_retrying: Callable, attempt: int) -> Any: # Returns the correct result after the correct time (should take 100 + 200 + 400 + 800 = 1500 ms) start = time.time() result = await HttpClientAsync._retry_with_exp_backoff( - returns_on_fifth_attempt, backoff_base=timedelta(milliseconds=100), backoff_factor=2, random_factor=0 + func=returns_on_fifth_attempt, backoff_base=timedelta(milliseconds=100), backoff_factor=2, random_factor=0 ) elapsed_time_seconds = time.time() - start assert result == 'SUCCESS' @@ -109,14 +109,16 @@ async def bails_on_third_attempt(stop_retrying: Callable, attempt: int) -> Any: attempt_counter = 0 with pytest.raises(RetryableError): await HttpClientAsync._retry_with_exp_backoff( - returns_on_fifth_attempt, max_retries=3, backoff_base=timedelta(milliseconds=1) + func=returns_on_fifth_attempt, max_retries=3, backoff_base=timedelta(milliseconds=1) ) assert attempt_counter == 4 # Bails when the bail function is called attempt_counter = 0 with pytest.raises(NonRetryableError): - await HttpClientAsync._retry_with_exp_backoff(bails_on_third_attempt, backoff_base=timedelta(milliseconds=1)) + await HttpClientAsync._retry_with_exp_backoff( + func=bails_on_third_attempt, backoff_base=timedelta(milliseconds=1) + ) assert attempt_counter == 3 @@ -163,31 +165,31 @@ def test_http_client_async_creates_async_impit_client() -> None: def test_parse_params_none() -> None: """Test _parse_params with None input.""" - assert BaseHttpClient._parse_params(None) is None + assert BaseHttpClient._parse_params(params=None) is None def test_parse_params_boolean() -> None: """Test _parse_params converts booleans to integers.""" - result = BaseHttpClient._parse_params({'flag': True, 'disabled': False}) + result = BaseHttpClient._parse_params(params={'flag': True, 'disabled': False}) assert result == {'flag': 1, 'disabled': 0} def test_parse_params_list() -> None: """Test _parse_params converts lists to comma-separated strings.""" - result = BaseHttpClient._parse_params({'ids': ['id1', 'id2', 'id3']}) + result = BaseHttpClient._parse_params(params={'ids': ['id1', 'id2', 'id3']}) assert result == {'ids': 'id1,id2,id3'} def test_parse_params_datetime() -> None: """Test _parse_params converts datetime to Zulu format.""" dt = datetime(2024, 1, 15, 10, 30, 45, 123000, tzinfo=UTC) - result = BaseHttpClient._parse_params({'created_at': dt}) + result = BaseHttpClient._parse_params(params={'created_at': dt}) assert result == {'created_at': '2024-01-15T10:30:45.123Z'} def test_parse_params_none_values_filtered() -> None: """Test _parse_params filters out None values.""" - result = BaseHttpClient._parse_params({'a': 1, 'b': None, 'c': 'value'}) + result = BaseHttpClient._parse_params(params={'a': 1, 'b': None, 'c': 'value'}) assert result == {'a': 1, 'c': 'value'} @@ -195,7 +197,7 @@ def test_parse_params_mixed() -> None: """Test _parse_params with mixed types.""" dt = datetime(2024, 1, 15, 10, 30, 45, 123000, tzinfo=UTC) result = BaseHttpClient._parse_params( - { + params={ 'limit': 10, 'offset': 0, 'flag': True, @@ -218,15 +220,15 @@ def test_parse_params_mixed() -> None: def test_is_retryable_error() -> None: """Test _is_retryable_error correctly identifies retryable errors.""" mock_response = Mock() - assert BaseHttpClient._is_retryable_error(InvalidResponseBodyError(mock_response)) - assert BaseHttpClient._is_retryable_error(impit.NetworkError('test')) - assert BaseHttpClient._is_retryable_error(impit.TimeoutException('test')) - assert BaseHttpClient._is_retryable_error(impit.RemoteProtocolError('test')) + assert BaseHttpClient._is_retryable_error(exc=InvalidResponseBodyError(response=mock_response)) + assert BaseHttpClient._is_retryable_error(exc=impit.NetworkError('test')) + assert BaseHttpClient._is_retryable_error(exc=impit.TimeoutException('test')) + assert BaseHttpClient._is_retryable_error(exc=impit.RemoteProtocolError('test')) # Non-retryable errors - assert not BaseHttpClient._is_retryable_error(ValueError('test')) - assert not BaseHttpClient._is_retryable_error(RuntimeError('test')) - assert not BaseHttpClient._is_retryable_error(Exception('test')) + assert not BaseHttpClient._is_retryable_error(exc=ValueError('test')) + assert not BaseHttpClient._is_retryable_error(exc=RuntimeError('test')) + assert not BaseHttpClient._is_retryable_error(exc=Exception('test')) def test_prepare_request_call_basic() -> None: @@ -368,7 +370,7 @@ def test_build_url_with_params_none() -> None: """Test _build_url_with_params with None params.""" client = BaseHttpClient() - url = client._build_url_with_params('https://api.test.com/endpoint') + url = client._build_url_with_params(url='https://api.test.com/endpoint') assert url == 'https://api.test.com/endpoint' @@ -376,7 +378,7 @@ def test_build_url_with_params_simple() -> None: """Test _build_url_with_params with simple params.""" client = BaseHttpClient() - url = client._build_url_with_params('https://api.test.com/endpoint', {'key': 'value', 'limit': 10}) + url = client._build_url_with_params(url='https://api.test.com/endpoint', params={'key': 'value', 'limit': 10}) assert 'key=value' in url assert 'limit=10' in url assert url.startswith('https://api.test.com/endpoint?') @@ -386,7 +388,7 @@ def test_build_url_with_params_list() -> None: """Test _build_url_with_params with list values.""" client = BaseHttpClient() - url = client._build_url_with_params('https://api.test.com/endpoint', {'tags': ['tag1', 'tag2', 'tag3']}) + url = client._build_url_with_params(url='https://api.test.com/endpoint', params={'tags': ['tag1', 'tag2', 'tag3']}) assert 'tags=tag1' in url assert 'tags=tag2' in url assert 'tags=tag3' in url @@ -397,7 +399,7 @@ def test_build_url_with_params_mixed() -> None: client = BaseHttpClient() url = client._build_url_with_params( - 'https://api.test.com/endpoint', {'limit': 10, 'tags': ['a', 'b'], 'name': 'test'} + url='https://api.test.com/endpoint', params={'limit': 10, 'tags': ['a', 'b'], 'name': 'test'} ) assert 'limit=10' in url assert 'tags=a' in url diff --git a/tests/unit/test_statistics.py b/tests/unit/test_statistics.py index 69fbc3c4..17799ea2 100644 --- a/tests/unit/test_statistics.py +++ b/tests/unit/test_statistics.py @@ -18,7 +18,7 @@ def test_add_rate_limit_error(attempts: list[int], expected_errors: list[int]) - """Test that add_rate_limit_error correctly tracks errors for different attempt sequences.""" stats = ClientStatistics() for attempt in attempts: - stats.add_rate_limit_error(attempt) + stats.add_rate_limit_error(attempt=attempt) assert stats.rate_limit_errors == expected_errors @@ -26,7 +26,7 @@ def test_add_rate_limit_error_invalid_attempt() -> None: """Test that add_rate_limit_error raises ValueError for invalid attempt.""" stats = ClientStatistics() with pytest.raises(ValueError, match=r'Attempt must be greater than 0'): - stats.add_rate_limit_error(0) + stats.add_rate_limit_error(attempt=0) def test_statistics_initial_state() -> None: @@ -41,7 +41,7 @@ def test_add_rate_limit_error_type_validation() -> None: """Test type validation in add_rate_limit_error.""" stats = ClientStatistics() with pytest.raises(TypeError): - stats.add_rate_limit_error('1') # ty: ignore[invalid-argument-type] + stats.add_rate_limit_error(attempt='1') # ty: ignore[invalid-argument-type] def test_statistics_calls_and_requests_increment() -> None: @@ -65,18 +65,18 @@ def test_rate_limit_errors_accumulation() -> None: stats = ClientStatistics() # Add errors to different attempts - stats.add_rate_limit_error(1) - stats.add_rate_limit_error(2) - stats.add_rate_limit_error(3) + stats.add_rate_limit_error(attempt=1) + stats.add_rate_limit_error(attempt=2) + stats.add_rate_limit_error(attempt=3) assert stats.rate_limit_errors[0] == 1 assert stats.rate_limit_errors[1] == 1 assert stats.rate_limit_errors[2] == 1 # Add more errors to same attempts - stats.add_rate_limit_error(1) - stats.add_rate_limit_error(1) - stats.add_rate_limit_error(2) + stats.add_rate_limit_error(attempt=1) + stats.add_rate_limit_error(attempt=1) + stats.add_rate_limit_error(attempt=2) assert stats.rate_limit_errors[0] == 3 assert stats.rate_limit_errors[1] == 2 @@ -91,7 +91,7 @@ def test_rate_limit_errors_dict_behavior() -> None: assert stats.rate_limit_errors.get(999, 0) == 0 # Adding to high attempt numbers should work - stats.add_rate_limit_error(100) + stats.add_rate_limit_error(attempt=100) assert stats.rate_limit_errors[99] == 1 @@ -102,7 +102,7 @@ def test_statistics_independent_instances() -> None: stats1.calls = 10 stats1.requests = 20 - stats1.add_rate_limit_error(1) + stats1.add_rate_limit_error(attempt=1) assert stats2.calls == 0 assert stats2.requests == 0 @@ -113,8 +113,8 @@ def test_add_rate_limit_error_large_attempt() -> None: """Test add_rate_limit_error with large attempt numbers.""" stats = ClientStatistics() - stats.add_rate_limit_error(1000) + stats.add_rate_limit_error(attempt=1000) assert stats.rate_limit_errors[999] == 1 - stats.add_rate_limit_error(10000) + stats.add_rate_limit_error(attempt=10000) assert stats.rate_limit_errors[9999] == 1 diff --git a/tests/unit/test_url_generation.py b/tests/unit/test_url_generation.py index 0f142678..b557d7d4 100644 --- a/tests/unit/test_url_generation.py +++ b/tests/unit/test_url_generation.py @@ -96,7 +96,7 @@ def _get_mocked_kvs_response(signing_key: str | None = None) -> Mock: def test_dataset_public_url_sync(api_url: str, api_public_url: str | None) -> None: """Test public URL generation for datasets with sync client.""" client = ApifyClient(token='dummy-token', api_url=api_url, api_public_url=api_public_url) - dataset = client.dataset('someID') + dataset = client.dataset(dataset_id='someID') mock_response = Mock() mock_response.json.return_value = json.loads(MOCKED_DATASET_RESPONSE) @@ -114,7 +114,7 @@ def test_dataset_public_url_sync(api_url: str, api_public_url: str | None) -> No async def test_dataset_public_url_async(api_url: str, api_public_url: str | None) -> None: """Test public URL generation for datasets with async client.""" client = ApifyClientAsync(token='dummy-token', api_url=api_url, api_public_url=api_public_url) - dataset = client.dataset('someID') + dataset = client.dataset(dataset_id='someID') mock_response = Mock() mock_response.json.return_value = json.loads(MOCKED_DATASET_RESPONSE) @@ -138,7 +138,7 @@ async def test_dataset_public_url_async(api_url: str, api_public_url: str | None def test_kvs_public_url_sync(api_url: str, api_public_url: str | None, signing_key: str | None) -> None: """Test public URL generation for key-value stores with sync client.""" client = ApifyClient(token='dummy-token', api_url=api_url, api_public_url=api_public_url) - kvs = client.key_value_store(MOCKED_KVS_ID) + kvs = client.key_value_store(key_value_store_id=MOCKED_KVS_ID) with mock.patch.object(client._http_client, 'call', return_value=_get_mocked_kvs_response(signing_key=signing_key)): public_url = kvs.create_keys_public_url() @@ -162,7 +162,7 @@ def test_kvs_public_url_sync(api_url: str, api_public_url: str | None, signing_k async def test_kvs_public_url_async(api_url: str, api_public_url: str | None, signing_key: str | None) -> None: """Test public URL generation for key-value stores with async client.""" client = ApifyClientAsync(token='dummy-token', api_url=api_url, api_public_url=api_public_url) - kvs = client.key_value_store(MOCKED_KVS_ID) + kvs = client.key_value_store(key_value_store_id=MOCKED_KVS_ID) with mock.patch.object( client._http_client, @@ -192,12 +192,14 @@ def test_kvs_record_public_url_sync(api_url: str, api_public_url: str | None, si """Test record public URL generation for key-value stores with sync client.""" client = ApifyClient(token='dummy-token', api_url=api_url, api_public_url=api_public_url) key = 'some_key' - kvs = client.key_value_store(MOCKED_KVS_ID) + kvs = client.key_value_store(key_value_store_id=MOCKED_KVS_ID) with mock.patch.object(client._http_client, 'call', return_value=_get_mocked_kvs_response(signing_key=signing_key)): public_url = kvs.get_record_public_url(key=key) - expected_signature = f'?signature={create_hmac_signature(signing_key, key)}' if signing_key else '' + expected_signature = ( + f'?signature={create_hmac_signature(secret_key=signing_key, message=key)}' if signing_key else '' + ) assert public_url == ( f'{(api_public_url or DEFAULT_API_URL).strip("/")}/v2/key-value-stores/{MOCKED_KVS_ID}/' f'records/{key}{expected_signature}' @@ -210,12 +212,14 @@ async def test_kvs_record_public_url_async(api_url: str, api_public_url: str | N """Test record public URL generation for key-value stores with async client.""" client = ApifyClientAsync(token='dummy-token', api_url=api_url, api_public_url=api_public_url) key = 'some_key' - kvs = client.key_value_store(MOCKED_KVS_ID) + kvs = client.key_value_store(key_value_store_id=MOCKED_KVS_ID) with mock.patch.object(client._http_client, 'call', return_value=_get_mocked_kvs_response(signing_key=signing_key)): public_url = await kvs.get_record_public_url(key=key) - expected_signature = f'?signature={create_hmac_signature(signing_key, key)}' if signing_key else '' + expected_signature = ( + f'?signature={create_hmac_signature(secret_key=signing_key, message=key)}' if signing_key else '' + ) assert public_url == ( f'{(api_public_url or DEFAULT_API_URL).strip("/")}/v2/key-value-stores/{MOCKED_KVS_ID}/' f'records/{key}{expected_signature}' diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 4478b425..c16eae81 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -26,17 +26,17 @@ def test_to_safe_id() -> None: - assert to_safe_id('abc') == 'abc' - assert to_safe_id('abc/def') == 'abc~def' - assert to_safe_id('abc~def') == 'abc~def' - assert to_safe_id('user/resource/extra') == 'user~resource~extra' + assert to_safe_id(id='abc') == 'abc' + assert to_safe_id(id='abc/def') == 'abc~def' + assert to_safe_id(id='abc~def') == 'abc~def' + assert to_safe_id(id='user/resource/extra') == 'user~resource~extra' def test_encode_webhook_list_to_base64() -> None: - assert encode_webhook_list_to_base64([]) == 'W10=' + assert encode_webhook_list_to_base64(webhooks=[]) == 'W10=' assert ( encode_webhook_list_to_base64( - [ + webhooks=[ { 'event_types': [WebhookEventType.ACTOR_RUN_CREATED], 'request_url': 'https://example.com/run-created', @@ -55,7 +55,7 @@ def test_encode_webhook_list_to_base64() -> None: @pytest.mark.parametrize( 'exc', [ - InvalidResponseBodyError(impit.Response(status_code=200)), + InvalidResponseBodyError(response=impit.Response(status_code=200)), impit.HTTPError('generic http error'), impit.NetworkError('network error'), impit.TimeoutException('timeout'), @@ -67,7 +67,7 @@ def test_encode_webhook_list_to_base64() -> None: ], ) def test__is_retryable_error(exc: Exception) -> None: - assert is_retryable_error(exc) is True + assert is_retryable_error(exc=exc) is True @pytest.mark.parametrize( @@ -79,7 +79,7 @@ def test__is_retryable_error(exc: Exception) -> None: ], ) def test__is_not_retryable_error(exc: Exception) -> None: - assert is_retryable_error(exc) is False + assert is_retryable_error(exc=exc) is False @pytest.mark.parametrize( @@ -97,14 +97,14 @@ def test_catch_not_found_or_throw(status_code: HTTPStatus, error_type: str, *, s mock_response.status_code = status_code mock_response.text = f'{{"error":{{"type":"{error_type}"}}}}' - error = ApifyApiError(mock_response, 1) + error = ApifyApiError(response=mock_response, attempt=1) error.type = error_type if should_suppress: - catch_not_found_or_throw(error) + catch_not_found_or_throw(exc=error) else: with pytest.raises(ApifyApiError): - catch_not_found_or_throw(error) + catch_not_found_or_throw(exc=error) @pytest.mark.parametrize( @@ -123,12 +123,12 @@ def test_catch_not_found_or_throw(status_code: HTTPStatus, error_type: str, *, s ) def test_filter_none_values(input_dict: dict, *, remove_empty_dicts: bool, expected: dict) -> None: """Test filtering None values from dictionaries.""" - assert filter_none_values(input_dict, remove_empty_dicts=remove_empty_dicts) == expected + assert filter_none_values(data=input_dict, remove_empty_dicts=remove_empty_dicts) == expected def test_encode_key_value_store_record_value_dict() -> None: """Test that dictionaries are encoded as JSON.""" - value, content_type = encode_key_value_store_record_value({'key': 'value'}) + value, content_type = encode_key_value_store_record_value(value={'key': 'value'}) assert b'"key"' in value assert b'"value"' in value assert content_type == 'application/json; charset=utf-8' @@ -147,9 +147,9 @@ def test_encode_key_value_store_record_value( ) -> None: """Test encoding of key-value store record values.""" if input_content_type is not None: - value, content_type = encode_key_value_store_record_value(input_value, input_content_type) + value, content_type = encode_key_value_store_record_value(value=input_value, content_type=input_content_type) else: - value, content_type = encode_key_value_store_record_value(input_value) + value, content_type = encode_key_value_store_record_value(value=input_value) assert value == expected_value assert content_type == expected_content_type @@ -157,7 +157,7 @@ def test_encode_key_value_store_record_value( def test_encode_key_value_store_record_value_bytesio() -> None: """Test that BytesIO is encoded as octet-stream.""" buffer = io.BytesIO(b'buffer data') - value, content_type = encode_key_value_store_record_value(buffer) + value, content_type = encode_key_value_store_record_value(value=buffer) assert value == buffer assert content_type == 'application/octet-stream' @@ -179,14 +179,14 @@ class _TestEnum(Enum): ) def test_enum_to_value(input_value: _TestEnum | str | int | None, expected: str | int | None) -> None: """Test enum to value conversion.""" - assert enum_to_value(input_value) == expected + assert enum_to_value(value=input_value) == expected def test_response_to_dict() -> None: """Test parsing response as dictionary.""" mock_response = Mock() mock_response.json.return_value = {'key': 'value'} - assert response_to_dict(mock_response) == {'key': 'value'} + assert response_to_dict(response=mock_response) == {'key': 'value'} @pytest.mark.parametrize( @@ -201,21 +201,21 @@ def test_response_to_dict_raises_for_non_dict(json_return_value: object) -> None mock_response = Mock() mock_response.json.return_value = json_return_value with pytest.raises(ValueError, match='The response is not a dictionary'): - response_to_dict(mock_response) + response_to_dict(response=mock_response) def test_response_to_list() -> None: """Test parsing response as list.""" mock_response = Mock() mock_response.json.return_value = ['item1', 'item2'] - assert response_to_list(mock_response) == ['item1', 'item2'] + assert response_to_list(response=mock_response) == ['item1', 'item2'] def test_response_to_list_wraps_dict_in_list() -> None: """Test that response_to_list wraps a dict response in a list.""" mock_response = Mock() mock_response.json.return_value = {'dict': 'response'} - assert response_to_list(mock_response) == [{'dict': 'response'}] + assert response_to_list(response=mock_response) == [{'dict': 'response'}] def test_response_to_list_raises_for_non_list() -> None: @@ -223,7 +223,7 @@ def test_response_to_list_raises_for_non_list() -> None: mock_response = Mock() mock_response.json.return_value = 'string' with pytest.raises(ValueError, match='The response is not a list'): - response_to_list(mock_response) + response_to_list(response=mock_response) @pytest.mark.parametrize( @@ -243,39 +243,39 @@ def test_response_to_list_raises_for_non_list() -> None: ) def test_encode_base62(input_value: int, expected: str) -> None: """Test base62 encoding.""" - assert encode_base62(input_value) == expected + assert encode_base62(num=input_value) == expected def test_create_hmac_signature() -> None: """Test HMAC signature creation.""" # Test with known values - signature = create_hmac_signature('secret_key', 'test_message') + signature = create_hmac_signature(secret_key='secret_key', message='test_message') assert isinstance(signature, str) assert len(signature) > 0 # Same inputs should produce same output - signature2 = create_hmac_signature('secret_key', 'test_message') + signature2 = create_hmac_signature(secret_key='secret_key', message='test_message') assert signature == signature2 # Different inputs should produce different output - signature3 = create_hmac_signature('different_key', 'test_message') + signature3 = create_hmac_signature(secret_key='different_key', message='test_message') assert signature != signature3 - signature4 = create_hmac_signature('secret_key', 'different_message') + signature4 = create_hmac_signature(secret_key='secret_key', message='different_message') assert signature != signature4 def test_create_storage_signature() -> None: """Test storage signature creation.""" # Non-expiring signature - signature = create_storage_content_signature('resource_123', 'secret_key') + signature = create_storage_content_signature(resource_id='resource_123', url_signing_secret_key='secret_key') assert isinstance(signature, str) assert len(signature) > 0 # Expiring signature signature_expiring = create_storage_content_signature( - 'resource_123', - 'secret_key', + resource_id='resource_123', + url_signing_secret_key='secret_key', expires_in=timedelta(seconds=60), ) @@ -284,13 +284,15 @@ def test_create_storage_signature() -> None: assert signature != signature_expiring # Different because of expiration # Different resource IDs produce different signatures - signature2 = create_storage_content_signature('resource_456', 'secret_key') + signature2 = create_storage_content_signature(resource_id='resource_456', url_signing_secret_key='secret_key') assert signature != signature2 # Same inputs should produce same output (for non-expiring) - signature3 = create_storage_content_signature('resource_123', 'secret_key') + signature3 = create_storage_content_signature(resource_id='resource_123', url_signing_secret_key='secret_key') assert signature == signature3 # Test with version parameter - signature_v1 = create_storage_content_signature('resource_123', 'secret_key', version=1) + signature_v1 = create_storage_content_signature( + resource_id='resource_123', url_signing_secret_key='secret_key', version=1 + ) assert signature != signature_v1 diff --git a/website/src/pages/home_page_example.py b/website/src/pages/home_page_example.py index 6b8a3fc3..6198e01b 100644 --- a/website/src/pages/home_page_example.py +++ b/website/src/pages/home_page_example.py @@ -2,10 +2,10 @@ async def main() -> None: - apify_client = ApifyClientAsync('MY-APIFY-TOKEN') + apify_client = ApifyClientAsync(token='MY-APIFY-TOKEN') # Start an Actor and wait for it to finish. - actor_client = apify_client.actor('john-doe/my-cool-actor') + actor_client = apify_client.actor(actor_id='john-doe/my-cool-actor') call_result = await actor_client.call() if call_result is None: @@ -13,6 +13,6 @@ async def main() -> None: return # Fetch results from the Actor run's default dataset. - dataset_client = apify_client.dataset(call_result.default_dataset_id) + dataset_client = apify_client.dataset(dataset_id=call_result.default_dataset_id) list_items_result = await dataset_client.list_items() print(f'Dataset: {list_items_result}')