Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,23 @@ print(results["search_metadata"]["status"])

If the search is still processing, retrieve it again later. See the [async search guide](https://serpapi-python.readthedocs.io/en/latest/user_guide/async-search-archive.html) for polling with HTTP timeouts and a deadline.

### Batch asynchronous searches

To run many searches at once, `async_search()` submits the whole batch with `{"async": True}` and polls the Search Archive API until every search finishes:

```python
queries = ["burly", "creator", "doubtful", "minecraft"]
results = client.async_search(queries=queries, engine="youtube", device="desktop")

for query, result in zip(queries, results):
if isinstance(result, Exception):
print(query, "failed:", result)
else:
print(query, result["search_metadata"]["status"])
```

Each item of the batch can also be a full parameter dictionary, so searches with different engines or parameters can be mixed in one call. The results come back in the same order as the input. A search that fails, or is still running when the `timeout` (300 seconds by default) expires, leaves its exception in its place instead of failing the whole batch.

## Async client

If your app uses `asyncio` on Python 3.11 or later, you can use `serpapi.AsyncClient` to search without blocking other tasks.
Expand Down
118 changes: 117 additions & 1 deletion serpapi/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
import io
import json
import os
import time
from collections.abc import Mapping

import requests

from .http import AsyncHTTPClient, HTTPClient
from .exceptions import SearchIDNotProvided
from .exceptions import SearchIDNotProvided, TimeoutError
from .models import AsyncSerpResults, SerpResults
from .utils import _response_json

Expand Down Expand Up @@ -116,6 +118,119 @@ def search_archive(self, params: dict = None, **kwargs):
r = self.request("GET", f"/searches/{ search_id }", params=params, **request_kwargs)
return SerpResults.from_http_response(r, client=self)

def async_search(self, searches=None, *, queries=None, poll_interval=1, timeout=300, **kwargs):
"""Run a batch of searches asynchronously and wait for every result.

Each search is submitted with ``{"async": True}``, then the Search
Archive API is polled until every search finishes. This is the submit,
poll and re-queue loop from the async search guide, without the
bookkeeping.

Searches are given as a list of parameter dictionaries, or as a list
of query strings with shared parameters:

.. code-block:: python

results = client.async_search(
queries=["burly", "creator", "doubtful", "minecraft"],
engine="youtube",
device="desktop",
)

A plain string in the list is shorthand for ``{"q": string}``.
Parameters passed as keyword arguments apply to every search, and a
search's own parameters take precedence over them. The ``proxies``,
``verify``, ``stream``, and ``cert`` keyword arguments are passed to
the underlying HTTP requests, as in :meth:`search`.

The returned list has one entry per search, in the same order as the
input. An entry is a ``serpapi.SerpResults`` object once its search
finishes, including searches whose final status is ``"Error"``. If a
search could not be submitted or retrieved, or is still unfinished
when ``timeout`` expires, its entry is the exception instead, so one
failed search does not lose the rest of the batch.

:param searches: A list of searches. Each item is a parameter
dictionary like the one :meth:`search` accepts, or a query string.
:param queries: A list of query strings, as an alternative to
``searches``. Combined with shared keyword parameters, such as
``engine``, this is the quickest way to run one search per query.
:param poll_interval: Seconds to wait between rounds of archive
checks. Defaults to 1.
:param timeout: Overall deadline in seconds, covering submission and
polling. Searches still unfinished at the deadline get a
``TimeoutError`` entry. Pass ``None`` to wait without a deadline.
Defaults to 300.

**Learn more**: https://serpapi.com/search-archive-api
"""
if searches is None:
searches = queries
if searches is None:
raise TypeError("async_search() requires a list of searches or queries")
if isinstance(searches, (str, Mapping)):
searches = [searches]

# These are arguments that should be passed to the underlying requests.request call.
request_kwargs = {}
for key in ["proxies", "verify", "stream", "cert"]:
if key in kwargs:
request_kwargs[key] = kwargs.pop(key)

results = [None] * len(searches)
pending = {}

for index, item in enumerate(searches):
params = {"q": item} if isinstance(item, str) else dict(item)
for key, value in kwargs.items():
params.setdefault(key, value)
params["async"] = True

try:
submitted = self.search(params, **request_kwargs)
search_id = submitted["search_metadata"]["id"]
except Exception as error: # One failed search must not sink the batch.
results[index] = error
else:
pending[index] = search_id

deadline = None if timeout is None else time.monotonic() + timeout
while pending:
if deadline is not None and time.monotonic() >= deadline:
break

for index, search_id in list(pending.items()):
try:
# Send only the search ID: reusing the search parameters
# (such as "q") makes the Search Archive API return an error.
result = self.search_archive(
{"search_id": search_id}, **request_kwargs
)
except Exception as error: # One failed search must not sink the batch.
results[index] = error
del pending[index]
continue

metadata = (
result.get("search_metadata")
if isinstance(result, Mapping)
else None
)
status = metadata.get("status") if metadata else None
if status is None or status in ("Success", "Cached", "Error"):
results[index] = result
del pending[index]

if pending:
time.sleep(poll_interval)

for index, search_id in pending.items():
results[index] = TimeoutError(
f"Search {search_id} did not finish within {timeout} seconds"
)

return results

def upload_image(self, image, **kwargs):
"""Upload an image to SerpApi's Image API.

Expand Down Expand Up @@ -422,6 +537,7 @@ async def account(self, params: dict = None, **kwargs):
search = _client.search
extract = _client.extract
search_archive = _client.search_archive
async_search = _client.async_search
upload_image = _client.upload_image
locations = _client.locations
account = _client.account
186 changes: 186 additions & 0 deletions tests/test_async_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import json

import pytest
import requests

import serpapi
from serpapi import Client
from serpapi.exceptions import HTTPError, TimeoutError


def json_response(payload, status_code=200):
response = requests.Response()
response.status_code = status_code
response._content = json.dumps(payload).encode()
response.headers["Content-Type"] = "application/json"
return response


class FakeSerpApi:
"""Answers /search and /searches/<id> requests without any network access.

Submitting a search returns a "Processing" search whose ID is derived
from its query. Each archive request for a search pops the next status
from that search's script in ``statuses``; the last status repeats.
"""

def __init__(self):
self.submit_params = []
self.archive_params = []
self.statuses = {}
self.fail_submit_for = set()

def request(self, method, url, params, headers, **kwargs):
if "/searches/" in url:
return self.archive(url.rsplit("/", 1)[-1], params)
return self.submit(params)

def submit(self, params):
self.submit_params.append(dict(params))
q = params.get("q")
if q in self.fail_submit_for:
return json_response({"error": f"Invalid query: {q}"}, status_code=400)
return json_response(
{"search_metadata": {"id": f"id-{q}", "status": "Processing"}}
)

def archive(self, search_id, params):
self.archive_params.append(dict(params))
statuses = self.statuses.get(search_id, ["Success"])
status = statuses.pop(0) if len(statuses) > 1 else statuses[0]
payload = {
"search_metadata": {"id": search_id, "status": status},
"search_parameters": {"q": search_id[len("id-"):]},
}
if status == "Error":
payload["error"] = "The search failed"
return json_response(payload)


@pytest.fixture
def fake():
return FakeSerpApi()


@pytest.fixture
def batch_client(fake, monkeypatch):
client = Client(api_key="test_key")
monkeypatch.setattr(client.session, "request", fake.request)
return client


def test_async_search_all_succeed(batch_client, fake):
fake.statuses = {
"id-coffee": ["Success"],
"id-tea": ["Cached"],
}

results = batch_client.async_search(
[{"engine": "google", "q": "coffee"}, {"engine": "google", "q": "tea"}],
poll_interval=0,
)

assert [r["search_metadata"]["status"] for r in results] == ["Success", "Cached"]
assert all(isinstance(r, serpapi.SerpResults) for r in results)
# Every search was submitted as an asynchronous search.
assert [p["async"] for p in fake.submit_params] == [True, True]


def test_async_search_preserves_input_order(batch_client, fake):
# "slow" finishes a round after the others, but keeps its position.
fake.statuses = {
"id-slow": ["Processing", "Success"],
"id-fast": ["Success"],
"id-cached": ["Cached"],
}

results = batch_client.async_search(["slow", "fast", "cached"], poll_interval=0)

assert [r["search_parameters"]["q"] for r in results] == ["slow", "fast", "cached"]


def test_async_search_polls_until_finished(batch_client, fake):
fake.statuses = {"id-coffee": ["Processing", "Processing", "Success"]}

results = batch_client.async_search([{"q": "coffee"}], poll_interval=0)

assert results[0]["search_metadata"]["status"] == "Success"
assert len(fake.archive_params) == 3


def test_async_search_failed_submit_does_not_sink_the_batch(batch_client, fake):
fake.fail_submit_for = {"bad"}

results = batch_client.async_search(["good", "bad", "also good"], poll_interval=0)

assert isinstance(results[0], serpapi.SerpResults)
assert isinstance(results[1], HTTPError)
assert results[1].error == "Invalid query: bad"
assert isinstance(results[2], serpapi.SerpResults)


def test_async_search_error_status_is_returned(batch_client, fake):
fake.statuses = {"id-broken": ["Error"]}

results = batch_client.async_search(["broken"], poll_interval=0)

assert isinstance(results[0], serpapi.SerpResults)
assert results[0]["search_metadata"]["status"] == "Error"
assert results[0]["error"] == "The search failed"


def test_async_search_queries_with_shared_parameters(batch_client, fake):
# The call shape proposed in the issue: query strings plus shared parameters.
results = batch_client.async_search(
queries=["burly", "creator"],
engine="youtube",
device="desktop",
poll_interval=0,
)

assert len(results) == 2
for params, q in zip(fake.submit_params, ["burly", "creator"]):
assert params["q"] == q
assert params["engine"] == "youtube"
assert params["device"] == "desktop"


def test_async_search_archive_requests_send_only_the_search_id(batch_client, fake):
fake.statuses = {"id-coffee": ["Processing", "Success"]}

batch_client.async_search(
[{"engine": "google", "q": "coffee"}], poll_interval=0
)

# Reusing the search parameters (such as "q") makes the archive API error.
assert fake.archive_params == [
{"search_id": "id-coffee", "api_key": "test_key"},
{"search_id": "id-coffee", "api_key": "test_key"},
]


def test_async_search_unfinished_search_times_out(batch_client, fake):
fake.statuses = {"id-slow": ["Processing"]}

results = batch_client.async_search(
["slow"], poll_interval=0.01, timeout=0.1
)

assert isinstance(results[0], TimeoutError)


def test_async_search_does_not_mutate_the_given_parameters(batch_client):
params = {"engine": "google", "q": "coffee"}

batch_client.async_search([params], poll_interval=0)

assert params == {"engine": "google", "q": "coffee"}


def test_async_search_empty_batch(batch_client):
assert batch_client.async_search([]) == []


def test_async_search_requires_searches_or_queries(batch_client):
with pytest.raises(TypeError):
batch_client.async_search()