`contextproxy` provides context-based lazy-loaded proxy objects for flask apps.
Project description
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.
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 withFlask
'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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file contextproxy-0.1.0.dev1.tar.gz
.
File metadata
- Download URL: contextproxy-0.1.0.dev1.tar.gz
- Upload date:
- Size: 10.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | db2c68fb79f57e173c312961f419e696396774be1584d8149fb84556b2ec9401 |
|
MD5 | 9ad1bb2510af83b1512982a6daf64667 |
|
BLAKE2b-256 | 9f2cfd10fb2899120edd8d58faffe2ccfac3b86b7d5cd945ecac38b9aa427601 |
File details
Details for the file contextproxy-0.1.0.dev1-py3-none-any.whl
.
File metadata
- Download URL: contextproxy-0.1.0.dev1-py3-none-any.whl
- Upload date:
- Size: 4.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6f5b3f9a228d464258feaefc93864278656b23c0bab084c48e2c3476c2b17c01 |
|
MD5 | 3aa1234332c1d1a981e09e9ac80908b3 |
|
BLAKE2b-256 | cd78fe33a82ef13b1894a0289781e8f78b306bbca27ec03d4ccf382229dac21c |