Metadata-Version: 2.4
Name: usageflow-flask
Version: 0.3.6
Summary: Flask middleware for UsageFlow - Usage-based pricing made simple
Home-page: https://github.com/usageflow/usageflow-python
Author: UsageFlow
Author-email: ronen@usageflow.io
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.6
Description-Content-Type: text/markdown
Requires-Dist: flask>=2.0.0
Requires-Dist: usageflow-core>=0.3.5
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# UsageFlow for Flask

Meter selected Flask routes and inspect their traces in the
[UsageFlow Console](https://console.usageflow.io).

Use Python 3.10 or newer. Although the current package metadata advertises
Python 3.6+, the source uses Python 3.10 syntax.

## 1. Install

```bash
python -m pip install usageflow-flask
```

[View `usageflow-flask` on PyPI](https://pypi.org/project/usageflow-flask/).

## 2. Set the API key

Create an application and API key in the Console, then set it in the process
environment:

```bash
export USAGEFLOW_API_KEY="your-api-key"
```

The package does not require `python-dotenv`.

## 3. Register the middleware

Register one `UsageFlowMiddleware` instance on the Flask application before the
application begins serving requests:

```python
import os

from flask import Flask, jsonify
from usageflow.flask import UsageFlowMiddleware

app = Flask(__name__)


@app.get("/api/hello")
def hello():
    return jsonify({"message": "hello"})


usageflow = UsageFlowMiddleware(
    app,
    api_key=os.environ["USAGEFLOW_API_KEY"],
)
```

Flask integration uses the constructor directly; do not use
`app.add_middleware`.

## 4. Select routes in the Console

For the application that owns the API key, add a `monitoringPaths` entry for the
first route:

```text
method: GET
url: /api/hello
```

Use `whitelistEndpoints` for routes that must be skipped. A whitelist match wins
over a monitoring match. The middleware refreshes Console configuration about
every 10 seconds.

Important: an empty monitoring map skips **all** requests. It does not enable
monitor-all behavior. Configure a monitoring path and wait for a refresh before
testing.

Methods can be an HTTP method or `*`. URL `*` matches every path. A URL that
contains `*` acts as a prefix after the `*` characters are removed, not as a
general glob or regular expression. For example, `/api/users/*` matches
`/api/users/123`.

Current limitation: when several URL patterns use the same method, only the
first pattern may be evaluated. Prefer one prefix or `*` entry per method.

Flask route selection compares Console paths with the concrete request path.
For a dynamic Flask route such as `/users/<user_id>`, monitor a suitable prefix
such as `/users/*`, or list the concrete paths you intend to meter.

## 5. Send a request

Start the application, allow up to 10 seconds for the first configuration
refresh, then call the monitored route:

```bash
curl -i http://127.0.0.1:5000/api/hello
```

## 6. Verify the first Trace

Open the application's Traces view in the Console and confirm a `GET /api/hello`
trace appears. If it does not appear, wait for another refresh and send one more
request.

## Production and security notes

- UsageFlow records request method, route/path information, client and user-agent
  data, headers, query/path parameters, and JSON request bodies. It records
  response status, headers, duration, and a schema derived from JSON responses;
  it does not attach the full response body to trace metadata.
- Request header names containing `key` are redacted. Other headers and JSON body
  fields are not automatically redacted, so avoid monitoring routes that expose
  secrets unless your data handling policy allows it.
- Policy identity may come from a path parameter, query parameter, JSON body
  field, header, bearer-token claim, cookie, or configured claim in a JWT cookie.
  JWTs are decoded without signature verification for identity extraction.
  Your application remains responsible for authentication and authorization.
- Connectivity and telemetry failures generally fail soft: the Flask request
  continues without UsageFlow tracking. An explicit policy decision, including
  endpoint blocking or a denied usage request, can intentionally reject traffic.

## Troubleshooting

- **No Trace:** confirm the API key belongs to the selected Console application,
  `monitoringPaths` is not empty, the method and concrete path match, and the
  route is not whitelisted. Wait at least 10 seconds after Console changes.
- **Dynamic route does not match:** Flask filtering sees the concrete path; use a
  prefix such as `/users/*`.
- **Application does not connect:** confirm `USAGEFLOW_API_KEY` is present in the
  server process and outbound secure WebSocket access is allowed.
- **Request is denied:** check the application's UsageFlow endpoint and usage
  policies. Fail-soft connectivity behavior does not override an explicit policy
  denial.
