> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usetusk.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Learn how to initialize Tusk Drift in a Python application

## 1. Initialize the SDK

Create an init file or add the SDK initialization to your application entry point. The SDK must be initialized **before** your application starts handling requests.

<Warning>Ensure that `TuskDrift` is initialized before any other telemetry providers (e.g., OpenTelemetry, Sentry, etc.). If not, your existing telemetry may not work properly.</Warning>

### Initialization Parameters

<table>
  <thead>
    <tr>
      <th>Option</th>
      <th>Type</th>
      <th>Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><code>api\_key</code></td>
      <td><code>str</code></td>
      <td><b>Required if using Tusk Cloud</b></td>
      <td>Your Tusk Drift API key.</td>
    </tr>

    <tr>
      <td><code>env</code></td>
      <td><code>str</code></td>
      <td><code>os.environ.get("ENV", "development")</code></td>
      <td>The environment name.</td>
    </tr>

    <tr>
      <td><code>log\_level</code></td>
      <td><code>"silent" | "error" | "warn" | "info" | "debug"</code></td>
      <td><code>"info"</code></td>
      <td>The logging level.</td>
    </tr>

    <tr>
      <td><code>sampling\_rate</code></td>
      <td><code>float</code></td>
      <td><code>1.0</code></td>
      <td>Override the base sampling rate (0.0 - 1.0) for recording. Takes precedence over <code>TUSK\_RECORDING\_SAMPLING\_RATE</code> and config file base-rate settings.</td>
    </tr>
  </tbody>
</table>

