Skip to main content

Arcane flask

This package help us authenticate users

Get Started

pip install arcane-flask

Example Usage

from arcane.flask import check_access_rights
from arcane.core import RightsLevelEnum, UserRightsEnum
from arcane.datastore import Client as DatastoreClient
from arcane.pubsub import Client as PubSubClient

datastore_client = DatastoreClient()
pubsub_client = PubSubClient()

@check_access_rights(
    service='my-service',
    required_rights=RightsLevelEnum.VIEWER,
    service_user_right=UserRightsEnum.MY_SERVICE,
    datastore_client=datastore_client,
    pubsub_client=pubsub_client,
    receive_rights_per_client=True,
    project='my-project',
    timeout=30  # Timeout in seconds
)
def function(params):
    pass

Timeout Configuration

The check_access_rights decorator includes a built-in timeout parameter that allows you to set a maximum execution time for the decorated function. If the function exceeds this timeout, the decorator will automatically return a timeout response.

import time

@check_access_rights(
    service='my-service',
    required_rights=RightsLevelEnum.VIEWER,
    service_user_right=UserRightsEnum.MY_SERVICE,
    datastore_client=datastore_client,
    pubsub_client=pubsub_client,
    project='my-project',
    timeout=2  # 2 seconds timeout
)
def slow_function():
    time.sleep(5)  # This will exceed the timeout
    return {'result': 'success'}

If the function exceeds the timeout, the decorator will return:

({'detail': 'Request Timeout'}, 504)

Note: Set the timeout parameter to a value a few seconds less than your Cloud Run or server timeout configuration to ensure proper error handling.

Activity tracking

Tracking records request usage (user, service, function, status code, execution time, optional metadata) and sends it to a configurable sink via a ports & adapters setup. You pass a tracker (adapter) and a service name at startup; every request is then tracked automatically.

Register tracking at app startup

Use init_tracking(app, tracker, service_name). The tracker is any implementation of TrackingPort (e.g. LogTrackingAdapter or PubSubTrackingAdapter).

Log adapter (development or debugging; events go to the Python logger at INFO):

from arcane.flask import init_tracking
from arcane.flask.tracking import LogTrackingAdapter

app = Flask(__name__)
tracker = LogTrackingAdapter()
init_tracking(app, tracker, service_name="my-service")

PubSub adapter (production; events go to a Google Cloud Pub/Sub topic):

from arcane.flask import init_tracking
from arcane.flask.tracking import PubSubTrackingAdapter
from arcane.pubsub import Client as PubSubClient

app = Flask(__name__)
pubsub_client = PubSubClient()
tracker = PubSubTrackingAdapter(
    pubsub_client=pubsub_client,
    project="my-project",
    topic="activity-tracker",  # optional; default is "activity-tracker"
)
init_tracking(app, tracker, service_name="my-service")

Custom columns (PubSub only) By default the PubSub adapter sends all standard fields. You can restrict which fields are published by passing columns:

tracker = PubSubTrackingAdapter(
    pubsub_client=pubsub_client,
    project="my-project",
    topic="activity-tracker",
    columns=["user_email", "service", "status_code", "execution_time"],
)

Undecorated routes are tracked

Routes that do not use check_access_rights are still tracked. The middleware fills in a baseline event using the request: function_name comes from Flask’s request.endpoint (the view function name), service from the service_name you passed to init_tracking, and email is empty.

Enriching context during the request

Use enrich_tracking() inside any route (with or without check_access_rights) to add or merge key/value pairs into the event’s additional_info. Multiple calls in the same request are merged.

from arcane.flask.tracking import enrich_tracking

@app.route("/process")
def process():
    enrich_tracking({"labels": ["feed"]})
    size = read_file_size()
    enrich_tracking({"file_size": size})
    return {"status": "ok"}, 200

The emitted event will include additional_info={"labels": ["feed"], "file_size": ...}.

Excluding endpoints

Pass excluded_endpoints so some views (e.g. health checks) are not tracked:

init_tracking(
    app,
    tracker,
    service_name="my-service",
    excluded_endpoints=frozenset({"health", "readiness"}),
)

Custom adapter

Implement the TrackingPort interface and pass it to init_tracking:

from arcane.flask.tracking import TrackingPort, ActivityEvent

class MyTrackingAdapter(TrackingPort):
    def emit(self, event: ActivityEvent) -> None:
        # send event to your backend (Kafka, HTTP, etc.)
        ...

Request ids

Use get_request_id() from this package:

from arcane.flask import get_request_id

request_id = get_request_id()   # None outside a request context

It reads X-Request-Id, falling back to the first segment of X-Cloud-Trace-Context, and works under both Flask and Connexion v3.

Do not use flask_log_request_id.current_request_id()

