diff --git a/README.md b/README.md index 7877fb4e..a1b6fa41 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ This package provides analytics and distributed tracing for event-driven applica - [Chalice](https://github.com/iopipe/iopipe-python#chalice) - [Serverless](https://github.com/iopipe/iopipe-python#serverless) - [Zappa](https://github.com/iopipe/iopipe-python#zappa) + - [Accessing Context](https://github.com/iopipe/iopipe-python#accessing-context) + - [Contributing](https://github.com/iopipe/iopipe-python#contributing) - [Running Tests](https://github.com/iopipe/iopipe-python#running-tests) - [License](https://github.com/iopipe/iopipe-python#license) @@ -675,6 +677,20 @@ Then in your `zappa_settings.json` file include the following: Where `module-path.to.lambda_handler` is the Python module path to the `lambda_handler` you created above. For example, if you put it in `myproject/__init__.py` the path would be `myproject.lambda_handler`. +### Accessing Context + +If the framework you're using makes it non-trivial to access the Lamba context, you can use `iopipe.context`. The `iopipe.context` is `None` if outside of an invocation. + +```python +from iopipe import IOpipe + +iopipe = IOpipe() + +# Be sure to check, can be None +if iopipe.context: + # do something with context +``` + ## Contributing Contributions are welcome. We use the [black](https://github.com/ambv/black) code formatter. diff --git a/iopipe/agent.py b/iopipe/agent.py index 0cc279c9..78556a28 100644 --- a/iopipe/agent.py +++ b/iopipe/agent.py @@ -48,6 +48,7 @@ def __init__(self, token=None, url=None, debug=None, plugins=None, **options): self.config = set_config(**options) self.config["plugins"] = self.load_plugins(self.config["plugins"]) + self.context = None self.futures = [] self.pool = futures.ThreadPoolExecutor() self.report = None @@ -88,7 +89,7 @@ def __call__(self, func): def wrapped(event, context): logger.debug("%s wrapped with IOpipe decorator" % repr(func)) - context = ContextWrapper(context, self) + self.context = context = ContextWrapper(context, self) # if env var IOPIPE_ENABLED is set to False skip reporting if self.config["enabled"] is False: diff --git a/tests/test_agent.py b/tests/test_agent.py index a10a9d9a..5000ea2f 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -152,3 +152,16 @@ def test_disabled_reporting_with_error( handler(None, mock_context) assert iopipe.report.sent is False + + +@mock.patch("iopipe.report.send_report", autospec=True) +def test_context_attribute(mock_send_report, handler, mock_context): + """Assert that the current context is available as an iopipe attribute""" + iopipe, handler = handler + + assert hasattr(iopipe, "context") + assert iopipe.context is None + + handler(None, mock_context) + + assert iopipe.context is not None