add context manager features

This commit is contained in:
Andrew Herrington
2021-12-30 23:15:08 -06:00
parent 9f139177dc
commit 0606e83f19
10 changed files with 373 additions and 20 deletions

View File

@@ -19,6 +19,14 @@ Either the Client or AsyncClient can be used as a ContextManager (or Async Conte
This is probably the easiest way to use the Clients for one-off scripts. If you do not need to keep a client open for multiple requests, just use
the context manager.
.. note::
When using either of the client types as a context manager, the httpx client underlying the client will be closed when the context manager exits.
Since we allow you to pass in a client on creation, its possible to use a shared client with this library. If you then use the client as a contextmanager,
it will close that shared client.
Just a thing to be aware of!
Sync
----
@@ -95,3 +103,39 @@ If you want to use the client in an async program, use AsyncClient instead of Cl
check = await client.create_check(CreateCheck(name="New Check", tags="tag1 tag2")
print(check)
CheckTrap
---------
Ever wanted to run some code and wrape it in a healthcheck check without thinking about it?
That's what CheckTrap is for.
.. code-block:: python
from healthchecks_io import Client, AsyncClient, CheckCreate, CheckTrap
client = Client(api_key="myapikey")
# create a new check, or use an existing one already with just its uuid.
check = await client.create_check(CreateCheck(name="New Check", tags="tag1 tag2")
with CheckTrap(client, check.uuid):
# when entering the context manager, sends a start ping to your check
run_my_thing_to_monitor()
# If your method exits without an exception, sends a success ping
# If there's an exception, a failure ping will be sent with the exception and traceback
client = AsyncClient(ping_key="ping_key")
# works with async too, and the ping api and slugs
with CheckTrap(client, check.slug) as ct:
# when entering the context manager, sends a start ping to your check
# Add custom logs to what gets sent to healthchecks. Reminder, only the first 10k bytes get saved
ct.add_log("My custom log message")
run_my_thing_to_monitor()
# If your method exits without an exception, sends a success ping
# If there's an exception, a failure ping will be sent with the exception and traceback