Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Flask Context Proxy

contextproxy is a @contextmanager style LocalProxy, managed by flask.g, designed to simplify the management of lazily loaded, context-based resources in Flask applications. It allows resources to be easily accessed, automatically initialized and cleaned up based on Flask's request and application lifecycle, and can be used to share resources across multiple requests or manage them on a per-request basis.

Release PyPI - Version GitHub License

Features

  • Easy Access: Resources can be accessed using decorated names, making them easy to use in your application.
  • Lazy Initialization: Resources are only initialized when accessed, saving computation and memory for unused resources.
  • Automatic Teardown: Resources are cleaned up automatically after the application context is torn down.
  • Supports Flask Contexts: The decorator works seamlessly with Flask's request and application contexts, ensuring context isolation and cleanup.
  • Thread Safety: Ensures that resources are unique per thread in multi-threaded environments.

Installation

You can install contextproxy by including the file in your project directory or packaging it as a Python module.

pip install .

Usage

To use contextproxy, simply apply it as a decorator to a generator function that yields the resource you want to manage. The resource will be lazily initialized and binded to flask.g for the duration of the application context.

It should be noted that the resource is finalized only after the application context ends (for Flask>=0.9). That means the resource will be shared across multiple requests within the same application context.

Basic Example

from flask import Flask
from contextproxy import contextproxy

app = Flask(__name__)

@contextproxy(app)
def resource():
    # Initialize the resource
    resource_value = "This is a shared resource"
    yield resource_value
    # Teardown logic (e.g., closing connections) goes here
    print("Resource has been cleaned up")

@app.route('/')
def index():
    return f"Resource: {resource}"

if __name__ == "__main__":
    app.run(debug=True)

In the example above, the resource is lazily initialized the first time it's accessed and will be automatically cleaned up after the application context ends.

Advanced Usage

Handling Exceptions in Resource Initialization

If your resource initialization involves risky operations (like database connections), you can handle exceptions cleanly within the resource function.

@contextproxy(app)
def risky_resource():
    uuid = uuid4()
    print(f"before: Preparing to create resource ({uuid})")
    try:
        print(f"yielding: Creating resource ({uuid})")
        yield f"resource {uuid=}"
        print(f"yielded: where is this? ({uuid})")
    except Exception as e:
        print(f"except: error processing resource ({uuid}): {type(e)}: {e}")
    else:
        print(f"else: okey processing resource ({uuid})")
    finally:
        print(f"finally: Destroying resource ({uuid})")
    print(f"after: Destroyed resource ({uuid})")

Contributing

If you’d like to contribute to contextproxy, feel free to fork the repository, submit issues, or open a pull request!

License

This project is licensed under the MIT License.

Release files for contextproxy 0.1.0.dev1

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

Source distribution (sdist)

Source distribution for contextproxy 0.1.0.dev1
File Size Uploaded
contextproxy-0.1.0.dev1.tar.gz 10.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for contextproxy 0.1.0.dev1
File Interpreter ABI Platform
contextproxy-0.1.0.dev1-py3-none-any.whl Python 3 none any Details

Total release size: 15.5 kB

Release files / contextproxy-0.1.0.dev1.tar.gz

Download URL contextproxy-0.1.0.dev1.tar.gz
Size 10.7 kB
Tags Source
SHA-256 checksum
How to use checksums
db2c68fb79f57e173c312961f419e696396774be1584d8149fb84556b2ec9401
BLAKE2b-256 checksum
How to use checksums
9f2cfd10fb2899120edd8d58faffe2ccfac3b86b7d5cd945ecac38b9aa427601
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/5.1.1 CPython/3.12.6

Release files / contextproxy-0.1.0.dev1-py3-none-any.whl

Download URL contextproxy-0.1.0.dev1-py3-none-any.whl
Size 4.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6f5b3f9a228d464258feaefc93864278656b23c0bab084c48e2c3476c2b17c01
BLAKE2b-256 checksum
How to use checksums
cd78fe33a82ef13b1894a0289781e8f78b306bbca27ec03d4ccf382229dac21c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/5.1.1 CPython/3.12.6

Release history Release notifications | RSS feed

This release

0.1.0.dev1 This release

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