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
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from contextlib import suppress
from datetime import timedelta

from crawlee import ConcurrencySettings, Request
Expand Down Expand Up @@ -50,9 +51,13 @@ async def error_processing(context: BasicCrawlingContext, error: Exception) -> N
)

async with session_pool:
# The pool creates sessions on demand, so create them before binding
# the first requests to them, for example for authentication
sessions = [await session_pool.get_session() for _ in range(10)]
# Add the sessions before binding the first requests to them,
# for example one session per authenticated profile
profile_ids = [f'profile-{i}' for i in range(10)]
for profile_id in profile_ids:
# A resumed run restores the usable sessions from the persisted state
with suppress(ValueError):
await session_pool.add_session({'id': profile_id})

# Create a pool of requests bound to their respective sessions
# Use `always_enqueue=True` if session initialization happens on a non-unique
Expand All @@ -61,10 +66,10 @@ async def error_processing(context: BasicCrawlingContext, error: Exception) -> N
Request.from_url(
'https://example.org/',
label='session_init',
session_id=session.id,
session_id=profile_id,
use_extended_unique_key=True,
)
for session in sessions
for profile_id in profile_ids
]

await crawler.run(init_requests)
Expand Down
46 changes: 45 additions & 1 deletion docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ Session state, including the persisted session pool state, has a new `retired` f

### The session pool creates sessions on demand

`SessionPool` no longer fills itself up to `max_pool_size` when you enter it. `get_session()` creates a new session while the pool has fewer than `max_pool_size` sessions, and picks a random one after that. `get_session_by_id()` no longer creates sessions, so a request bound by `session_id` to a session that the pool hasn't created yet fails with a `RequestCollisionError`. To bind requests to sessions up front, create the sessions with `get_session()` before you run the crawler.
`SessionPool` no longer fills itself up to `max_pool_size` when you enter it. `get_session()` creates a new session while the pool has fewer than `max_pool_size` sessions, and picks a random one after that. `get_session()` with a session ID doesn't create sessions, so a request bound by `session_id` to a session that the pool hasn't created yet fails with a `RequestCollisionError`. To bind requests to sessions up front, add the sessions with `add_session()` before you run the crawler.

### Sessions carry their proxy

Expand Down Expand Up @@ -895,6 +895,48 @@ def create_session(options: SessionOptions) -> Session:
session_pool = SessionPool(create_session_function=create_session)
```

### `get_session()` takes the session ID

`SessionPool.get_session_by_id()` is removed. Pass the ID to `get_session()` instead. With an ID, `get_session()` returns the usable session with this ID or `None`, and doesn't create a session.

### `add_session()` is async and takes session options

`SessionPool.add_session()` is a coroutine and returns the added session. Besides a `Session`, it takes the options of a new session and builds the session from them the same way as the sessions the pool creates: merged over `create_session_settings`, with a proxy from `proxy_configuration`, by `create_session_function`. A passed `Session` is added as it is.

When the pool already holds a usable session with the same ID, `add_session()` raises a `ValueError`. A session with the same ID that's no longer usable is replaced. In v1, `add_session()` logged a warning and kept the old session in both cases.

**Before (v1):**

```python
session_pool.add_session(Session(id='login'))
session = await session_pool.get_session_by_id('login')
```

**Now (v2):**

```python
# highlight-next-line
await session_pool.add_session({'id': 'login'})
# highlight-next-line
session = await session_pool.get_session('login')
```

When `add_session()` has grown the pool beyond `max_pool_size`, `get_session()` creates a new session only if removing the retired sessions leaves room for it. Otherwise, it returns one of the remaining sessions. In v1, it created a new session every time it removed retired sessions.

### A session ID is unique in the pool

The pool holds one usable session per ID. It raises a `ValueError` when:

- `get_session()` gets a session from `create_session_function` with the ID of a usable session already in the pool. Such a function includes one that returns the same `Session` object on every call, so with a `max_pool_size` over 1 the second `get_session()` raises.
- The pool is entered, and the function gives two restored sessions the same ID.
- `create_session_settings` holds an `id`, and `max_pool_size` is over 1.

In v1, a new session silently replaced the session with its ID, so a pool with a fixed session ID and a `max_pool_size` over 1 created new sessions, without the cookies of the old one, on every `get_session()` call. To share one session, pass `max_pool_size=1`. To use several sessions with fixed IDs, add them with `add_session()`.

`get_session()` and `add_session()` also raise a `ValueError` when the session they build is no longer usable, such as a shared session that `create_session_function` returns after it was retired. In v1, the pool returned such a session. When the pool is entered, it drops a restored session that the function recreates unusable.

In a crawler, a `ValueError` from `get_session()` ends the crawl: `run()` raises it after the crawler has tried to get a session three times.

### `max_session_rotations` is removed

Session errors no longer have their own retry budget, the same as in Crawlee JS v4. The `max_session_rotations` crawler option and the `Request.session_rotation_count` property are removed. A `SessionError`, which includes a `ProxyError` and a blocked response, retires the session and counts towards `max_request_retries` like any other error. With the defaults, a request that keeps failing with session errors gets 4 attempts instead of 10. To allow more attempts on blocked requests, raise `max_request_retries`.
Expand Down Expand Up @@ -1606,6 +1648,8 @@ The `ThrottlingRequestManager` warning about capping a delay now calls it a "req

The WARNING `Encountered "<error>", rotating session and retrying...` is removed. Session errors log the same `Retrying request to <url> due to: <error>. <location>` WARNING as other errors. For the other session error changes, see [`max_session_rotations` is removed](#max_session_rotations-is-removed).

`SessionPool.add_session()` no longer logs the `Session with ID ... already exists in the pool.` warning. It raises a `ValueError` for a usable session with the same ID and replaces one that's no longer usable. For details, see [`add_session()` is async and takes session options](#add_session-is-async-and-takes-session-options).

The `Retrying request to ...` WARNING is now logged after the `error_handler` runs, and only when the request is retried. In v1, it was logged before the error handler, so it also appeared when the handler then raised.

The error of an `AdaptivePlaywrightCrawler` sub crawler that timed out now reads `rendering_type=static timed out after 60.0 seconds`, with a space before `seconds`.
Expand Down
2 changes: 1 addition & 1 deletion src/crawlee/crawlers/_basic/_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ async def _get_session(self) -> Session:
async def _get_session_by_id(self, session_id: str) -> Session | None:
"""Take the session with the given id from the session pool."""
return await wait_for(
partial(self._session_pool.get_session_by_id, session_id),
partial(self._session_pool.get_session, session_id),
timeout=self._internal_timeout,
timeout_message='Fetching a session from the pool timed out after '
f'{self._internal_timeout.total_seconds()} seconds',
Expand Down
Loading
Loading