> **See also:** [Environment Variables guide](https://github.com/Use-Tusk/drift-python-sdk/blob/main/docs/environment-variables.md) for detailed information about environment variables.

### Framework-Specific Setup

<Tabs>
  <Tab title="Flask">
    ```python theme={null}
    import os
    from flask import Flask
    from drift import TuskDrift

    # Initialize SDK BEFORE creating Flask app
    sdk = TuskDrift.initialize(
        api_key=os.environ.get("TUSK_API_KEY"),
        env=os.environ.get("FLASK_ENV", "development"),
        log_level="debug"
    )

    app = Flask(__name__)

    @app.route("/")
    def hello():
        return "Hello, World!"

    if __name__ == "__main__":
        # Mark app as ready before starting server
        sdk.mark_app_as_ready()
        app.run(host="0.0.0.0", port=8000)
    ```
  </Tab>

  <Tab title="FastAPI">
    ```python theme={null}
    import os
    import uvicorn
    from fastapi import FastAPI
    from drift import TuskDrift

    # Initialize SDK BEFORE creating FastAPI app
    sdk = TuskDrift.initialize(
        api_key=os.environ.get("TUSK_API_KEY"),
        env=os.environ.get("ENV", "development"),
        log_level="debug"
    )

    app = FastAPI()

    @app.get("/")
    async def hello():
        return {"message": "Hello, World!"}

    if __name__ == "__main__":
        # Mark app as ready before starting server
        sdk.mark_app_as_ready()
        uvicorn.run(app, host="0.0.0.0", port=8000)
    ```
  </Tab>

  <Tab title="Django">
    For Django applications, initialize the SDK in your `manage.py` or WSGI/ASGI entry point:

    ```python theme={null}
    # manage.py
    import os
    import sys

    # Initialize SDK BEFORE Django setup
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

    from drift import TuskDrift

    sdk = TuskDrift.initialize(
        api_key=os.environ.get("TUSK_API_KEY"),
        env=os.environ.get("DJANGO_ENV", "development"),
        log_level="debug"
    )

    import django
    django.setup()

    # Mark app as ready
    sdk.mark_app_as_ready()

    def main():
        from django.core.management import execute_from_command_line
        execute_from_command_line(sys.argv)

    if __name__ == "__main__":
        main()
    ```
  </Tab>
</Tabs>

## 2. Configure sampling

Tusk Drift supports both fixed sampling and adaptive sampling. In `fixed` mode,
the SDK records at a constant rate. In `adaptive` mode, the SDK starts from a
configured base rate and can temporarily reduce recording if local exporter or
runtime pressure increases.

The base sampling rate uses the following precedence (highest to lowest):

1. **Init Parameter** (`sampling_rate`)
2. **Environment Variable** (`TUSK_RECORDING_SAMPLING_RATE`, with `TUSK_SAMPLING_RATE` kept as a legacy alias)
3. **Configuration File** (`recording.sampling.base_rate`, or legacy `recording.sampling_rate`)

If not specified, the default base sampling rate is `1.0` (100%). The sampling
mode defaults to `fixed`.

<Tabs>
  <Tab title="Init Parameter">
    Set the sampling rate directly in your initialization code:

    ```python theme={null}
    sdk = TuskDrift.initialize(
        api_key=os.environ.get("TUSK_API_KEY"),
        sampling_rate=0.1,  # 10% of requests
    )
    ```
  </Tab>

  <Tab title="Environment Variable">
    Set the `TUSK_RECORDING_SAMPLING_RATE` environment variable:

    ```bash theme={null}
    # Development - record everything
    TUSK_RECORDING_SAMPLING_RATE=1.0 python app.py

    # Production - sample 10% of requests
    TUSK_RECORDING_SAMPLING_RATE=0.1 python app.py
    ```
  </Tab>

  <Tab title="Configuration File">
    Use the nested `recording.sampling` config to choose `fixed` vs `adaptive` mode:

    ```yaml theme={null}
    # ... existing configuration ...

    recording:
      sampling:
        mode: adaptive
        base_rate: 0.1
        min_rate: 0.01
        log_transitions: true
      export_spans: true
      enable_env_var_recording: true
    ```

    The legacy `recording.sampling_rate` field is still supported as an alias
    for `recording.sampling.base_rate`.
  </Tab>
</Tabs>

### Recording Configuration Options

<table>
  <thead>
    <tr>
      <th>Option</th>
      <th>Type</th>
      <th>Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><code>sampling.mode</code></td>
      <td><code>str</code></td>
      <td><code>"fixed"</code></td>
      <td>Selects constant sampling or adaptive load shedding.</td>
    </tr>

    <tr>
      <td><code>sampling.base\_rate</code></td>
      <td><code>float</code></td>
      <td><code>1.0</code></td>
      <td>The base sampling rate (0.0 - 1.0). In <code>fixed</code> mode this is the effective rate. In <code>adaptive</code> mode the SDK may temporarily reduce below this base rate.</td>
    </tr>

    <tr>
      <td><code>sampling.min\_rate</code></td>
      <td><code>float</code></td>
      <td><code>0.001</code> in <code>adaptive</code> mode</td>
      <td>The minimum steady-state sampling rate for adaptive mode. In critical conditions the SDK can still temporarily pause recording.</td>
    </tr>

    <tr>
      <td><code>sampling.log\_transitions</code></td>
      <td><code>bool</code></td>
      <td><code>True</code></td>
      <td>Controls whether the SDK emits adaptive-sampling transition logs. Can also be overridden by <code>TUSK\_RECORDING\_SAMPLING\_LOG\_TRANSITIONS</code>.</td>
    </tr>

    <tr>
      <td><code>sampling\_rate</code></td>
      <td><code>float</code></td>
      <td><code>None</code></td>
      <td>Legacy alias for <code>recording.sampling.base\_rate</code>. Still supported for backward compatibility.</td>
    </tr>

    <tr>
      <td><code>export\_spans</code></td>
      <td><code>bool</code></td>
      <td><code>false</code></td>
      <td>Whether to export spans to Tusk backend or local files (<code>.tusk/traces</code>). If false, spans are only exported to local files.</td>
    </tr>

    <tr>
      <td><code>enable\_env\_var\_recording</code></td>
      <td><code>bool</code></td>
      <td><code>false</code></td>
      <td>Whether to enable environment variable recording and replaying. Recommended if your application's business logic depends on environment variables.</td>
    </tr>
  </tbody>
</table>

## 3. Mark the app as ready

Once your application has completed initialization (database connections, middleware setup, etc.), mark it as ready:

```python theme={null}
sdk = TuskDrift.initialize(
    api_key=os.environ.get("TUSK_API_KEY"),
)

# Your application setup...

# Mark app as ready for recording/replay
sdk.mark_app_as_ready()
print("Server started and ready for Tusk Drift")
```

The `mark_app_as_ready()` call signals to the SDK that your application is fully initialized and ready to handle requests. This ensures that traces are only recorded for requests that occur after your application is properly set up.

To record your first set of API tests with Tusk Drift, view [this guide](/api-tests/record-replay-tests).
