Skip to content
Merged
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
2 changes: 1 addition & 1 deletion docs/03_concepts/10_request_loaders.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ Here is a basic example of working with the <ApiLink to="class/RequestList">`Req

The <ApiLink to="class/RequestList">`RequestList`</ApiLink> supports state persistence, allowing it to resume from where it left off after interruption. This is particularly useful for long-running crawls or when you need to pause and resume crawling later.

To enable persistence, provide `persist_state_key` and optionally `persist_requests_key` parameters, and disable automatic cleanup by setting `purge_on_start = False` in the configuration. The `persist_state_key` saves the loader's progress, while `persist_requests_key` ensures that the request data doesn't change between runs. A request list with a `name` uses `CRAWLEE_REQUEST_LIST_STATE_<name>` and `CRAWLEE_REQUEST_LIST_REQUESTS_<name>` for the keys you don't pass. With a requests key, the list reads the whole source on first use, so the source must be finite. Requests that were in progress when the state was saved are served again after a restart. Use the request list as an async context manager, or call its `close()` method when you're done, so that its final state is saved. For more details on resuming interrupted crawls, see the [Stopping and resuming crawlers](../guides/stopping-and-resuming-crawlers) guide.
To enable persistence, provide `persist_state_key` and optionally `persist_requests_key` parameters, and disable automatic cleanup by passing `purge_on_start=False` to `Configuration`. The `persist_state_key` saves the loader's progress, while `persist_requests_key` ensures that the request data doesn't change between runs. A request list with a `name` uses `CRAWLEE_REQUEST_LIST_STATE_<name>` and `CRAWLEE_REQUEST_LIST_REQUESTS_<name>` for the keys you don't pass. With a requests key, the list reads the whole source on first use, so the source must be finite. Requests that were in progress when the state was saved are served again after a restart. Use the request list as an async context manager, or call its `close()` method when you're done, so that its final state is saved. For more details on resuming interrupted crawls, see the [Stopping and resuming crawlers](../guides/stopping-and-resuming-crawlers) guide.

<RunnableCodeBlock className="language-python" language="python">
{RlBasicPersistExample}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging

from crawlee import service_locator
from crawlee.configuration import Configuration
from crawlee.request_loaders import RequestList

logging.basicConfig(level=logging.INFO, format='%(asctime)s-%(levelname)s-%(message)s')
Expand All @@ -12,8 +13,7 @@
# This is necessary so that the state keys are not cleared at startup.
# The recommended way to achieve this behavior is setting the environment variable
# `CRAWLEE_PURGE_ON_START=0`
configuration = service_locator.get_configuration()
configuration.purge_on_start = False
service_locator.set_configuration(Configuration(purge_on_start=False))


async def main() -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging

from crawlee import service_locator
from crawlee.configuration import Configuration
from crawlee.http_clients import ImpitHttpClient
from crawlee.request_loaders import SitemapRequestLoader

Expand All @@ -13,8 +14,7 @@
# This is necessary so that the state keys are not cleared at startup.
# The recommended way to achieve this behavior is setting the environment variable
# `CRAWLEE_PURGE_ON_START=0`
configuration = service_locator.get_configuration()
configuration.purge_on_start = False
service_locator.set_configuration(Configuration(purge_on_start=False))


async def main() -> None:
Expand Down
2 changes: 1 addition & 1 deletion docs/04_guides/06_stopping_and_resuming.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Now resume crawling after the pause to process the remaining 3 links.

![Resuming crawling](/img/resuming-paused-crawl/01.webp 'Resuming crawling.')

Alternatively, set the environment variable `CRAWLEE_PURGE_ON_START=0` instead of `configuration.purge_on_start = False`:
Alternatively, set the environment variable `CRAWLEE_PURGE_ON_START=0` instead of passing `purge_on_start=False` to `Configuration`:

```bash
CRAWLEE_PURGE_ON_START=0 python your_crawler.py
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio

from crawlee import ConcurrencySettings, service_locator
from crawlee.configuration import Configuration
from crawlee.crawlers import (
BeautifulSoupCrawler,
BeautifulSoupCrawlingContext,
Expand All @@ -10,8 +11,7 @@
# This makes the scraper continue from where it left off in the previous run.
# The recommended way to achieve this behavior is setting the environment variable
# `CRAWLEE_PURGE_ON_START=0`
configuration = service_locator.get_configuration()
configuration.purge_on_start = False
service_locator.set_configuration(Configuration(purge_on_start=False))


async def main() -> None:
Expand Down
23 changes: 23 additions & 0 deletions docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,29 @@ async def main() -> None:
await crawler.run(['https://crawlee.dev/'])
```

## `Configuration` is immutable

`Configuration` instances are frozen, as in Crawlee JS v4. Assigning to a setting raises a `ValidationError`. Pass the value to the constructor instead, and register the instance before you create a crawler or open a storage:

**Before (v1):**

```python
from crawlee import service_locator

service_locator.get_configuration().purge_on_start = False
```

**Now (v2):**

```python
from crawlee import service_locator
from crawlee.configuration import Configuration

service_locator.set_configuration(Configuration(purge_on_start=False))
```

To get a modified copy of an existing instance, use `model_copy(update=...)`. It takes field names, not the `CRAWLEE_` aliases, and doesn't validate the values.

## `Event` is a `StrEnum`

`Event` now subclasses `enum.StrEnum`. Calling `str()` on a member or formatting it in an f-string returns its value, for example `'systemInfo'`. In v1, `str()` returned `'Event.SYSTEM_INFO'`, and so did an f-string on Python 3.11 and newer. Comparisons with plain strings work the same way as in v1.
Expand Down
6 changes: 5 additions & 1 deletion src/crawlee/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,15 @@ class Configuration(BaseSettings):
operations, and more.

Settings can also be configured via environment variables, prefixed with `CRAWLEE_`.

Instances are immutable, and assigning to a setting raises a `ValidationError`. To change a setting, pass the value
to the constructor. `model_copy(update=...)` also creates a modified copy, but it takes field names, not aliases,
and doesn't validate the values.
"""

# TODO: https://github.com/pydantic/pydantic-settings/issues/706
# Use `SettingsConfigDict(validate_by_name=True, validate_by_alias=True)` when issue is resolved.
model_config = SettingsConfigDict(populate_by_name=True)
model_config = SettingsConfigDict(populate_by_name=True, frozen=True)

internal_timeout: Annotated[timedelta | None, Field(alias='crawlee_internal_timeout')] = None
"""Timeout for the internal asynchronous operations."""
Expand Down
20 changes: 20 additions & 0 deletions tests/unit/test_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,23 @@ def test_global_configuration_works_reversed() -> None:
is Configuration.get_global_configuration()
is Configuration.get_global_configuration()
)


def test_configuration_is_immutable() -> None:
"""Assigning to a setting raises a `ValidationError` and leaves the value unchanged."""
configuration = Configuration(purge_on_start=True)

with pytest.raises(ValidationError, match='frozen'):
configuration.purge_on_start = False # ty: ignore[invalid-assignment]

assert configuration.purge_on_start is True


def test_configuration_model_copy_updates_setting() -> None:
"""`model_copy(update=...)` returns a new configuration with the setting changed."""
configuration = Configuration(purge_on_start=True)

updated = configuration.model_copy(update={'purge_on_start': False})

assert updated.purge_on_start is False
assert configuration.purge_on_start is True
Loading