Name | contextproxy JSON |
Version |
0.1.0.dev1
JSON |
| download |
home_page | None |
Summary | `contextproxy` provides context-based lazy-loaded proxy objects for flask apps. |
upload_time | 2024-09-19 17:06:32 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.7 |
license | MIT |
keywords |
flask
context
proxy
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# 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](https://github.com/guoquan/contextproxy/actions/workflows/release.yml/badge.svg)](https://github.com/guoquan/contextproxy/actions/workflows/release.yml)
[![PyPI - Version](https://img.shields.io/pypi/v/contextproxy)](https://pypi.org/project/contextproxy/)
[![GitHub License](https://img.shields.io/github/license/guoquan/contextproxy)](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.
```bash
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
```python
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.
```python
@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.
Raw data
{
"_id": null,
"home_page": null,
"name": "contextproxy",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "flask, context, proxy",
"author": null,
"author_email": "Quan Guo <1118270+guoquan@users.noreply.github.com>",
"download_url": "https://files.pythonhosted.org/packages/9f/2c/fd10fb2899120edd8d58faffe2ccfac3b86b7d5cd945ecac38b9aa427601/contextproxy-0.1.0.dev1.tar.gz",
"platform": null,
"description": "# Flask Context Proxy\n\n`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.\n\n[![Release](https://github.com/guoquan/contextproxy/actions/workflows/release.yml/badge.svg)](https://github.com/guoquan/contextproxy/actions/workflows/release.yml)\n[![PyPI - Version](https://img.shields.io/pypi/v/contextproxy)](https://pypi.org/project/contextproxy/)\n[![GitHub License](https://img.shields.io/github/license/guoquan/contextproxy)](LICENSE)\n\n## Features\n\n- **Easy Access**: Resources can be accessed using decorated names, making them easy to use in your application.\n- **Lazy Initialization**: Resources are only initialized when accessed, saving computation and memory for unused resources.\n- **Automatic Teardown**: Resources are cleaned up automatically after the application context is torn down.\n- **Supports `Flask` Contexts**: The decorator works seamlessly with `Flask`'s request and application contexts, ensuring context isolation and cleanup.\n- **Thread Safety**: Ensures that resources are unique per thread in multi-threaded environments.\n\n## Installation\n\nYou can install `contextproxy` by including the file in your project directory or packaging it as a Python module.\n\n```bash\npip install .\n```\n\n## Usage\n\nTo 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.\n\nIt 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.\n\n### Basic Example\n\n```python\nfrom flask import Flask\nfrom contextproxy import contextproxy\n\napp = Flask(__name__)\n\n@contextproxy(app)\ndef resource():\n # Initialize the resource\n resource_value = \"This is a shared resource\"\n yield resource_value\n # Teardown logic (e.g., closing connections) goes here\n print(\"Resource has been cleaned up\")\n\n@app.route('/')\ndef index():\n return f\"Resource: {resource}\"\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n```\n\nIn 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.\n\n## Advanced Usage\n\n### Handling Exceptions in Resource Initialization\n\nIf your resource initialization involves risky operations (like database connections), you can handle exceptions cleanly within the resource function.\n\n```python\n@contextproxy(app)\ndef risky_resource():\n uuid = uuid4()\n print(f\"before: Preparing to create resource ({uuid})\")\n try:\n print(f\"yielding: Creating resource ({uuid})\")\n yield f\"resource {uuid=}\"\n print(f\"yielded: where is this? ({uuid})\")\n except Exception as e:\n print(f\"except: error processing resource ({uuid}): {type(e)}: {e}\")\n else:\n print(f\"else: okey processing resource ({uuid})\")\n finally:\n print(f\"finally: Destroying resource ({uuid})\")\n print(f\"after: Destroyed resource ({uuid})\")\n```\n\n## **Contributing**\n\nIf you\u2019d like to contribute to `contextproxy`, feel free to fork the repository, submit issues, or open a pull request!\n\n## **License**\n\nThis project is licensed under the MIT License.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "`contextproxy` provides context-based lazy-loaded proxy objects for flask apps.",
"version": "0.1.0.dev1",
"project_urls": null,
"split_keywords": [
"flask",
" context",
" proxy"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "cd78fe33a82ef13b1894a0289781e8f78b306bbca27ec03d4ccf382229dac21c",
"md5": "3aa1234332c1d1a981e09e9ac80908b3",
"sha256": "6f5b3f9a228d464258feaefc93864278656b23c0bab084c48e2c3476c2b17c01"
},
"downloads": -1,
"filename": "contextproxy-0.1.0.dev1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "3aa1234332c1d1a981e09e9ac80908b3",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 4816,
"upload_time": "2024-09-19T17:06:30",
"upload_time_iso_8601": "2024-09-19T17:06:30.633450Z",
"url": "https://files.pythonhosted.org/packages/cd/78/fe33a82ef13b1894a0289781e8f78b306bbca27ec03d4ccf382229dac21c/contextproxy-0.1.0.dev1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "9f2cfd10fb2899120edd8d58faffe2ccfac3b86b7d5cd945ecac38b9aa427601",
"md5": "9ad1bb2510af83b1512982a6daf64667",
"sha256": "db2c68fb79f57e173c312961f419e696396774be1584d8149fb84556b2ec9401"
},
"downloads": -1,
"filename": "contextproxy-0.1.0.dev1.tar.gz",
"has_sig": false,
"md5_digest": "9ad1bb2510af83b1512982a6daf64667",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 10692,
"upload_time": "2024-09-19T17:06:32",
"upload_time_iso_8601": "2024-09-19T17:06:32.160177Z",
"url": "https://files.pythonhosted.org/packages/9f/2c/fd10fb2899120edd8d58faffe2ccfac3b86b7d5cd945ecac38b9aa427601/contextproxy-0.1.0.dev1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-19 17:06:32",
"github": false,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"lcname": "contextproxy"
}