Session · Python
Own shared request defaults, connection pools, per-host pacing and retry settings.
In this guide
Purpose and lifecycle
Create one session per site or authentication identity and pass it to related operations. Configuration setters return the same session. Settings are held in the Rust engine.
Set authentication and response-cache middleware before the first fetch. A clone copies request configuration but starts independent pools, metrics and middleware. It does not inherit installed auth/cache layers.
Cookies are explicitly configured request defaults, not a browser cookie jar. They have no domain, path or expiry attributes and Set-Cookie responses are not automatically persisted.
Python retry and cookie-management methods are in development source and are not included in the existing alpha.2 package; they require a later release or a matching source build.
Definition and availability
Source snapshot: 1.0.0-alpha.3. Package export. Declared in source; this is not a runtime test result.
Signatures and source locations are generated from the SDK wrappers. Clean snapshots link to the recorded commit. Modified snapshots link to main, which may differ; file hashes identify the local inputs.
class SessionUsage example
Use a matching source build. Where a snippet uses page, obtain it with the Page example first. Example URLs illustrate API shape; they are not promised datasets.
from crawlingo import Session, Dataset
# These retry and cookie methods require the development source.
session = Session().rate_limit(2).timeout(30)
session.retries(3).retry_delay(1).retry_backoff(2)
session.cookies({"locale": "en"})
print(session.get_cookies())
session.delete_cookie("locale").clear_cookies()
session.headers({"User-Agent": "ResearchDataset/1.0"})
result = Dataset("https://example.com/", session=session).field("title", "h1").build()
print(result.to_dict())Members
| Member | Kind | Return / value type | Source status |
|---|---|---|---|
| __init__ | method | Not annotated; see behavior notes | Present in source |
| headers | method | 'Session' | Present in source |
| cookies | method | 'Session' | Present in source |
| get_cookies | method | dict | Present in source |
| delete_cookie | method | 'Session' | Present in source |
| clear_cookies | method | 'Session' | Present in source |
| retries | method | 'Session' | Present in source |
| retry_backoff | method | 'Session' | Present in source |
| retry_delay | method | 'Session' | Present in source |
| proxy | method | 'Session' | Present in source |
| rate_limit | method | 'Session' | Present in source |
| auto_match | method | 'Session' | Present in source |
| timeout | method | 'Session' | Present in source |
| fingerprint_path | method | 'Session' | Present in source |
| fetcher_tier | method | 'Session' | Present in source |
| browser_profile | method | 'Session' | Present in source |
| auto_match_weights | method | 'Session' | Present in source |
| proxy_pool | method | 'Session' | Present in source |
| proxy_provider | method | 'Session' | Present in source |
| enable_response_cache | method | 'Session' | Present in source |
| basic_auth | method | 'Session' | Present in source |
| bearer_auth | method | 'Session' | Present in source |
| header_auth | method | 'Session' | Present in source |
| api_key_auth | method | 'Session' | Present in source |
| from_config | static method | 'Session' | Present in source |
| metrics | method | dict | Present in source |
| page | method | 'Page' | Present in source |
| dataset | method | 'Dataset' | Present in source |
| watch | method | 'Watch' | Present in source |
| crawl | method | 'Crawl' | Present in source |
| clone | method | 'Session' | Present in source |
| destroy | method | None | Present in source |
| __enter__ | method | 'Session' | Present in source |
| __exit__ | method | Not annotated; see behavior notes | Present in source |
__init__()
Create an empty session with a 30-second request timeout, standard HTTP transport and no pacing limit. No request is sent by construction.
Returns / value: Not annotated; see behavior notes.
def __init__(self)headers()
Replace the entire default header map. Node Page.create merges its request headers over this map. Authentication headers apply to every request using this session.
Returns / value: 'Session'.
def headers(self, headers: dict) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| headers | dict | Required | Header names and values; avoid sharing credentials across unrelated sites. |
cookies()
Replace the entire explicit cookie map. Use a different session for another authentication identity.
Returns / value: 'Session'.
def cookies(self, cookies: dict) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| cookies | dict | Required | Explicit cookie-name/value defaults. |
get_cookies()
Return a snapshot of configured cookies. Mutating the returned object does not mutate the session.
Returns / value: dict.
def get_cookies(self) -> dictdelete_cookie()
Remove one cookie by its case-sensitive name. Deleting an absent name succeeds without changing anything.
Returns / value: 'Session'.
def delete_cookie(self, name: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| name | str | Required | Field, header or attribute name for this operation. |
clear_cookies()
Remove all explicit cookie defaults. This does not clear an independently supplied Cookie header.
Returns / value: 'Session'.
def clear_cookies(self) -> 'Session'retries()
Set additional attempts after the initial request. 0 means one attempt. Integers 0–4294967295 are accepted. Default Page/Dataset/Crawl/Job retry count is 3; downloader/sitemap defaults can differ until explicitly set.
Returns / value: 'Session'.
def retries(self, count: int) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| count | int | Required | Count of additional retries after the initial attempt. |
retry_backoff()
Set a finite exponential multiplier >= 1. Delay for retry n starts at base × factor^n, capped by policy. Default factor is 2. In development source, Retry-After in seconds or HTTP-date form takes precedence when enabled; older releases support seconds only. Changes affect subsequent dispatches without rebuilding pools.
Returns / value: 'Session'.
def retry_backoff(self, factor: float) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| factor | float | Required | Finite multiplier, at least 1. |
retry_delay()
Set initial backoff in whole seconds, from 0 to 86400. The default policy uses 500 ms; use shared configuration for fractional-second timing. Computed delay is capped at max(configured maximum, initial delay).
Returns / value: 'Session'.
def retry_delay(self, seconds: int) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| seconds | int | Required | Time in seconds; see the method-specific range and timing semantics. |
proxy()
Set a static proxy URL. A static proxy takes priority over the rotation pool. HTTP(S) and supported SOCKS proxy behavior depends on the compiled HTTP client.
Returns / value: 'Session'.
def proxy(self, proxy_url: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| proxy_url | str | Required | Proxy endpoint URL accepted by the compiled HTTP transport. |
rate_limit()
Set the shared per-host request rate in requests per second. 0 disables configured pacing. This is not a global limit across separate sessions or machines.
Returns / value: 'Session'.
def rate_limit(self, requests_per_second: float) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| requests_per_second | float | Required | Per-host rate for the shared session. |
auto_match()
Enable heuristic CSS fingerprint recovery for the Dataset builder. It does not enable selector recovery in DatasetJob or execute JavaScript.
Returns / value: 'Session'.
def auto_match(self, enabled: bool) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| enabled | bool | Required | Enable or disable this behavior. |
timeout()
Set the per-attempt timeout in seconds. Total time can exceed it because of retries, backoff and rate-limit waits.
Returns / value: 'Session'.
def timeout(self, seconds: int) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| seconds | int | Required | Time in seconds; see the method-specific range and timing semantics. |
fingerprint_path()
Select the local directory used for lazily opened fingerprint storage. Keep one coherent identity/history for a selector; a new path has no recovery history.
Returns / value: 'Session'.
def fingerprint_path(self, path: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| path | str | Required | Filesystem path relative to the process working directory unless absolute. |
fetcher_tier()
Node exposes standard and stealthy HTTP tiers. Python can request browser only when its native build includes the browser feature and local Chromium is available. Stealth emulation does not guarantee access.
Returns / value: 'Session'.
def fetcher_tier(self, tier: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| tier | str | Required | Transport mode supported by this binding and native build. |
browser_profile()
Choose a supported HTTP impersonation profile: chrome, firefox or safari. A profile changes transport emulation; it does not launch a browser.
Returns / value: 'Session'.
def browser_profile(self, profile: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| profile | str | Required | HTTP impersonation profile; this does not launch a browser. |
auto_match_weights()
Set scoring weights used by the heuristic matcher. Similarity scores are not calibrated probabilities; validate recovered field values.
Returns / value: 'Session'.
def auto_match_weights(self, weights: dict) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| weights | dict | Required | Named heuristic matching weights. Review extracted values after changing scores. |
proxy_pool()
Replace the pool of proxy URLs used in round-robin order when no static proxy is set. This is configuration, not a proxy health-check service.
Returns / value: 'Session'.
def proxy_pool(self, proxies: list) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| proxies | list | Required | Proxy URL list used when no static proxy is configured. |
proxy_provider()
Fetch proxy entries from the configured provider endpoint. The Node binding currently discards a provider-fetch error; do not treat this setter returning as proof that proxies were loaded.
Returns / value: 'Session'.
def proxy_provider(self, url: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| url | str | Required | HTTP(S) source URL; verify the target is appropriate for your application. |
enable_response_cache()
Install in-memory response caching before first fetch. max_entries bounds entry count; default_ttl_seconds is the fallback freshness lifetime. Cache headers and validators still apply.
Returns / value: 'Session'.
def enable_response_cache(self, max_entries: int=1024, default_ttl_seconds: int=300) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| max_entries | int | Default: 1024 | Maximum number of cached responses, not a total byte limit. |
| default_ttl_seconds | int | Default: 300 | Fallback cache lifetime in seconds. |
basic_auth()
Install HTTP Basic Authorization middleware before the first request. Pass credentials through application configuration; do not embed them in example source.
Returns / value: 'Session'.
def basic_auth(self, username: str, password: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| username | str | Required | HTTP Basic username from application configuration. |
| password | str | Required | HTTP Basic password; obtain it from protected application configuration. |
bearer_auth()
Install a fixed Bearer token header before first fetch. Refresh or rotation is owned by your application.
Returns / value: 'Session'.
def bearer_auth(self, token: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| token | str | Required | Bearer credential managed by the application. |
header_auth()
Install a named authentication header before the first fetch.
Returns / value: 'Session'.
def header_auth(self, name: str, value: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| name | str | Required | Field, header or attribute name for this operation. |
| value | str | Required | Header or query value for the configured authentication method. |
api_key_auth()
Append an API-key query parameter to outgoing request URLs. Query values may appear in access logs; use a header where the upstream supports it.
Returns / value: 'Session'.
def api_key_auth(self, name: str, value: str) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| name | str | Required | Field, header or attribute name for this operation. |
| value | str | Required | Header or query value for the configured authentication method. |
from_config()
Load TOML or JSON, apply CRAWLINGO_* environment overrides and validate configuration. Omit the path to load defaults plus environment only. Explicit setters applied afterward override loaded settings.
Returns / value: 'Session'.
def from_config(cls, path: Optional[str]=None) -> 'Session'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| path | Optional[str] | Default: None | Filesystem path relative to the process working directory unless absolute. |
metrics()
Return a snapshot of fetch counts, statuses, per-host activity and latency. These are session metrics, not the DatasetJob record-quality report.
Returns / value: dict.
def metrics(self) -> dictpage()
Create a lazy Python Page attached to the session. Python Page currently supplies its own default timeout=30 and retries=3; pass explicit Page options when those values matter.
Returns / value: 'Page'.
def page(self, url: str) -> 'Page'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| url | str | Required | HTTP(S) source URL; verify the target is appropriate for your application. |
dataset()
Create a Dataset builder attached to this session. Add fields and call build to fetch.
Returns / value: 'Dataset'.
def dataset(self, url: str) -> 'Dataset'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| url | str | Required | HTTP(S) source URL; verify the target is appropriate for your application. |
watch()
Create a field-monitoring Watch handle. Register fields and callbacks before starting it.
Returns / value: 'Watch'.
def watch(self, url: str) -> 'Watch'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| url | str | Required | HTTP(S) source URL; verify the target is appropriate for your application. |
crawl()
Create a Python Crawl wrapper. Review its documented native-binding gaps before use.
Returns / value: 'Crawl'.
def crawl(self, url: str) -> 'Crawl'| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| url | str | Required | HTTP(S) source URL; verify the target is appropriate for your application. |
clone()
Return an independent session with copied defaults and retry settings. Cookie changes on the clone do not affect the original. Middleware is not cloned.
Returns / value: 'Session'.
def clone(self) -> 'Session'destroy()
Clear selected native state and drop cached managers when no operation retains them. This is cleanup, not cancellation of running jobs. Await owned work before cleanup.
Returns / value: None.
def destroy(self) -> None__enter__()
Return the same Python session for a with block.
Returns / value: 'Session'.
def __enter__(self) -> 'Session'__exit__()
The current Python context-manager exit is a no-op. It does not call destroy; manage cleanup explicitly.
Returns / value: Not annotated; see behavior notes.
def __exit__(self, exc_type, exc_val, exc_tb)| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
| exc_type | Not annotated | Required | Exception class supplied by the Python with statement, or None. |
| exc_val | Not annotated | Required | Exception instance supplied by the Python with statement, or None. |
| exc_tb | Not annotated | Required | Traceback supplied by the Python with statement, or None. |
Errors and operational limits
Node retry setters reject invalid numbers with RangeError. Native configuration failures use CrawlingoError; Python session methods can propagate native RuntimeError or ValueError directly. Do not assume identical exception translation across bindings.
Source availability, package publication and runtime validation are separate facts. These pages describe the source snapshot, not a claim that all platforms or every API path have passed production acceptance.