flask_log_request_id is still a dependency of this package, but only its RequestID(app) middleware is usable. Both of these raise ImportError: cannot import name '_app_ctx_stack' from 'flask':

from flask_log_request_id import current_request_id, RequestIDLogFilter

current_request_id()            # raises
RequestIDLogFilter().filter(record)   # raises on every log record

The package does from flask import _app_ctx_stack inside the call, and Flask removed _app_ctx_stack in 2.3. Because the import is deferred, RequestID(app) and the module-level imports all succeed — the failure only appears when the function runs, so an app boots cleanly and then fails per-request. A RequestIDLogFilter installed on the root logger raises on every record.

flask_log_request_id 0.10.1 is its latest release (2020) and is unmaintained, so there is no fixed version to upgrade to. Replace current_request_id() with get_request_id() above.

Structured logging labels

The arcane.flask.logs module lets you add structured labels to every log entry in a request. This is useful for attaching metadata such as component, module, function, or IDs like optimization_id.

First, set up logging once at application startup:

from arcane.flask import logs

logs.setup_logging(gcp_project="my-gcp-project-id")

Then, register a teardown handler to clear labels at the end of each request:

from arcane.flask import logs

@app.teardown_request
def clear_logging_labels(exc):
    logs.clear_labels()

Inside your handlers you can either attach labels imperatively:

from arcane.flask import logs

def validate_model_parallelism_post(optimization_id: str, job_prefix: str, ...):
    logs.attach_labels(
        component="feed-boost",
        module="api",
        function="validate_model_parallelism_post",
        optimization_id=optimization_id,
        job_prefix=job_prefix,
    )
    ...

or use the with_log_labels decorator for static labels and still add dynamic labels as needed:

from arcane.flask import logs

@logs.with_log_labels(
    component="feed-boost",
    module="api",
    function="validate_model_parallelism_post",
)
def validate_model_parallelism_post(optimization_id: str, job_prefix: str, ...):
    logs.attach_labels(
        optimization_id=optimization_id,
        job_prefix=job_prefix,
    )
    ...

All log records emitted during the request will then include a logging.googleapis.com/labels field with the JSON-encoded labels.

Metadata

Release files for arcane-flask 4.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for arcane-flask 4.2.2
File Size Uploaded
arcane_flask-4.2.2.tar.gz 15.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for arcane-flask 4.2.2
File Interpreter ABI Platform
arcane_flask-4.2.2-py3-none-any.whl Python 3 none any Details

Total release size: 33.5 kB

Release files / arcane_flask-4.2.2.tar.gz

Download URL arcane_flask-4.2.2.tar.gz
Size 15.4 kB
Tags Source
SHA-256 checksum
How to use checksums
e58cf41a45faace22857fcf45f4fa6276971576b2c6dfe1cbca6690d23c21767
BLAKE2b-256 checksum
How to use checksums
cb98223a18a182eace5e83cde3488377fe76a504455066a61753c7da0cd7e0ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.4.3 CPython/3.12.14 Linux/6.17.0-1022-azure

Release files / arcane_flask-4.2.2-py3-none-any.whl

Download URL arcane_flask-4.2.2-py3-none-any.whl
Size 18.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3373101a07908b78da557fa6efad74491ee6618355034d8c9d85d4cdd48e1220
BLAKE2b-256 checksum
How to use checksums
8d56ccff67f02d96c6e047642660e983110fd6a3d45796b5afd50b06b574980d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.4.3 CPython/3.12.14 Linux/6.17.0-1022-azure

Release history Release notifications | RSS feed

This release

4.2.2 This release

2 release files

4.2.1

2 release files

4.2.0

2 release files

4.0.0

2 release files

3.1.0

2 release files

3.0.0

2 release files

2.2.2

2 release files

2.2.1

2 release files

2.2.0

2 release files

2.0.7

2 release files

2.0.6

2 release files

2.0.5

2 release files

2.0.4

2 release files

2.0.3

2 release files

2.0.2

2 release files

2.0.1

2 release files

2.0.0

2 release files

1.14.3

2 release files

1.14.2

2 release files

1.14.1

2 release files

1.13.1

2 release files

1.13.0

2 release files

1.12.2

2 release files

1.12.1

2 release files

1.12.0

2 release files

1.11.0

2 release files

1.10.0

2 release files

1.9.1

2 release files

1.9.0

2 release files

1.8.0

2 release files

1.7.2

2 release files

1.7.1

2 release files

1.7.0

2 release files

1.6.0

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.10

2 release files

1.0.9

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

0.6.7

2 release files

0.6.6

2 release files

0.6.5

2 release files

0.6.4

2 release files

0.6.3

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.7

2 release files

0.5.6

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page