frankie567 / httpx-ws

WebSocket support for HTTPX
https://frankie567.github.io/httpx-ws/
MIT License
102 stars 12 forks source link

Client instances not closed. #15

Closed tomchristie closed 1 year ago

tomchristie commented 1 year ago

When using connect_ws() or aconnect_ws(), if you don't pass a client instance, then a new client instance is created, but remains unclosed once the call returns.

It's a little awkward to get right, but the safest approach is to stick with with ... blocks for handling open/close of resources:

@contextlib.contextmanager
def connect_ws(...):
    if client is None:
        with httpx.Client(...) as client:
            yield _connect_ws(..., client=client)
    else:
        yield _connect_ws(..., client=client)

@contextlib.contextmanager
def _connect_ws(...):
    # main body of `connect_ws()`, but with a *mandatory* client argument.

Although you can also handle it with try...except:

@contextlib.contextmanager
def connect_ws(...):
    should_close_client = False
    if client is None:
        client = ...
        should_close_client = True

    try:
        ... # main body of connect_ws()
    finally:
        if should_close_client:
            client.close()  # We only want to do this if we've created the client instance ourselves
frankie567 commented 1 year ago

Oh, of course! I'll fix this 😄